Workflows¶
Every Monday the #growth channel gets a digest of last week's numbers:
signups, churn, churn by plan, and a few lines on what moved. Pulling the
numbers is a fixed query and should run exactly as written. Writing the
summary needs a model. A scheduler starts it at 9am, and sometimes Alice asks
for it in a thread for an older week.
That job is a workflow: an ordered pipeline of typed steps, where the pipeline is code and the model reasons inside one step.
The pipeline in code¶
from pydantic import BaseModel, Field
from mash import AgentStep, CodeStep, StepContext, WorkflowSpec
class WeeklyMetricsRequest(BaseModel):
week_start: str = Field(description="The Monday the week starts on, as YYYY-MM-DD")
class MetricsSnapshot(BaseModel):
week_start: str
signups: int
churn_rate: float
churn_by_plan: dict[str, float]
class MetricsDigest(BaseModel):
summary: str
highlights: list[str]
def pull_metrics(request: WeeklyMetricsRequest, _context: StepContext) -> MetricsSnapshot:
row = weekly_metrics(request.week_start)
return MetricsSnapshot(week_start=request.week_start, **row)
WEEKLY_METRICS = WorkflowSpec(
workflow_id="weekly-metrics",
input_model=WeeklyMetricsRequest,
metadata={
"display_name": "Weekly metrics digest",
"description": "Pulls one week's signups and churn and writes a digest.",
},
steps=[
CodeStep(step_id="pull", run=pull_metrics,
input=WeeklyMetricsRequest, output=MetricsSnapshot),
AgentStep(step_id="digest", agent_id="analyst",
input=MetricsSnapshot, output=MetricsDigest),
],
)
A CodeStep is a Python function, sync or async. An AgentStep is one run
of a registered agent's loop. Every step declares a pydantic input and output,
and the last step's output is the run result. The steps list is the control
flow: a reviewer reads it in one place, a unit test calls pull_metrics
directly, and a change to the pipeline is a diff.
Workflows register on the host next to agents with .workflow(WEEKLY_METRICS),
and the companion can route a message to one. A host can be workflows alone: a workflow of pure CodeSteps references no
agents, and HostBuilder().workflow(spec).build() with no .agent() calls
serves only workflow runs.
Output threading¶
Each run starts from workflow_input, the payload the trigger supplied, typed
by input_model and fixed for the whole run. Before each step, the framework
merges the previous step's output over workflow_input and coerces the result
into the step's input model.
flowchart LR
WI["workflow_input\n{week_start}"] --> S1["pull\nCodeStep"]
S1 -- "MetricsSnapshot merged\nover workflow_input" --> S2["digest\nAgentStep (analyst)"]
S2 --> R["run result\nMetricsDigest"]
WorkflowSpec checks the pipeline when the host is built. Step ids must be
unique, both edges of every step must be typed, and with input_model set the
check goes field by field, so a step that expects a field no earlier step
provides fails before anything deploys.
The agent step¶
The analyst's request for the digest step gets a JSON message with a fixed
shape:
{
"workflow_id": "weekly-metrics",
"workflow_run_id": "mw:…",
"step_id": "digest",
"workflow_input": { "week_start": "2026-11-16" },
"input": { "week_start": "2026-11-16", "signups": 412, "churn_rate": 0.021,
"churn_by_plan": { "pro": 0.012, "team": 0.034 } }
}
The step's output becomes the request's
structured output schema, and the validated payload is
the next step's input. output takes a pydantic model or a JSON-schema dict.
An optional skill_name tells the agent to load that
skill before the step's work, which keeps long task
instructions in skill markdown.
The request runs on the agent directly, without the companion and without a
board. It starts from the agent's system prompt and this message, so every
run is self-contained. Inside the step the model reasons, calls tools and may
use the policy's sandbox; none of that changes the pipeline. An AgentStep
can also carry its own agent_spec, which the builder registers as a
workflow-only agent, hidden from listings and never routed to.
App and policy¶
A run acts for an app under a policy:
curl -X POST http://127.0.0.1:8000/api/v1/workflow/weekly-metrics/run \
-H "Content-Type: application/json" \
-d '{"app_id": "growth", "policy_id": "growth", "input": {"week_start": "2026-11-16"}}'
Both are required when the workflow has an AgentStep, or a CodeStep that
declares agent_ids. The run stores them with a snapshot of the policy, and
every agent step submits under them, so the analyst's code runs in the
growth sandbox. StepContext.app_id, .policy_id and .policy expose them
to code steps. Runs have no session and take no session queue, so the Monday
digest never waits behind a thread.
The same workflow is reachable from a conversation. When Alice writes
run the weekly metrics digest for the week of Nov 9 in a thread, the
companion picks weekly-metrics, fills week_start from the
message with a second structured output call, and asks for it if the message
doesn't say. It runs the workflow under the event's app and policy, replies
with the outcome, and writes one board entry with the run's input and result.
The run's steps never read or write the board.
Durability and resume¶
The host runs each run as a task. A run's durable state is its rows in the workflow tables: every step records its input and output, so a run that stopped continues by skipping its completed steps and feeding their stored outputs forward. When the host starts, it continues the runs it left queued or running.
Execution is at least once: a step interrupted mid-flight runs again. A pure
transform reruns safely. A step with external effects dedupes on a stable key
from StepContext, which hands it run_id, step_id, workflow_input and
attempt. The attempt stays the same when the host died in the step, and goes
up when a failed step is resumed. The framework never invents an idempotency
key for the author.
An agent step's request id is derived from the run, the step and the attempt.
After a host restart the step reattaches to its request and continues it mid
loop. resume_run puts a failed or cancelled run back in the queue under the
same run id, and the resumed step's new attempt starts a new request. A
completed run is rejected with a 409.
A step may declare timeout_s; exceeding it fails the step. A sync CodeStep
body runs in its own thread, which can't be stopped, so the step fails at the
deadline while the body runs on until it returns. A resume can start the step
again before the old body finishes, which is one more reason to key its
effects on ctx.run_id and ctx.attempt.
A dedup_key on submission is unique among a workflow's queued and running
runs, so a second trigger while a run is active is rejected. That makes
workflows safe to fire from schedules and webhooks.
The audit trail¶
Three tables belong to the workflow layer. workflow_runs holds one row per
run with status, workflow_input, result, app, policy and timing.
workflow_steps holds one row per step with status, input and output
snapshots, the attempt count, and the agent_request_id for agent steps.
workflow_step_events is an append-only lifecycle record keyed by run, step,
attempt and event type, which makes code steps observable, since a Python
function emits no runtime events of its own.
POST /api/v1/workflow/{id}/run returns a run_id, and
GET .../runs/{run_id}/events streams agent-step runtime events and
code-step lifecycle events over SSE, the same frames as an event's stream. In
the REPL, /workflow run weekly-metrics runs under the connection's app and
policy and streams the pipeline, and /workflow status and
/workflow resume cover the rest. When a digest comes out wrong, the trail
shows what pull returned and what the analyst received.
Fan-out¶
A pipeline is a straight line. Dynamic control flow, such as fan-out over
rows or branching, lives inside a CodeStep body, deduped on stable keys
from StepContext. Masher's experiment runner works
this way: its execution and judging steps fan out over a durable row ledger
inside a code step. Masher's other built-in workflows, and
Cortex's cortex-build, are pipelines on the same
layer.
That ends the architecture series. The next posts cover what an agent is built from, starting with the contract every model provider speaks.
Next: One LLM Contract.