Skip to content
Sign in

workflow

v0.3.14

Deterministic, crash-resumable multi-agent workflow orchestrator over harness turns.

Install

bash
iii call compose::add worker=workflow

Run 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.

  1. Observe the run (for an AGENT caller). For a call from an agent turn, workflow::start returns {run_id, next}. next is the harness::observe call 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 with UNKNOWN_RUN. A notification cut at the harness's 8,000-character limit is incomplete: call workflow::status once for the run. next is present only when the pre-call hook stamped your session; you pass no session id. A session whose policy narrows options.functions must allow harness::observe and workflow::on-run-completed.

    reply_to was removed: a start that passes it is refused with this recipe.

  2. Completion callback (push), for a WORKER caller. Pass notify to workflow::start. When the run reaches a terminal state the worker calls your function once with {run_id, status, result, result_error, failed_nodes?} (failed_nodes is 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 its workflow-notify queue at boot, apart from the workflow tick queue, so a slow callback cannot delay ticks; a custom queue must already be defined with queue::define. A start from an agent turn (one the pre-call hook stamped with a session) that passes notify is refused: the callback runs outside every node policy, so an agent uses next instead.

  3. 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 a schema it has must declare every segment under properties. A level without properties, or with additionalProperties, anyOf, $ref and 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 with on_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.args plus "value": <the node's input>: what a session node with the same reads, fanout or loop receives. fp's transforms take their input at value, so call.args must not hold one.
  • at. A JSON pointer into that input ("" or starting with /), or a non-empty array of them. value then carries the value there, or for an array the array of the values, in order; a pointer that finds nothing gives null. A body node of a loop receives {"input", "loop_previous", "own_previous"} (the loop node has no own_previous) and a fanout copy with reads {"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 loop while on "field": "value…". The result counts as JSON without a schema; with one it is checked against it, with the validator workflow-result::submit uses. The schema describes the whole response, so it is an object schema with the value under properties.value, for example {"type": "object", "properties": {"value": {"type": "array"}}}; start refuses a top-level type other than "object". A null response, one that fails schema, 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_only and effort are 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 the null that node delivers; skip_if_read_skipped: false does not turn this off. In a loop it is not: it reads null for 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 has on_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 as laptop/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, and on_error applies as for any node. A function node holds no max_concurrency slot and adds nothing to the run's usage. 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 slower sweep_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_errors unless the continue fails too; with on_error: "continue" only that final failure reads as null.
  • An older harness, which reports no failure on harness::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 from from_run spend 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 used reaches the limit: give it room for max_concurrency × (context + maximum output), or lower max_concurrency. A failed provider call keeps its reservation. With max_cost_usd, a node whose model has no pricing fails.
  • A node whose turn ends on the budget (failure.code harness.budget_exceeded on harness::status) fails with run budget exceeded: <the harness's text>, even with a wake armed or on_error: "continue". The run then stops its remaining nodes, as workflow::stop does, and fails with a result_error that 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 settles done; the next generation of any node stops the run.
  • In such a run no node may call workflow::start or harness::send: both are added to every node's deny, whatever its functions allows, since a nested run or a session it sends to would spend outside the ledger.
  • workflow::start asks the harness for budget ledgers first (harness::budget::delete of wf: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 name workflow.
  • workflow::status returns the limits and the ledger in budget. The ledger stays until the sweep collects the run, 24 h after it ends, and is deleted with it.
  • A repeated idempotency_key returns 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"]}
  • when takes a loop's while shape and operators (equals, not_equals, in, lt, lte, gt, gte, is; see Loops). Its field starts with the node it reads, "<id>.<path>"; the node runs after that one. That node must not be a fanout node and must have a schema; the start checks the field against it as it checks while.field: the schema must declare it with a type the operator compares, and list it in required.
  • 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 under on_error: "continue", or itself skipped) does not hold either. skipped is not a failure: a run whose nodes are all done or skipped completes.
  • A skipped node's readers receive null (in an array of reads and in output, under its key). With skip_if_read_skipped: true a reader is skipped instead, so "discover" → "plan" (when count gt 0) → "apply" (skip_if_read_skipped) ends the run at once when discover finds nothing. A fanout over a skipped node is always skipped, and so is a function node outside a loop that reads one: null has no elements, and a transform cannot take it.
  • A skipped output node makes a completed run's result null, as a failed one under on_error: "continue" does; workflow::status tells them apart. A node only a when reads is not unread, so name it in output to keep its result (["discover", "apply"] above).
  • A fanout node with when is gated once as a whole: skipped, it has no copies and its readers receive null, not [].
  • If/else is two nodes with opposite conditions (equals / not_equals, is: true / is: false); a join that reads both receives null for the branch that did not run.
  • A node of a loop cannot declare when or skip_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"}
  • while is field, 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 number a number below, at most, above or at least it ({"field": "errors", "gt": 0})
    "is": true or "is": false this boolean

    A missing field, a value of another type (the string "3" for gt, 0 for is: false) or a null result ends the loop. max_repeats (1 to 100) counts passes after the first, so 2 means at most 3 passes. The loop node must have a schema, and when its schema declares the field, the start checks the operator against it: the declared type must be string for equals, not_equals and in (and each of their strings in the field's enum, when it has one), number or integer for lt, lte, gt and gte, and boolean for is. The start also refuses a field the schema does not list in required: each segment of the path must be in the required of its enclosing object, even with additionalProperties, unless that level uses anyOf, oneOf, allOf or $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 once open_findings was 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. passes is at least 1 and below max_repeats, and the start checks stall.field like while.field, as a number.

  • A new pass starts only when every node of the loop is done in 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 with on_error: "continue"; to retry a pass that timed out, set the body node's retries. A body fanout over a skipped node outside the loop is skipped too, so the loop ends after its first pass.

  • Pass k of a node runs as uid <id>#it<k> (the first pass keeps <id>), in its own session, with the node's timeout_ms and retries. workflow::node-result with <id>#it<k> returns pass k (<id>#it0 the first pass); the bare id of a loop node or body node returns its last pass, like reads and output. It returns null for a node that is not done.

  • 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). Copy i of pass k runs 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, and output naming the fanout returns the copies of the last pass. A copy gets own_previous: null, since copy i of one pass has nothing to do with copy i of the next; the previous pass reaches it through loop_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, reads reads 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. output may 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 when output names only a body node. A body node whose last pass failed under on_error: "continue" returns null (its error is in failed_nodes), never an earlier pass; read one with workflow::node-result and <id>#it<k>. Without on_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 meets while means the loop gave up: the repeats ran out, stall ended it, or a node of the last pass failed (see failed_nodes). Any other value means the condition stopped holding. The pass count is the number of <id>#it<k> uids in nodes, plus one.

  • Pass and copy numbers have as many digits as they need (v#it10), so a uid sorted as text puts v#it10 before v#it2. The workflow::status maps are keyed by uid in text order; take the numbers from the uid. node_details picks, result_error and failed_nodes list, and the console shows each loop's passes, and each pass's copies, in number order.

  • Say in the task of each node of the loop how to use loop_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 its task says to build on own_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 done node with the same id;
  • the node is unchanged, as the worker stores it: task, reads, schema, model, provider, profile, system_prompt, functions (with default_functions for a node without its own), the folder (filesystem_root, else the caller's), effort, fanout, when, skip_if_read_skipped and call. label, phase, timeout_ms, retries, read_only and on_error may 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 input gets the same input.

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 usage to the new run: its tokens stay counted in the earlier run. It has no session or start time; workflow::node-result on 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 that from_run is refused and the request must run in full.
  • workflow::start refuses a from_run that names no run (or one already collected), a run still running (stop it with workflow::stop or wait), a run being stopped (retry in a moment), or a run it cannot read. A repeated idempotency_key returns the original run before from_run is read.
  • from_run reads the earlier run's results under the rule workflow::status and workflow::node-result use: 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.

  • nodes also lists the nodes that have not started as pending. 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 whose when did not hold is skipped (a skipped fanout once, under its node id), apart from failed and cancelled; it has no entry in node_errors. So is a node a person settled with workflow::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>), in nodes, node_errors, node_results and node_details. These maps are keyed in text order (v#it10 before v#it2).
  • phases counts node uids per phase: {"code": {"total": 2, "done": 0, "failed": 0, "cancelled": 0, "running": 1, "skipped": 0}}. failed includes the cancelled ones, never the skipped ones. Nodes without a phase are left out, and the map is omitted when empty. Each loop pass counts once, so total grows with every repeat.
  • usage is 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 is null while no attempt reported it. The worker reads an attempt's harness::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. Only details: true makes 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. complete is 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, so usage is then a lower bound with complete: 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 with max_total_tokens or max_cost_usd: the limits, and the run ledger read live from harness::budget::get (5 s timeout), with or without details: {"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}}. reserved is held by generations in flight, remaining is total - used - reserved (at least 0), and total and remaining are null for a dimension without a limit. tokens and cost_usd are 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 from usage, 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 for workflow::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, and workflow::stop still 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 as skipped, whatever its on_error, so its readers get null exactly as for a node whose when did not hold (skip_if_read_skipped and a function node's implied skip apply). A running node's session is stopped the way workflow::stop stops 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.
    • node is 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 readers null at its position, and does not count as a skipped fanout for skip_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 null for 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 run workflow::stop is ending (… is stopping). workflow::skip also 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 call workflow::stop on a run may call them, and node sessions are denied workflow::* by default. workflow::status shows paused until 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 ignores quiet_deadlines, so disposing a parked node's armed wake sends it a [notification] wake removed message 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. If harness::stop fails, 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; only workflow::stop gets 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 its timeout_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::status reads 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_ms runs 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-pending read (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 until workflow::stop. A sub-agent's hold counts only when approval-gate recorded the sub-agent session's parent_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.
  • retries defaults to 1. A node that times out is refired once unless it sets retries: 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::stop does. 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_only is 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 reads or fanout, 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_previous and, 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 its stall stop 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 has on_error: "continue". Put the loop node in output, or read it from a later node: a last result that still meets while means the loop gave up (the repeats ran out, stall ended it, or a node of the last pass failed; see failed_nodes), any other value means the condition stopped holding, and the pass count is the number of <id>#it<k> uids in nodes, plus one. while compares one field with one operator, and stall looks back one pass at a time; anything else is the loop node's judgement, written into its result. Say in the task of each node of the loop how to use loop_previous (for example: fix every finding in it), and in a body node that answers with the work itself, to build on own_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; output may also name a body node, which returns its last pass.
  • The run result is capped at 1 MiB. An output whose combined value is larger fails the run, and result_error says so. The node results stay readable with workflow::node-result, so name fewer nodes in output when their results are large.
  • Node usage covers the current attempt. A refired node's usage in node_details covers its newest @r<n> session tree only; the run's usage counts 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_ms refire when it stays parked. A message sent into a node session after the sweep collected its run fails with harness.budget_unavailable.
  • Stopping an idle caller. Stopping an idle caller cancels the running nodes, but consumers of on_error: continue nodes still fire. Use workflow::stop to end the run.
  • finished_at after an upgrade. Nodes that ended before the upgrade get the time of the run's next write as finished_at; a run that had already ended has none.
  • reply_to runs after an upgrade. A run started with reply_to before 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 read workflow::status, within 24 h of the run's end.
  • Forgotten observe. An agent that never makes the next call is not woken; the outcome stays in workflow::status for 24 h. The worker logs a warning and counts workflow.runs.ended_unobserved for a run with a stamped caller, no notify and 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 subtract workflow.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's run_id against the replayed the run's end log 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 WATCH up 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.

Search the registry

Find workers, kits and executables, or jump to a page.