workflow
v0.3.14Deterministic, crash-resumable multi-agent workflow orchestrator over harness turns.
Install
iii call compose::add worker=workflowRun in your project with the iii engine running. Exact versions are immutable and digest-pinned.
workflow worker
A deterministic DAG orchestrator running over the iii harness. Accepts
workflow::start / workflow::stop / workflow::pause /
workflow::resume / workflow::skip calls; persists run
state in state; fans out nodes as child harness sessions with deterministic
ids so duplicate deliveries are idempotent.
The always-on harness observers (harness::on-turn-completed → wake,
harness::hook::on-pre-call → stamp-reply, harness::hook::on-post-turn →
validate-result, harness::hook::on-pre-generate → inject-result-contract)
are created once at startup. An
observer created before the harness is up stays pending and becomes active
when the harness registers its function, and again after a harness restart.
workflow::start is registered at boot, but answers "not ready, retry" until
the stamp-reply observer is active, or until 10 s passed while the harness is
absent, so an agent's call cannot run unstamped while the worker boots. If the
harness refuses the stamp-reply hook, at boot or when it starts or restarts
later, workflow::start refuses every call with the reason until a worker
restart after the fix.
The last — harness::hook::on-pre-generate → inject-guidance — follows the
inject_guidance knob in the workflow configuration entry (ON by default):
turning it off shrinks prompts (the harness's # Granted functions catalog
still advertises the workflow::* ids) and the worker observes or disposes it
hot, no restart.
Getting the result back (don't poll)
workflow::start returns a run_id immediately. There are a few ways to learn
the outcome; prefer push over polling workflow::status in a loop.
Observe the run (for an AGENT caller). For a call from an agent turn,
workflow::startreturns{run_id, next}.nextis theharness::observecall that wakes your session when the run ends. Make it exactly as given, then end your turn:// workflow::start returns { "run_id": "r_…", "next": { "call": "harness::observe", "arguments": { "function_id": "workflow::on-run-completed", "args": { "run_id": "r_…" }, "label": "workflow r_…", "action": "Workflow finished: <title>", "lifecycle": { "expires_in_ms": 82800000 } }, "then": "END YOUR TURN after this call; …" } }The outcome arrives as
[notification] workflow r_…: {…}, at once if the run already ended: the worker replays a finished run to an observer of it. The wake expires an hour before the run is collected (24 h after it ended), so an expired wake can observe again and still get the replay; a collected run is refused withUNKNOWN_RUN. A notification cut at the harness's 8,000-character limit is incomplete: callworkflow::statusonce for the run.nextis present only when the pre-call hook stamped your session; you pass no session id. A session whose policy narrowsoptions.functionsmust allowharness::observeandworkflow::on-run-completed.reply_towas removed: a start that passes it is refused with this recipe.Completion callback (push), for a WORKER caller. Pass
notifytoworkflow::start. When the run reaches a terminal state the worker calls your function once with{run_id, status, result, result_error, failed_nodes?}(failed_nodesis omitted when no node failed; see Events):workflow::start { "nodes": { /* ... */ }, "input": { /* ... */ }, "notify": { "function_id": "myworker::wf-done" } // optional "queue", defaults to "workflow-notify" }Delivery is durable (enqueued) and at-least-once — make the handler idempotent and dedup on
run_id. This is the push path; no polling. The worker defines itsworkflow-notifyqueue at boot, apart from theworkflowtick queue, so a slow callback cannot delay ticks; a customqueuemust already be defined withqueue::define. A start from an agent turn (one the pre-call hook stamped with a session) that passesnotifyis refused: the callback runs outside every node policy, so an agent usesnextinstead.Observe every run. Every terminal run also calls
workflow::on-run-completed. Observe it without args to see all runs, e.g. for audit (see Events); to wait for one run, pass args{ run_id }instead.iii.observe( { function_id: 'workflow::on-run-completed', filters: { 'input.status': { $eq: 'failed' } }, capture: ['output'] }, 'audit::workflow-failed', )
workflow::status remains for one-off inspection, but a live tracker should
observe the run (agents: the next call) or pass notify (workers) rather than
run a status loop.
The request
workflow::start takes one level of nodes:
{"input": {"topic": "durable workflows"},
"nodes": {
"research": {"task": "List the key findings on the topic.",
"schema": {"type": "object", "properties": {"findings": {"type": "array", "items": {"type": "string"}}},
"required": ["findings"]}},
"report": {"reads": "research", "task": "Write a one-page report from these findings."}}}The worker refuses an unknown key at either level, and lists every shape
problem of a request in one refusal. A key whose value is null counts as
omitted. The removed shape (definition, agent, input.from, depends_on,
fanout.over, output.from, the node: prefix) is refused with the recipe
for each moved key.
| Top-level key | Default | Meaning |
|---|---|---|
nodes |
required | One sub-agent session per node (a function node runs a function instead), keyed by node id. An id has no #, . or /. |
input |
null |
Any JSON. Every node without reads or fanout receives it. |
output |
every unread node | A node id returns that result as is; an array of ids returns an object keyed by id. An unread node is one no other node names in reads, fanout or when: one returns its result as is, several an object keyed by id. A loop node or a loop body node returns its last pass; see Loops. |
max_concurrency |
default_max_concurrency in the workflow configuration entry; unset, the worker host's parallelism minus 2 (1 to 16) |
Live node sessions at once (running, or reserved for a send); further ready nodes queue for a slot. At least 1. Start writes the value into the run's stored definition, so a change to the configuration key reaches new runs only, and a run stored before this default keeps no cap. A sub-run a node starts gets its own cap, not a share of its parent's. |
default_functions |
everything except workflow::*, configuration::*, approval::*, harness::hook::* and harness::send |
Dispatch policy of every node without functions. From an agent turn it is narrowed to what the caller session may call; see The node policy below. |
idempotency_key, notify |
none | See Getting the result back. |
title |
the call's description | Display title of the run, returned by workflow::list and workflow::status. Trimmed and cut to 80 characters; blank counts as omitted. When an agent omits it, the pre-call hook fills it from the description the agent gave its workflow::start call. A repeated idempotency_key returns the original run with its original title. |
from_run |
none | Id of an ended run (completed, failed or cancelled) whose finished nodes this run reuses instead of running them again; see Reusing an earlier run. Blank counts as omitted. |
max_total_tokens, max_cost_usd |
none | A ceiling on the tokens (an integer, at least 1) or the US dollars (a number above 0) that every node session of the run and its sub-agents may spend; see Run budget. |
| Node key | Default | Meaning |
|---|---|---|
task |
required unless call |
The node's opening message. Its input follows as JSON, fenced as untrusted data. |
reads |
the run input |
A node id delivers that result as is (a text node as a JSON string, a fanout node as the array of its copies' results); "<id>.<path>" delivers one field of that node's JSON result, see Reading one field; an array delivers an object keyed by each entry as written. The node runs after them. |
fanout |
none | One copy per element of an array; see Fanout. |
schema |
text node (a function node: unchecked JSON) | JSON Schema, with a top-level type, of the JSON value the node delivers. Required on a session node a fanout or reads path points at and on a loop node. On a function node it describes the {"value": …} object, so its type must be "object". |
model |
the caller's model | A model id from router::models::list; an unregistered id is refused at start. |
provider |
the routed provider | Only with model or profile. |
profile |
none | Agent profile id (lowercase letters, digits, - and _, at most 64 characters) sent as the harness options.agent. It excludes system_prompt, and a model it pins wins over model. |
system_prompt |
none | Appended to the child's built-in identity prompt. |
functions |
default_functions |
The node session's dispatch policy: an allow-list array or { "allow", "deny" }. List a denied id to give it back; a node that starts a sub-run lists both workflow::start and workflow::on-run-completed. From an agent turn it is narrowed to what the caller session may call; see The node policy below. |
filesystem_root |
the caller's folder | Absolute folder the node's session runs in. It must lie inside the caller's folder with symlinks resolved, checked once at start on the worker's host; a run without a caller folder cannot set it. Fanout copies and loop passes share it. |
timeout_ms |
default_pending_timeout_ms (30 min) |
Wall clock an attempt may run, from its send, not counting time a call of the attempt's session, or of a direct sub-agent, waits in an approval hold. At least 1000. |
retries |
max_node_retries (1) |
Refires after a timeout, each in a new @r<n> session. At most 10. A failed turn is not refired; see read_only. |
read_only |
false |
true states that the node has no side effects, so a turn that fails on a transient provider failure is continued once in its own session; see Transient provider failures. The worker does not check it. |
on_error |
"fail" |
"continue": a failed or cancelled node counts as finished with a null result, so its readers run and the run can complete. The error stays in node_errors. |
effort |
the profile's reasoning_effort, else the provider default |
Reasoning effort of the node's session, 1 to 80 characters, trimmed. default (any case) means unset, as in a profile. off, minimal, low, medium, high and xhigh (any case) are sent as the harness options.thinking_level; the provider maps a level the model does not support (for example off only where the model can turn thinking off). Any other string (max, ultra, …) is provider-native and is sent as options.provider_options.<provider>.reasoning_effort under the node's provider: the written provider, or the caller's provider a node without profile inherits with the caller's model. When the node has none (a profile node, a written model without provider, or a caller whose provider is unknown), start refuses the run; set provider, and model on a node without profile. Fanout copies, loop passes and retries keep it. On a profile node it overrides the profile's reasoning_effort only on a harness with the MOT-6007 precedence change; on an older harness the profile's effort wins. A node without profile, or whose profile sets no reasoning_effort, gets it on any harness. |
label |
none | Session title (fanout copies get #<i>, loop passes #it<k>, a copy in a pass #it<k>#<i>) and node_details.label. 1 to 80 characters. |
phase |
none | Group counted in workflow::status phases. 1 to 80 characters. |
loop |
none | Repeat this node and its body while a condition on a field of its result holds; see Loops. |
when |
none | Run the node only when a condition on another node's result holds, in loop.while's shape with the node id first: {"field": "triage.risk", "equals": "high"}. Otherwise the node is skipped; see Conditional nodes. |
skip_if_read_skipped |
false (implied on a call node outside a loop, where false does not turn it off) |
true: the node is skipped too when a node it reads or gates on was skipped, so a skip passes down a chain. |
call |
none | {"function_id": "fp::…", "args": {…}} in place of task: the node runs an fp transform on its input instead of a session, and is skipped when a node it reads was skipped; see Function nodes. |
The model. A node that omits model and provider runs on the caller's
model, read once at start from the caller session's harness::status
context and written into the stored definition, so retries, loop passes and
fanout copies stay on it. It also takes the caller's provider, unless it has a
profile. With no caller session, or an unreadable model, a node without a
profile is refused; a profile node then runs on the profile's pinned
model. With output omitted, every unread node is required: a failed side
node fails the run unless it sets on_error: "continue".
The node policy. A node never gets more than its caller may call. On a
start from an agent turn the worker reads the caller session's dispatch policy
(options.functions of its harness_turn record) once and narrows every
node's policy to it: each allow entry is intersected with the caller's allow
(shell::* with shell::exec gives shell::exec, laptop/* with * gives
laptop/*), and the caller's denies are added. A node that starts a sub-run
keeps workflow::start and workflow::on-run-completed only when the caller
may call them, and a nested run is narrowed to its node's narrowed policy.
Entries that overlap without one containing the other (shell::ex* and
shell::exec) are dropped. A JSON node still gets workflow-result::submit;
a start whose caller denies it, while the run has a JSON node, is refused.
When that policy cannot be read the start is refused. A worker or CLI caller
has no session policy, so its nodes are not narrowed.
Fanout
A fanout node runs one copy per element of an array.
fanout |
The array | Copies start |
|---|---|---|
"plan.items" |
The items array of plan's JSON result, read once. |
When plan and every node in reads are settled. |
["security","cost"] |
The array as written. | When every node in reads is settled; without reads, at once. |
| The node has | A copy receives |
|---|---|
fanout only |
its element |
fanout and reads: "draft" |
{"input": <draft's result>, "fanout_item": <its element>} |
fanout and reads: ["draft","spec"] |
{"input": {"draft": …, "spec": …}, "fanout_item": <its element>} |
input is what a plain node with the same reads receives. A copy never
receives the run input. The node's result, for its readers and output, is
the array of its copies' results in element order (the order written, for a
written array); a failed copy of an on_error: "continue" node reads as
null. A fanout cannot iterate another fanout's result: flatten it with a
function node, or read it with a join node that returns one
array. In a loop body a fanout runs again in each pass; see Loops.
Several critics, each with an angle, over one draft:
{"input": {"feature": "..."},
"nodes": {
"draft": {"task": "Write a one-page design note for the feature."},
"critic": {"fanout": ["security", "cost", "operability"], "reads": "draft",
"task": "Criticize the draft in `input` from the angle in `fanout_item`. List concrete problems."},
"final": {"reads": ["draft", "critic"], "task": "Revise the draft. Fix every valid problem in `critic`."}}}Three critic copies start when draft is done; final receives
{"draft": "<the draft>", "critic": ["…", "…", "…"]} and is the run's result.
Reading one field
"reads": "plan.summary" delivers the summary field of plan's JSON
result; more segments walk nested objects ("plan.meta.owner"). A path walks
object fields only: an array index such as "plan.steps.0" is not supported
and reads null. The first segment is the node, which still runs first. In an array of reads the key is
the entry as written: "reads": ["plan.summary", "brief"] delivers
{"plan.summary": …, "brief": …}.
- At start: the node needs a
schema, as for a fanout path (a text node has no fields; a function node without one is read unchecked), must not be a fanout node (its result is an array), and aschemait has must declare every segment underproperties. A level withoutproperties, or withadditionalProperties,anyOf,$refand the like, is not checked. - At run time a field the result lacks, or a value on the way that is not
an object, delivers
null, as does a node that failed withon_error: "continue". Unlike a fanout path, it never fails the node. - A loop node read from outside its loop delivers the field of its last pass.
JSON nodes
A JSON node (one with schema) runs under the harness's text contract, so its
session has no submit_result tool. Its system prompt carries the result
contract: the schema, and the instruction to deliver the result by calling
workflow-result::submit with {"result": <value>}.
workflow::inject-result-contract, a pre-generate hook on node sessions,
appends it on every generation of the node's live attempt, so the opening
message is only the task and its input; the value is checked against the schema, and an
invalid one is refused with the cause so the node calls again.
workflow::validate-result observes the harness's post-turn hook for node
sessions: a turn that submitted passes, and so does a final message that is
itself a valid JSON value (one fenced code block is tolerated); anything else
is denied with the cause and the schema, so the harness re-prompts the turn,
at most max_validation_retries times. A turn that ends with a wake armed
(harness::status reads expects_wake) passes whatever it says, so a node can
park on a status line and answer on the woken turn. A node that submitted
settles when its turn ends, even with a wake armed, or at its timeout_ms
when the turn is still running then: done with the submitted result, never
refired or failed with node_timeout. The worker then stops its
session tree: armed wakes are disposed, and background shell jobs and child
sessions are killed. A node that must wait for a wake submits on the woken
turn. A node that must leave a background job running ends with no wake armed.
When the node settles, reconcile checks its result again and stores the parsed
value. A result that does not parse or match (a turn the hook did not check,
for example while this worker restarted) gets the same correction sent into the
node's session, at most twice per attempt; then the node fails. The failed
node's error (node_errors, the run's result_error) names the cause without
the schema. workflow::start rejects a schema that does not compile.
Provider-native structured output is not used for a node, even on a model that
supports it: the schema is checked after the answer, not enforced while the
model writes it. The node session's harness result (harness::status result,
harness::on-turn-completed, the result any other post-turn validator on
that session receives) is the answer text; the parsed value is only in
workflow::status and workflow::node-result.
There is no separate finish signal: with no wake armed, a final message that
parses and matches the schema settles the node. A node that may park needs a
schema with required fields a status line cannot satisfy. Under
{"type": "object"} alone, or any schema with no required, a status object
such as {"status": "waiting on build"} sent after a refused
harness::observe becomes the node's result.
Function nodes
A node with call in place of task runs an fp value transform on its input
inside the tick: no session, no model, no tokens. It does the plain code
between agents: drop nulls, dedupe, flatten, count votes.
"dedupe": {"reads": "find", "call": {"function_id": "fp::uniqBy", "args": {"path": "/id"}}}- Input. The function receives
call.argsplus"value": <the node's input>: what a session node with the samereads,fanoutorloopreceives. fp's transforms take their input atvalue, socall.argsmust not hold one. at. A JSON pointer into that input (""or starting with/), or a non-empty array of them.valuethen carries the value there, or for an array the array of the values, in order; a pointer that finds nothing givesnull. A body node of a loop receives{"input", "loop_previous", "own_previous"}(the loop node has noown_previous) and a fanout copy withreads{"input", "fanout_item"}, so"at": "/input"hands a transform the array itself.- Result. The function's response as is:
{"value": <the transformed value>}for a transform. Readers pick the field:"reads": "dedupe.value","fanout": "flat.value", a loopwhileon"field": "value…". The result counts as JSON without aschema; with one it is checked against it, with the validatorworkflow-result::submituses. The schema describes the whole response, so it is an object schema with the value underproperties.value, for example{"type": "object", "properties": {"value": {"type": "array"}}}; start refuses a top-leveltypeother than"object". A null response, one that failsschema, or one over the 1 MiB result cap fails the node. - Keys. Beside
call:reads,fanout,schema,loop,on_error,when,skip_if_read_skipped,label,phase.task,model,profile,provider,system_prompt,functions,filesystem_root,timeout_ms,retries,read_onlyandeffortare refused. - Skips. A function node is skipped when a node it reads or gates on was
skipped, as if it set
skip_if_read_skipped: true, since a transform cannot take thenullthat node delivers;skip_if_read_skipped: falsedoes not turn this off. In a loop it is not: it readsnullfor the skipped node and a transform that needs an array fails on it, as a node of a loop cannot be skipped, so the run fails unless the node hason_error: "continue". - Which functions. fp value transforms only, the ones that answer
{"value": …}(fp::compact,fp::flatten,fp::uniqBy,fp::countBy, …), since the call skips the approval gate and every pre-call hook.fp::pipe,fp::batch,fp::when,fp::condition, every other fp function and other workers' functions are refused at start; chain function nodes for several steps. From an agent turn the caller session must be allowed to call the function (an allow entry matches and no deny does), or the start is refused. A namespaced entry such aslaptop/fp::*never grants the call and, as a deny, always refuses it, since the run's namespace is not known at start. A function no worker registered is refused at start, as an unknown model is, so the fp worker must be installed. - Failure. A call that errors, or runs longer than
dispatch_timeout_ms, fails the node at once: there is no retry, andon_errorapplies as for any node. A function node holds nomax_concurrencyslot and adds nothing to the run'susage. It settles in the tick that finds it ready; its readers start on the next tick.
A vote tally over three refuters:
{"nodes": {
"claim": {"task": "State the claim in the run input as one sentence."},
"refute": {"fanout": ["r1", "r2", "r3"], "reads": "claim",
"task": "Try to refute the claim in `input`; `fanout_item` names your attempt.",
"schema": {"type": "object", "properties": {"verdict": {"enum": ["refuted", "holds"]}},
"required": ["verdict"]}},
"vote": {"reads": "refute", "call": {"function_id": "fp::countBy", "args": {"path": "/verdict"}}}}}vote delivers {"value": {"refuted": 2, "holds": 1}}. It counts and does
not decide: no fp transform picks the top key, so the node that reads the
counts (or the caller) takes the majority from them.
Findings deduped by key before one node fixes them:
{"nodes": {
"find": {"task": "List the problems, each {\"id\", \"text\"}.", "schema": {"type": "array"}},
"dedupe": {"reads": "find", "call": {"function_id": "fp::uniqBy", "args": {"path": "/id"}}},
"fix": {"reads": "dedupe.value", "task": "Fix every problem."}}}fp::uniqBy keeps the first element per id; "path": "" compares whole
elements, as fp::uniq does.
Parallel finders, repeated until a pass finds nothing new. Each pass dedupes its findings, drops those an earlier pass found, and verifies only the fresh ones:
{"nodes": {
"find": {"fanout": ["security", "performance", "api"],
"task": "Find problems from the angle in `input`, each {\"id\", \"text\"}. loop_previous.value.known.value lists what earlier passes found.",
"schema": {"type": "array"}},
"flat": {"reads": "find", "call": {"function_id": "fp::flatten", "at": "/input"}},
"uniq": {"reads": "flat.value", "call": {"function_id": "fp::uniqBy", "args": {"path": "/id"}, "at": "/input"}},
"prev": {"call": {"function_id": "fp::getOr", "args": {"path": "/loop_previous/value/known/value", "default": []}}},
"fresh": {"reads": ["uniq.value", "prev.value"],
"call": {"function_id": "fp::differenceBy", "args": {"path": "/id"},
"at": ["/input/uniq.value", "/input/prev.value"]}},
"verify": {"fanout": "fresh.value", "task": "Check this finding."},
"known": {"reads": ["prev.value", "fresh.value"],
"call": {"function_id": "fp::flatten", "at": ["/input/prev.value", "/input/fresh.value"]}},
"count": {"reads": "fresh.value", "call": {"function_id": "fp::size", "at": "/input"}},
"state": {"reads": ["known", "count", "verify"], "call": {"function_id": "fp::get", "args": {"path": "/input"}},
"loop": {"body": ["find", "flat", "uniq", "prev", "fresh", "verify", "known", "count"],
"while": {"field": "value.count.value", "gt": 0}, "max_repeats": 5}}}}prev is [] in the first pass (loop_previous is null, so the pointer
misses) and the known list of the pass before in every later one. fresh
keeps the findings prev does not list (fp::differenceBy), verify runs
one copy per fresh finding, and known adds them to the list. The loop node
state delivers {"value": {"known": {"value": […]}, "count": {"value": n}, "verify": […]}}; a pass with no fresh finding has no verify copy and a
count of 0, which ends the loop. state reads verify because every body
node must feed the loop node. A node after the loop reads
state.value.known.value.
A fanout over the files every copy of another fanout listed:
{"nodes": {
"scan": {"fanout": ["src", "docs"], "task": "List the files of this folder.",
"schema": {"type": "array", "items": {"type": "string"}}},
"flat": {"reads": "scan", "call": {"function_id": "fp::flatten"}},
"each": {"fanout": "flat.value", "task": "Review this file."}}}scan delivers [["a.rs", "b.rs"], ["README.md"]], flat delivers
{"value": ["a.rs", "b.rs", "README.md"]}, and each runs one copy per file.
On on_error: "continue" a failed scan copy reads as null; drop it first
with fp::compact.
Transient provider failures
The harness resumes a turn whose provider fails temporarily (an outage, a rate
limit, a cut stream) up to max_transient_resumes times in a row, waiting
2 s, 8 s and then 30 s before each resume (a successful generation resets the
count), and then fails the turn with failure.retryable: true on harness::status. A node with
read_only: true whose turn fails that way is not failed: it stays running,
and at least 60 s later the worker sends one continue message into the same
session, so the transcript and the provider's prompt cache carry over and the
work already done is not paid again. The continue asks the node to resume where it stopped,
without repeating calls that already returned, and to deliver its result.
- Once per node uid, over all its attempts: each fanout copy and loop pass has
its own, and a timeout refire does not give a new one. A second transient
failure fails the node, and so does any failure of a node without
read_only. - The continue runs in what is left of
timeout_ms, which still counts from the attempt's send (less time in approval holds), and needs at least 5 minutes of it when sent: it reloads the whole transcript, so a continue the timeout stops at once would be paid for nothing. With less than 7 minutes left at the failure (the wait, one default sweep period and those 5 minutes), the node fails at once instead. A pass that reaches the due continue with less than 5 minutes left (a slowersweep_expression, say) fails the node with the transient error instead of sending it. - Before sending, the worker reads the session again: a session that moved on (a person typed into it, say) is settled as usual instead. With a caller session, every pass reads the caller while a node waits: a stopped caller turn stops the run, and an unreadable caller holds the continue for the next pass.
- The transient error never reaches
node_errorsunless the continue fails too; withon_error: "continue"only that final failure reads asnull. - An older harness, which reports no
failureonharness::status, makes every failed turn fail the node.
Run budget
max_total_tokens and max_cost_usd cap the whole run, every node session and
its sub-agents, with one harness budget ledger, wf:<run_id>. Without them a
run behaves as before.
- Every opening send of a node session joins the ledger with the run's limits
in
options.budget_ledger: each fanout copy, loop pass and timeout refire, and a probe that re-sends. A function node, a skipped node and a node reused fromfrom_runspend nothing. A sub-agent inherits its parent's ledger, and a correction or continue message goes into a session that already has it. The harness accepts that option from the workflow worker only, so an agent cannot leave its cap. - The harness checks the ledger before each generation and reserves its worst
case, the context plus the model's maximum output, then charges what it
used. Parallel nodes reserve at once, so a run can stop well before
usedreaches the limit: give it room formax_concurrency× (context + maximum output), or lowermax_concurrency. A failed provider call keeps its reservation. Withmax_cost_usd, a node whose model has no pricing fails. - A node whose turn ends on the budget (
failure.codeharness.budget_exceededonharness::status) fails withrun budget exceeded: <the harness's text>, even with a wake armed oron_error: "continue". The run then stops its remaining nodes, asworkflow::stopdoes, and fails with aresult_errorthat names the limits, what the ledger used of each, and the node:run budget exceeded: max_total_tokens 200000 (used 187344); node 'review#2': generation requires up to 24000 tokens, but only 12656 remain in the shared 200000-token budget.(used …)is left out when the ledger cannot be read. A node that delivered its result before its turn hit the budget settlesdone; the next generation of any node stops the run. - In such a run no node may call
workflow::startorharness::send: both are added to every node'sdeny, whatever itsfunctionsallows, since a nested run or a session it sends to would spend outside the ledger. workflow::startasks the harness for budget ledgers first (harness::budget::deleteofwf:probe) and refuses a capped run when the harness lacks them or does not take the join from this worker: an older harness would ignore the option. The worker must run under the nameworkflow.workflow::statusreturns the limits and the ledger inbudget. The ledger stays until the sweep collects the run, 24 h after it ends, and is deleted with it.- A repeated
idempotency_keyreturns the original run with its original limits.
Conditional nodes
when runs a node only when a condition on another node's JSON result holds:
"triage": {"task": "Rate the change's risk.",
"schema": {"type": "object",
"properties": {"risk": {"type": "string", "enum": ["low", "high"]}},
"required": ["risk"]}},
"review": {"task": "Review the change adversarially.", "reads": "triage",
"when": {"field": "triage.risk", "equals": "high"}},
"report": {"task": "Write the report.", "reads": ["triage", "review"]}whentakes a loop'swhileshape and operators (equals,not_equals,in,lt,lte,gt,gte,is; see Loops). Itsfieldstarts with the node it reads,"<id>.<path>"; the node runs after that one. That node must not be a fanout node and must have aschema; the start checks the field against it as it checkswhile.field: the schema must declare it with a type the operator compares, and list it inrequired.- When the condition does not hold, the node settles as
skipped: no session, no retry, no error, no usage. A producer without a result (failed underon_error: "continue", or itself skipped) does not hold either.skippedis not a failure: a run whose nodes are alldoneorskippedcompletes. - A skipped node's readers receive
null(in an array of reads and inoutput, under its key). Withskip_if_read_skipped: truea reader is skipped instead, so"discover"→"plan"(when count gt 0) →"apply"(skip_if_read_skipped) ends the run at once whendiscoverfinds nothing. A fanout over a skipped node is always skipped, and so is a function node outside a loop that reads one:nullhas no elements, and a transform cannot take it. - A skipped output node makes a completed run's
resultnull, as a failed one underon_error: "continue"does;workflow::statustells them apart. A node only awhenreads is not unread, so name it inoutputto keep its result (["discover", "apply"]above). - A fanout node with
whenis gated once as a whole: skipped, it has no copies and its readers receivenull, not[]. - If/else is two nodes with opposite conditions (
equals/not_equals,is: true/is: false); a join that reads both receivesnullfor the branch that did not run. - A node of a loop cannot declare
whenorskip_if_read_skipped. A node outside the loop may gate on the loop node: it waits for the last pass.
Loops
A loop on a node (the loop node) runs it and its body nodes again while a
condition on a field of its JSON result holds, as a do-while:
"work": {"task": "Implement the ticket; fix every finding in loop_previous.", "profile": "deepwork-impl",
"on_error": "continue"},
"verify": {"task": "Review the work.", "profile": "deepwork-adversary", "reads": "work", "on_error": "continue",
"schema": {"type": "object",
"properties": {"verdict": {"type": "string", "enum": ["pass", "reject"]},
"findings": {"type": "array", "items": {"type": "string"}}},
"required": ["verdict", "findings"]},
"loop": {"body": ["work"], "while": {"field": "verdict", "equals": "reject"}, "max_repeats": 2}},
"report": {"task": "Report the outcome.", "reads": "verify"}whileisfield, a dotted path into the loop node's result, and exactly one operator:Operator The loop repeats while the field is "equals": "reject"this string "not_equals": "pass"a string other than this one "in": ["reject", "partial"]one of these strings "lt","lte","gt","gte": a numbera number below, at most, above or at least it ( {"field": "errors", "gt": 0})"is": trueor"is": falsethis boolean A missing field, a value of another type (the string
"3"forgt,0foris: false) or a null result ends the loop.max_repeats(1 to 100) counts passes after the first, so2means at most 3 passes. The loop node must have aschema, and when its schema declares the field, the start checks the operator against it: the declaredtypemust bestringforequals,not_equalsandin(and each of their strings in the field'senum, when it has one),numberorintegerforlt,lte,gtandgte, andbooleanforis. The start also refuses a field the schema does not list inrequired: each segment of the path must be in therequiredof its enclosing object, even withadditionalProperties, unless that level usesanyOf,oneOf,allOfor$ref. A result without the field ends the loop after one pass.stall(optional) ends the loop when a number stops going down:"stall": {"field": "open_findings", "passes": 2}ends it onceopen_findingswas not lower than in the pass before for 2 passes in a row (the first pass has none before it, so it never counts). A missing or non-number value counts as not lower.passesis at least 1 and belowmax_repeats, and the start checksstall.fieldlikewhile.field, as a number.A new pass starts only when every node of the loop is
donein the last pass (for a fanout node, every copy of that pass; a pass with no copy is done). A failed or skipped node or copy ends the loop, even withon_error: "continue"; to retry a pass that timed out, set the body node'sretries. A body fanout over a skipped node outside the loop is skipped too, so the loop ends after its first pass.Pass
kof a node runs as uid<id>#it<k>(the first pass keeps<id>), in its own session, with the node'stimeout_msandretries.workflow::node-resultwith<id>#it<k>returns passk(<id>#it0the first pass); the bare id of a loop node or body node returns its last pass, likereadsandoutput. It returns null for a node that is notdone.A body node may declare
fanout. It fans out again in each pass, from that pass's array (a path reads its node's result of the same pass). Copyiof passkruns as uid<id>#it<k>#<i>(the first pass keeps<id>#<i>). A reader in the loop receives the array of its own pass's copies, andoutputnaming the fanout returns the copies of the last pass. A copy getsown_previous: null, since copyiof one pass has nothing to do with copyiof the next; the previous pass reaches it throughloop_previous. Each pass's copies count toward the run's 50,000 nodes: a pass that would go past it fails its fanout. The loop node cannot fan out.Every node of the loop receives
{"input": <its input>, "loop_previous": <the loop node's result of the previous pass>}, and a body node also"own_previous": <its own result of the previous pass>. Both are null on the first pass. Inside the loop,readsreads the same pass.Outside the loop a node can read only the loop node: readers (a fanout over it too) wait for its last pass and read that result.
outputmay name the loop node and any body node: each returns its last pass, all from the same pass, and the run waits for the loop to end even whenoutputnames only a body node. A body node whose last pass failed underon_error: "continue"returnsnull(its error is infailed_nodes), never an earlier pass; read one withworkflow::node-resultand<id>#it<k>. Withouton_error: "continue", a failed pass of any node of a loop the output needs fails the run.Put the loop node in
output, or read it from a later node. After the run, a result that still meetswhilemeans the loop gave up: the repeats ran out,stallended it, or a node of the last pass failed (seefailed_nodes). Any other value means the condition stopped holding. The pass count is the number of<id>#it<k>uids innodes, plus one.Pass and copy numbers have as many digits as they need (
v#it10), so a uid sorted as text putsv#it10beforev#it2. Theworkflow::statusmaps are keyed by uid in text order; take the numbers from the uid.node_detailspicks,result_errorandfailed_nodeslist, and the console shows each loop's passes, and each pass's copies, in number order.Say in the
taskof each node of the loop how to useloop_previous(for example: fix every finding in it). A body node whose result is the work itself (a text or a JSON document, nothing left on disk) starts every pass from scratch unless itstasksays to build onown_previous(for example: keep own_previous and change only what the findings ask for).Every body node must feed the loop node, a body node must not read its loop node, a node belongs to at most one loop, and the loop node must not declare
fanout.Under
max_concurrency, free slots go to ready uids in node-id order, so an earlier node's pass can take a slot before a later node's first pass.
Reusing an earlier run
"from_run": "<run id>" resumes an earlier run after an edit, a failure or a
stop: each node that run finished is settled done at start with its stored
result, and only the rest run. Send the whole request again with the edits;
the worker decides per node. A node is reused when all of these hold:
- the earlier run has a
donenode with the same id; - the node is unchanged, as the worker stores it:
task,reads,schema,model,provider,profile,system_prompt,functions(withdefault_functionsfor a node without its own), the folder (filesystem_root, else the caller's),effort,fanout,when,skip_if_read_skippedandcall.label,phase,timeout_ms,retries,read_onlyandon_errormay change; - every node it reads (or gates on) was reused, so a change reruns the node and every node downstream of it, and nothing else;
- a node that receives the run
inputgets the sameinput.
A fanout node that passes these keeps the earlier run's array: each copy that
was done is reused and the others run; its readers are reused only when every
copy was. A changed fanout array reruns every copy.
Never reused: the nodes of a loop and every node that reads one (the loop runs
again from its first pass), and a failed or cancelled node, on_error: "continue" or not, with its readers. A node the earlier run skipped that
passes the same checks is settled skipped again at start, as its gate decides
the same from the same inputs, so its readers can be reused. A node
workflow::skip skipped is not: a person's skip is no decision of its inputs,
so it runs again, and so do its readers. A model or
folder a node inherits from its caller is part of the node, so a start from
another model or folder reruns those nodes. A profile edited since the earlier
run is not detected: the node stores only the profile id.
- A reused node adds no
usageto the new run: its tokens stay counted in the earlier run. It has no session or start time;workflow::node-resulton the new run returns its result. - The results are copied into the new run, which can itself be a later run's
from_run. A run is deleted 24 h after it ends; after thatfrom_runis refused and the request must run in full. workflow::startrefuses afrom_runthat names no run (or one already collected), a run still running (stop it withworkflow::stopor wait), a run being stopped (retry in a moment), or a run it cannot read. A repeatedidempotency_keyreturns the original run beforefrom_runis read.from_runreads the earlier run's results under the ruleworkflow::statusandworkflow::node-resultuse: the run id.
workflow::status
workflow::status { run_id, details? } returns run_id, status, title
(when the run has one), paused: true (while paused), nodes (uid → state), node_errors, node_results, result, result_error,
created_at, updated_at, phases, usage and, for a run with a
budget, budget. A run started with
from_run also returns from_run, and reused_nodes, the uids settled from it
(each done, and "reused": true in node_details). reused_nodes is left
out when no node was reused: read a missing list as empty.
nodesalso lists the nodes that have not started aspending. An unexpanded fanout appears once under its node id (in a loop, each unexpanded pass of it under<id>#it<k>); a fanout over an empty array lists nothing. A node whosewhendid not hold isskipped(a skipped fanout once, under its node id), apart fromfailedandcancelled; it has no entry innode_errors. So is a node a person settled withworkflow::skip, which may have run partway. Each loop pass is listed under its own<id>#it<k>uid (a fanout copy in a pass under<id>#it<k>#<i>), innodes,node_errors,node_resultsandnode_details. These maps are keyed in text order (v#it10beforev#it2).phasescounts node uids perphase:{"code": {"total": 2, "done": 0, "failed": 0, "cancelled": 0, "running": 1, "skipped": 0}}.failedincludes thecancelledones, never theskippedones. Nodes without a phase are left out, and the map is omitted when empty. Each loop pass counts once, sototalgrows with every repeat.usageis the run's total over every node and every attempt:{"input_tokens": 1, "output_tokens": 1, "cache_read_tokens": 1, "cache_write_tokens": 1, "reasoning_tokens": null, "cost_usd": 0.42, "complete": true}. A counter isnullwhile no attempt reported it. The worker reads an attempt'sharness::metrics(the node session's tree) once, when it writes the attempt's end: the node settles, fails, is cancelled, or a refire stops it. An attempt whose send failed is read too, unless the harness refused it: a send that timed out may still have started a turn. One window is not covered: when the worker crashes, or fails to save the run, after the harness took a send but before the worker recorded it, and the run is stopped before the next tick finds that session, the attempt's usage is not counted and the total can still read complete. It makes those reads under the run lock, 16 at a time with a 5 s timeout each, so a stalled harness makes a tick or sweep pass that ends attempts up to 5 s longer per 16 of them. Status adds the stored total of those to a live read of each attempt still running, so it calls no harness function per ended node. Onlydetails: truemakes the live reads; without it, and for a running attempt whose read failed or fell outside the 100 described nodes, the attempt is left out.completeis false when an attempt is left out, when an attempt's read failed, was partial or had a generation without usage, and for a run started before this field existed (attempts that ended before the upgrade are not counted). A running attempt's read is partial while one of its turns is still generating, sousageis then a lower bound withcomplete: false, and the console shows it as≥; a running attempt whose turns have all settled can read as complete. A session tree that keeps generating after its attempt ended (a sub-agent still running, a stop that has not landed yet) is counted as it stood then.budget, only for a run started withmax_total_tokensormax_cost_usd: the limits, and the run ledger read live fromharness::budget::get(5 s timeout), with or withoutdetails:{"max_total_tokens": 200000, "max_cost_usd": 1.5, "tokens": {"total": 200000, "used": 187344, "reserved": 0, "remaining": 12656}, "cost_usd": {"total": 1.5, "used": 0.92, "reserved": 0.0, "remaining": 0.58}}.reservedis held by generations in flight,remainingistotal - used - reserved(at least 0), andtotalandremainingarenullfor a dimension without a limit.tokensandcost_usdare left out before the first node send and when the read fails. The ledger counts every generation of the node sessions' trees, so it can differ fromusage, which is read when an attempt ends.
With details: true it adds node_details for at most 100 uids (running
first, then pending, failed, cancelled, done, skipped; within each, by node id,
then a loop's passes and fanout copies in number order) and details_truncated: true when it cut the
list:
"node_details": {"kan-12": {
"state": "running", "label": "KAN-12 · x", "phase": "code", "model": "m",
"profile": "deepwork-lead", "session_id": "wf_r_ab_kan-12@r0", "attempt": 0,
"started_at": 1, "finished_at": 2, "elapsed_ms": 1,
"harness_status": "completed", "expects_wake": true, "last_generate_at": 3,
"usage": {"complete": true, "sessions": 3, "turns": 12, "function_calls": 40,
"function_call_errors": 0, "input_tokens": 1, "output_tokens": 1,
"cache_read_tokens": 1, "cache_write_tokens": 1,
"reasoning_tokens": null, "cost_usd": 0.42},
"depth": 2, "waiting_approval": true,
"pending_calls": [{"session_id": "wf_r_ab_kan-12@r0", "function_call_id": "fc_1",
"function_id": "shell::run", "pending_at": 4}]}}waiting_approval: true marks a running node whose session, or a direct
sub-agent of it, has a call held by
approval-gate for a person's decision.
pending_calls lists those calls: session_id and function_call_id name the
hold for approval::resolve, and pending_at is when it was held; arguments
are not copied. Status reads them with one paginated approval::list-pending
read per request (up to 20 calls of 500 rows), only when a described node is
running. Both keys are absent for any
other node, and for every node when approval-gate is not installed or the read
fails. A sub-agent of a sub-agent is not matched.
depth is the longest depends_on path from a source to the node in the
definition: 0 for a node with no dependencies, and for every node once the
definition is gone. A fanout copy and a loop pass take their node's depth. The
console orders nodes that have not started by it.
usage comes from harness::metrics over the node session's tree, and model
and last_generate_at from its context snapshots. harness_status and
expects_wake come from harness::status, for running nodes only. A running
node waiting for its transient retry also has
retry_at, the epoch ms its continue is due; until then its harness_status
reads failed. A node whose
send never reached the harness gets no live fields. These live
reads run without the run lock, 16 at a time, with a 5 s timeout each. A failed
read leaves its fields out, and status stores nothing it reads (the run's
usage total is read and stored when an attempt ends, as above). model of a node with
a profile is shown only once observed, because the profile may pin another
model. Callers compute idle time from last_generate_at.
elapsed_ms is finished_at minus started_at, or the time since
started_at while the node runs. It is the clock timeout_ms is checked
against, so harness queue wait, parked time and the 2 s settle poll are
included; time in an approval hold is included too, but the deadline moves
past it (see Limits). It covers the current attempt: a timeout refire starts it again, and
attempt counts those; each earlier attempt ran the full timeout_ms.
workflow::list
workflow::list { caller_session_id } returns { runs: [{ run_id, status, title?, created_at, updated_at }] }, newest created_at first, status as
workflow::status gives it. It lists the runs started from that session or
from any session in its harness::session-tree (its sub-agents), or from the
session alone when the tree read fails. A run stays listed until it is
collected, 24 h after it ended. For an agent's call the pre-call hook
overwrites caller_session_id with the agent's own session, so an agent lists
only its own runs. The console's Workflow section calls it.
workflow::pause, workflow::resume and workflow::skip
workflow::pause { run_id }returns{ run_id, paused: true }. While a run is paused its tick starts no new node: no agent node, no function node, no refire. Running nodes finish and settle as usual, and their timeouts keep counting: a node that times out with a retry left has its session stopped at once and its refire waits forworkflow::resume(the pause stops the session of a refire marked just before it). An attempt whose session the tick already reserved still goes out (its probe or send retry). A paused run still ends: it completes or fails once its nodes settle, andworkflow::stopstill cancels it.workflow::resume { run_id }returns{ run_id, paused: false }and ticks the run, so the held nodes start. Pausing a paused run, or resuming a running one, is a no-op success.workflow::skip { run_id, node }returns{ run_id, skipped: [uid…] }. It settles each named node asskipped, whatever itson_error, so its readers getnullexactly as for a node whosewhendid not hold (skip_if_read_skippedand a function node's implied skip apply). A running node's session is stopped the wayworkflow::stopstops it, which also disposes the wakes of a parked node; a node that has not started is marked at once. A result or failure the stopped turn delivers later is ignored, also one it submitted before the skip.nodeis a node id, a fanout copy<id>#<i>, a loop pass<id>#it<k>or a fanout copy in a pass<id>#it<k>#<i>. A bare id is the node's last loop pass; for a fanout in a loop,<id>#it<k>is that pass's fanout.- A bare fanout id skips the whole fanout before it expands (readers get
null), and every copy that has not ended after it expanded. Skipping one copy gives readersnullat its position, and does not count as a skipped fanout forskip_if_read_skipped. - In a loop it skips that pass only. A pass repeats only when every node of
it is done, so the loop ends after that pass; the pass's other nodes still
run, and read
nullfor the skipped one. - A skipped node counts as settled, so its readers start even while the
skipped node's own dependencies still run. On a paused run they wait for
workflow::resume.
- All three refuse an unknown run (
workflow::<fn>: no run '<id>'), a run that has finished (… has finished (<status>)) and a runworkflow::stopis ending (… is stopping).workflow::skipalso refuses an unknown node (run '<id>' has no node '<node>'), a node that has ended (node '<uid>' has already finished (<state>)) and a fanout with every copy ended (fanout '<id>' has no unfinished copy). - Like
workflow::stop, they check no caller: whoever may callworkflow::stopon a run may call them, and node sessions are deniedworkflow::*by default.workflow::statusshowspauseduntil the run ends.
Limits
- Parked nodes and stop. A node whose session waits on an armed wake stays
running until a later turn ends it, unless it already submitted its result.
When this worker stops a node session (timeout, refire,
workflow::stop, a run ending with nodes in flight, a submitted node settling with a wake armed), it disposes every observer in the session's tree after the stop, so a parked session ends cancelled instead of waking later. That stop also kills the session tree's background shell jobs and child sessions; for a submitted node the session reads cancelled in the harness while the node is done. This needs harness v1.9.4 or newer: an older harness ignoresquiet_deadlines, so disposing a parked node's armed wake sends it a[notification] wake removedmessage and starts a new turn right away. A wake that delivers between the stop and the disposal starts one more turn, which a second stop cancels; wakes that turn arms before the second stop stay armed, so the session can still wake once more. Ifharness::stopfails, the observers stay and the session can still wake; nothing retries the stop or the disposal for a refired, timed-out, skipped or settled submitted node; onlyworkflow::stopgets a second pass when the run finalizes. A skipped node's session that wakes that way runs once more, and its output is ignored. The node's new state is written before its stop, so a worker that exits between the two leaves that session unstopped: it runs its current turn out and keeps its wakes, and its output is ignored. A node stopped from outside while it holds armed wakes settles only when its wakes retire or at itstimeout_ms, unless it had submitted. A submitted one settles at once from its turn's status: done if the turn had completed, cancelled if the stop cancelled a running turn. - A finished node settles on a second poll. A node whose
harness::statusreads finished is polled again 2 s later and settles from that reply, so a parked node does not settle on its parking turn. Each tick or sweep pass that settles a node takes about 2 s longer, holding the run lock and one of the 10 tick-queue slots that all runs share. A wake whose turn starts more than 2 s after its claim, or whose dispatch fails after the claim, can still settle the parking turn. A message that reaches a finished node session within the 2 s makes the node settle on that later turn. - The timeout counts queue wait.
timeout_msruns from the send, so it includes harness queue wait and parked time. The sweep checks it once a minute. - An approval hold pauses the timeout. Each sweep pass that finds a
running node makes one paginated
approval::list-pendingread (up to 20 calls of 500 rows). A node whose session, or a direct sub-agent of it, has a held call is not timed out, refired, failed or settled while the hold lasts; when the hold ends, the node gets the time it had left when the hold started, plus up to one sweep period, since the end is seen at the next pass. The transient-retry window counts the same way. Holds do not expire, so a hold nobody resolves keeps the node running untilworkflow::stop. A sub-agent's hold counts only when approval-gate recorded the sub-agent session'sparent_session_id(it reads it from session-manager when the call is held); a deeper sub-agent's hold, or one recorded without it, is not seen and its node times out as before. A hold that starts after a pass's read is seen at the next pass, but a refire checks first: before the tick stops the timed-out attempt, it reads that session's holds again (filtered to the session and to its direct sub-agents), and a node with a call held by then stays on its attempt as a held node. A node out of retries fails without that check. A pass reads at most 10,000 holds, the oldest first; a held call beyond the cap is not seen, so its node times out as before: the refire check still finds it, but a node out of retries fails. approval-gate is optional: when the call is missing or fails, timeouts work as without it (a refire goes ahead), and a hold it already tracked ends at that pass; seen again later, it counts from that pass. retriesdefaults to 1. A node that times out is refired once unless it setsretries: 0, and a refire repeats the node's side effects.- A transient retry waits 1 to 2 minutes. The continue goes out with the
first tick or sweep pass at or after
retry_at, and the default sweep runs once a minute. A stop of an idle caller does not cancel a node waiting for its continue;workflow::stopdoes. A stop of a busy caller is seen only while it is the caller's current turn: one followed by a new caller turn before the next pass (up to one sweep period) is missed.read_onlyis a promise the worker does not check: a node with side effects that sets it gets continued too, though the continue asks it not to repeat calls that already returned. - No ordering-only dependency. A node runs after the nodes it names in
readsorfanout, and receives their results, so in "do X, then validate" over shared state the validator reads X's result, which may be text. - Loops are bounded and quiet. Each pass is a new session; continuity is
the work it leaves behind plus
loop_previousand, for a body node,own_previous. A loop ends without an error when its repeats run out (at most 100 after the first pass), when the condition reads a missing field or a value of another type, when itsstallstop fires, or when the next pass's nodes, before its fanouts expand, would push the run past 50,000 materialized nodes. A body fanout that would push it past fails instead, which fails the run unless that node hason_error: "continue". Put the loop node inoutput, or read it from a later node: a last result that still meetswhilemeans the loop gave up (the repeats ran out,stallended it, or a node of the last pass failed; seefailed_nodes), any other value means the condition stopped holding, and the pass count is the number of<id>#it<k>uids innodes, plus one.whilecompares one field with one operator, andstalllooks back one pass at a time; anything else is the loop node's judgement, written into its result. Say in thetaskof each node of the loop how to useloop_previous(for example: fix every finding in it), and in a body node that answers with the work itself, to build onown_previous. A body node may fan out, again in each pass; the loop node may not. Outside its loop a node reads only the loop node;outputmay also name a body node, which returns its last pass. - The run result is capped at 1 MiB. An
outputwhose combined value is larger fails the run, andresult_errorsays so. The node results stay readable withworkflow::node-result, so name fewer nodes inoutputwhen their results are large. - Node usage covers the current attempt. A refired node's
usageinnode_detailscovers its newest@r<n>session tree only; the run'susagecounts every attempt. - A run budget errs toward stopping early. A generation a harness restart
interrupts keeps its reservation, and parallel nodes reserve their worst
case at once (see Run budget). A sub-agent that alone hits
the budget fails; its node fails at its own next generation, or at its
timeout_msrefire when it stays parked. A message sent into a node session after the sweep collected its run fails withharness.budget_unavailable. - Stopping an idle caller. Stopping an idle caller cancels the running
nodes, but consumers of
on_error: continuenodes still fire. Useworkflow::stopto end the run. finished_atafter an upgrade. Nodes that ended before the upgrade get the time of the run's next write asfinished_at; a run that had already ended has none.reply_toruns after an upgrade. A run started withreply_tobefore the upgrade gets no delivery: its record still loads, but nothing posts its outcome and nothing wakes its caller. To recover, prompt the caller to observe the run with args{ run_id }(a run that already ended is replayed at once; one still running reports when it ends) or to readworkflow::status, within 24 h of the run's end.- Forgotten observe. An agent that never makes the
nextcall is not woken; the outcome stays inworkflow::statusfor 24 h. The worker logs a warning and countsworkflow.runs.ended_unobservedfor a run with a stamped caller, nonotifyand no observer of that run (an every-run observer does not count). A run that ends before its caller's observe lands counts too, so the counter is an upper bound on stalled callers. Do not subtractworkflow.runs.replayed: it counts every replay (a second observer, or one re-listed after a restart). To find the runs really stalled, match the warning'srun_idagainst thereplayed the run's endlog lines.
Events
| Function | Args | Filter on | Event |
|---|---|---|---|
workflow::on-run-completed |
{ run_id? }: one run, replayed if it already ended; omitted: every run |
input.run_id, input.status (no replay) |
RunCompletedEvent { run_id, status: completed | failed | cancelled, result, result_error, failed_nodes? } |
The function is private (only this worker calls it; anyone may observe it) and
returns the event it is called with. The worker calls it once per terminal run,
at least once (a crash mid-finalize re-fires it), and only while an observer
wants that run; dedup on run_id. failed_nodes lists the
node '<uid>': <error> of each node a completed run tolerated failing
(on_error: continue), and is omitted when there are none.
An observer with args { run_id } gets only that run. Adding it for a run that
already ended replays the event to it at once, through the observer: a call
target receives the bare event, not the Observed envelope of a live delivery,
so a worker with its own target must accept both (or use notify). An observer
accepted during the run's final tick can get both the live event and the
replay. Adding one for an unknown or collected run is refused with
UNKNOWN_RUN, and unknown args with INVALID_ARGS. filters get no replay:
to wait for one run, use args, never filters.
Observers
| Observed function | Args / filters | Target | Target receives |
|---|---|---|---|
cron::on-tick |
args { expression: <sweep_expression> } |
workflow::sweep |
the tick (capture: [output], read as payload.output) |
harness::on-turn-completed |
filters { "input.session_id": { "$prefix": "wf_" } } |
workflow::wake |
TurnCompletedEvent of a node session (capture: [output], read as payload.output) |
harness::hook::on-pre-call |
args { functions: ["workflow::start", "workflow::list", "workflow-result::submit"], on_error: "fail_closed", timeout_ms: 30000 } |
workflow::stamp-reply |
the pre-call hook input; returns the hook decision, with the caller's session stamped as caller_session_id and, on workflow::start without a title, the call's description as title. A hook error or timeout refuses the agent's call |
harness::hook::on-post-turn |
args { sessions: ["wf_*"], on_error: "fail_open", timeout_ms: 30000, retry_prompt: <answer-format nudge> } |
workflow::validate-result |
the post-turn hook input; returns deny with a reason for a JSON node's answer that is not a JSON value matching its schema, unless a wake is armed. An error or timeout passes the turn, and reconcile still checks the result |
harness::hook::on-pre-generate |
args { sessions: ["wf_*"], on_error: "fail_open", timeout_ms: 5000, input: ["generate.system_prompt"] } |
workflow::inject-result-contract |
the envelope and the system prompt; returns the prompt with the JSON node's result contract appended, or no mutation for a text node, a finished or stale attempt and any failed read. An error or timeout leaves the prompt as it is |
harness::hook::on-pre-generate |
args { on_error: "fail_open", inject_prompt: <workflow guidance> }, only while inject_guidance is on |
workflow::inject-guidance |
not called: the harness joins inject_prompt into the system prompt |
configuration::on-updated |
filters on input.id and input.event_type (through iii-config-client) |
workflow::on-config-change |
the configuration event (capture: [output], read as payload.output) |
A sweep_expression change observes the new expression first, then disposes
the old observer; if the cron worker refuses the new expression
(INVALID_CRON_EXPRESSION), the old observer and schedule stay.
These targets and the queued workflow::tick are registered with
metadata.internal: hidden from engine::functions::list and
directory::search_functions, still delivered by id.
Console UI
The worker ships its console UI into any running console (the injectable-UI
protocol): a Workflow section in the chat's Context panel, which lists the
chat's runs with workflow::list and follows each with workflow::status, and
the chat cards for workflow::start, workflow::status, workflow::stop and
workflow::node-result. A running run's row has a Pause button (Resume while it
is paused, marked paused), and each running or pending node row of it a Skip
button; they call workflow::pause, workflow::resume and workflow::skip,
and a refused call shows on the run's row and is announced to a screen reader. A run of one node gets no buttons. It also renders the <workflow_input> block a node
session opens with as a card (readable rows, the JSON one click away) through
the console's message-block slot; a console without that slot shows the raw
tag. It is built from ui/ (build.rs runs pnpm install && pnpm build when ui/dist/ is missing or stale; SKIP_UI_BUILD=1 uses it
as is) and embedded in the binary (src/ui.rs). For the dev loop, set
III_WORKFLOW_UI_WATCH to the build output directory (or 1 for ui/dist)
to hot-swap the assets in open consoles.
Scaling & concurrency
Single-writer-per-run (the correctness model)
Every path that reads, mutates, and writes a run record — workflow::tick,
reconcile, the pending-timeout sweep, workflow::stop, workflow::pause,
workflow::resume and workflow::skip — holds the
per-run WorkflowLocks guard before touching state. This serialises writes
within one process and closes the read-modify-write race.
Idempotency for duplicate event deliveries is provided by deterministic ids:
the child session id (wf_<run_id>_<node_uid>@r<attempt>) and the
workflow_node_result/<run_id>/<node_uid> key are stable, so a re-delivered
tick that re-fires an already-running node is a no-op at the harness layer.
A tick persists each node's attempt session before sending it; a later tick
that finds the session reserved asks harness::status before sending again.
A workflow::start idempotency_key is checked and written under one fixed
lock ("idem"), and the sweep deletes the key with its run under that lock.
Node sessions carry the caller as metadata.parent_session_id, so they sit in
the caller's session tree: stopping the caller's session stops every running
node. When the caller's turn reads cancelled, the run ends cancelled, even
with on_error: continue nodes; an idle caller is not detected (see Limits).
workflow::stop stops one run's node sessions without touching the caller.
Node sessions run in the caller's folder: the pre-call hook stamps the caller
turn's metadata.fs_scope.root as caller_fs_root (replacing any value the
agent sent), and every node send carries it as
options.metadata.fs_scope.root, unless the node sets filesystem_root.
Without one, nodes get the harness default folder. A non-agent caller (CLI, worker) is not hooked, so its
caller_fs_root is used as sent; an empty one is refused. A node granted
workflow::start and workflow::on-run-completed (its next observe;
workflow::* is denied by default) passes its own folder to a nested run and
is woken when it ends. The hook runs only on
calls made from an agent turn, so the harness refuses workflow::start as an
observer binding target and fp refuses it as a pipe step; both need the
harness and fp releases that carry those refusals.
One instance per namespace
A function id has one host per namespace: the engine rejects a second
registration of the same id with FUNCTION_NAMESPACE_CONFLICT. The worker
registers every workflow::* function, workflow::on-run-completed included,
so the first instance in a namespace hosts them all and the
per-run WorkflowLocks live in that one process. A second instance in the same
namespace gets every registration rejected while its observers (the sweep and
the harness hooks) still deliver to the first instance's functions, so each
sweep and hook runs twice. Run one workflow worker per namespace.
Why not state::compare-and-set
state::set is an unconditional overwrite. state::compare-and-set exists,
but the worker does not adopt it for run records or idempotency keys:
- it compares the whole stored value, so every run-record write would have to carry the full previous record;
- an absent key compares equal to a stored
null; - it has no size guard;
- on Redis it retries a scope-wide
WATCHup to 8 times, so concurrent writers to different runs in the same scope contend with each other.
Since the engine allows one instance per namespace (above), the in-process
locks give every run one writer, and WorkflowRunRecord carries no version
field.