fascicle 0.17.3 → 0.17.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/AGENTS.md +7 -7
- package/dist/acp.d.ts +1 -1
- package/dist/acp.js +1 -1
- package/dist/agents.d.ts +1 -1
- package/dist/agents.js +1 -1
- package/dist/{core-Dwir3pkb.js → core-Bfzt55Fl.js} +68 -43
- package/dist/core-Bfzt55Fl.js.map +1 -0
- package/dist/diagram_bin.js +1 -1
- package/dist/{engine-DPPqAVdZ.js → engine-CbVdzplI.js} +131 -50
- package/dist/engine-CbVdzplI.js.map +1 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.js +3 -3
- package/dist/{invoke-DF7YLovL.js → invoke-x5SNh9DV.js} +3 -3
- package/dist/{invoke-DF7YLovL.js.map → invoke-x5SNh9DV.js.map} +1 -1
- package/dist/{leading_system-DJvuhESU.js → leading_system-C23TJ9OQ.js} +52 -22
- package/dist/leading_system-C23TJ9OQ.js.map +1 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +1 -1
- package/dist/stdio.js +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +3 -3
- package/dist/{types-C7pO0jLq.d.ts → types-C23S11Kk.d.ts} +26 -1
- package/dist/viewer.js +1 -1
- package/package.json +1 -1
- package/dist/core-Dwir3pkb.js.map +0 -1
- package/dist/engine-DPPqAVdZ.js.map +0 -1
- package/dist/leading_system-DJvuhESU.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"core-Dwir3pkb.js","names":["label_of","label_of","label_of","list","start_run","settle","next_id","next_id","next_id","next_id","next_id","next_id","next_id","next_id","next_id","next_id"],"sources":["../src/core/cleanup.ts","../src/core/display_name.ts","../src/core/step_kinds.ts","../src/core/node_label.ts","../src/core/replays.ts","../src/core/diagram.ts","../src/core/errors.ts","../src/core/is_step.ts","../src/core/describe.ts","../src/core/streaming.ts","../src/core/suspend_ids.ts","../src/core/runner.ts","../src/schema/validate.ts","../src/core/durable.ts","../src/core/step_id.ts","../src/core/step.ts","../src/core/sequence.ts","../src/core/parallel.ts","../src/core/branch.ts","../src/core/map.ts","../src/core/pipe.ts","../src/policy/backoff.ts","../src/core/retry.ts","../src/core/fallback.ts","../src/core/timeout.ts","../src/core/loop.ts","../src/core/compose.ts","../src/core/checkpoint.ts","../src/core/suspend.ts","../src/core/scope.ts","../src/core/chain.ts"],"sourcesContent":["/**\n * Per-run cleanup registry.\n *\n * Handlers fire in LIFO (reverse registration) order on abort, on uncaught\n * error in the root, and on successful completion. Each handler has a\n * 5-second timeout; timeouts are recorded in the trajectory but do not block\n * other handlers. A handler that throws is recorded as `cleanup_error`;\n * subsequent handlers still execute.\n */\n\nimport type { CleanupFn, TrajectoryLogger } from './types.js'\n\nconst HANDLER_TIMEOUT_MS = 5_000\n\nexport type CleanupRegistry = {\n readonly register: (fn: CleanupFn) => void\n readonly run_all: () => Promise<void>\n}\n\n/**\n * Create the per-run cleanup registry.\n *\n * `register` collects handlers during the run; `run_all` fires them once in\n * LIFO order and is idempotent. A registration arriving after the flush is\n * not executed; it is recorded as `cleanup_registered_after_flush` so the\n * leak is visible in the trajectory instead of silently dropped.\n */\nexport function create_cleanup_registry(trajectory: TrajectoryLogger): CleanupRegistry {\n const handlers: CleanupFn[] = []\n let ran = false\n\n function register(fn: CleanupFn): void {\n if (ran) {\n trajectory.record({\n kind: 'cleanup_registered_after_flush',\n })\n return\n }\n handlers.push(fn)\n }\n\n async function run_all(): Promise<void> {\n if (ran) return\n ran = true\n for (let i = handlers.length - 1; i >= 0; i -= 1) {\n const fn = handlers[i]\n if (!fn) continue\n await run_one(fn, trajectory)\n }\n }\n\n return { register, run_all }\n}\n\n/**\n * Run a single cleanup handler, never letting it fail the run.\n *\n * Races the handler against a 5-second timer. Whichever loses the race only\n * results in a trajectory record (`cleanup_timeout` or `cleanup_error`); the\n * returned promise always resolves so the remaining handlers still execute.\n * A timed-out handler keeps running in the background; it is abandoned, not\n * killed.\n */\nasync function run_one(fn: CleanupFn, trajectory: TrajectoryLogger): Promise<void> {\n let timeout_id: ReturnType<typeof setTimeout> | null = null\n try {\n await new Promise<void>((resolve) => {\n timeout_id = setTimeout(() => {\n trajectory.record({ kind: 'cleanup_timeout', timeout_ms: HANDLER_TIMEOUT_MS })\n resolve()\n }, HANDLER_TIMEOUT_MS)\n \n Promise.resolve()\n .then(() => fn())\n .then(\n () => {\n if (timeout_id) clearTimeout(timeout_id)\n resolve()\n },\n (err: unknown) => {\n if (timeout_id) clearTimeout(timeout_id)\n trajectory.record({\n kind: 'cleanup_error',\n error: err instanceof Error ? err.message : String(err),\n })\n resolve()\n },\n )\n })\n } finally {\n if (timeout_id) clearTimeout(timeout_id)\n }\n}\n","/**\n * Display-name resolution.\n *\n * Every consumer that renders a step for human eyes (the runner's span\n * labels, `describe`, bench reports) resolves the same way, so the order\n * lives here rather than in three copies: `config.display_name` first (what\n * composers write from their `name` option), then `meta.name` (what\n * `step(id, fn, { name })` writes), then the caller's fallback.\n *\n * Identity deliberately never participates. A step's `id` is rendered\n * separately by the consumers that want it, so renaming a step for\n * readability cannot move a checkpoint key, a resume address, or a\n * trajectory id.\n */\n\nimport type { AnyStep, StepMetadata } from './types.js'\n\n/**\n * Resolve the human-readable label for `node`, falling back to `fallback`\n * (typically the step's kind) when neither display channel is populated.\n * It reads only `config` and `meta`, so a `describe.json` node resolves the\n * same way as the step it was drawn from.\n */\nexport function resolve_display_name(\n node: Pick<AnyStep, 'config' | 'meta'>,\n fallback: string,\n): string {\n const display = node.config?.['display_name']\n if (typeof display === 'string' && display.length > 0) return display\n const name = node.meta?.name\n if (typeof name === 'string' && name.length > 0) return name\n return fallback\n}\n\n/**\n * The `meta` a composer spreads into the step it returns for its\n * `description` option: `meta.description` when one is given, and nothing\n * otherwise, so a composer without a description carries no empty `meta`\n * for `describe` to echo.\n */\nexport function description_meta(description: string | undefined): {\n readonly meta?: StepMetadata\n} {\n return description === undefined ? {} : { meta: { description } }\n}\n","/**\n * Closed registry of every `Step.kind` produced by the composition layer.\n *\n * The viewer (and any other consumer that needs to enumerate primitives:\n * palette, docs, code generation) can rely on this being the exhaustive set. New\n * primitives must add their kind here. `step_kinds.test.ts` pins the list\n * against the kinds core actually constructs, in both directions. The\n * composites (`ensemble`, `tournament`, and the rest) add no kinds of their\n * own: each builds a `compose` step that carries its name as the display name.\n */\n\nexport const STEP_KINDS = [\n 'step',\n 'sequence',\n 'parallel',\n 'branch',\n 'map',\n 'pipe',\n 'retry',\n 'fallback',\n 'timeout',\n 'loop',\n 'compose',\n 'checkpoint',\n 'suspend',\n 'scope',\n 'stash',\n 'use',\n 'chain',\n] as const\n\nexport type StepKind = (typeof STEP_KINDS)[number]\n\n/**\n * Check whether a value is one of the registered `Step.kind` strings.\n */\nexport function is_step_kind(value: unknown): value is StepKind {\n return typeof value === 'string' && (STEP_KINDS as readonly string[]).includes(value)\n}\n","/**\n * What a flow node is called: its display name, an id its author chose, or\n * its kind, in that order. `describe.diagram` labels its rows this way, and\n * `describe.replays` names the steps it finds the same way.\n *\n * A counter-generated id never serves as a label, because its number depends\n * on what else the process built first.\n */\n\nimport { resolve_display_name } from './display_name.js'\nimport { is_step_kind } from './step_kinds.js'\nimport type { FlowNode } from './types.js'\n\n// Built-in kinds whose id the caller supplies. Every other built-in kind\n// numbers its id from a process-wide counter.\nconst CHOSEN_ID_KINDS: ReadonlySet<string> = new Set(['step', 'suspend'])\n\n/**\n * Pick a node's label: its display name, else an id its author chose, else\n * its kind. `by_kind` reports the last case, where the kind already shows.\n */\nexport function label_of(node: FlowNode): { readonly label: string; readonly by_kind: boolean } {\n const display = resolve_display_name(node, '')\n if (display !== '') return { label: display, by_kind: false }\n if (has_chosen_id(node)) return { label: node.id, by_kind: false }\n return { label: node.kind, by_kind: true }\n}\n\n/**\n * True when a node's id was chosen by its author. Anonymous steps, cycle\n * markers, and every built-in composer carry generated ids. A kind outside\n * the built-in set belongs to a hand-built step, whose id is its author's.\n */\nexport function has_chosen_id(node: FlowNode): boolean {\n if (node.anonymous === true || node.kind === '<cycle>') return false\n return !is_step_kind(node.kind) || CHOSEN_ID_KINDS.has(node.kind)\n}\n","/**\n * The analysis behind `describe.replays(step)`: which steps marked\n * `side_effect` a resumed run can run again before it reaches a gate.\n *\n * A run that resumes at a `suspend` replays the flow from its input, so a step\n * that ran before the gate runs again, unless a `checkpoint` stored its\n * result. The runtime reports each one as a `step_replayed` event once it has\n * happened. This finds them from the flow's shape alone, before anything runs,\n * so an app can hold its flow to having none in a test.\n *\n * It reads only the `FlowNode` tree that `describe.json` produces. A marked\n * step can replay at a gate when it can start before the gate in one pass and\n * no checkpoint stores its result first. Where the two paths split decides\n * which comes first:\n *\n * - `parallel` members start together, and a step's arms run in whatever\n * order its body calls them, so either one can.\n * - The arms of a `branch` exclude each other within a pass, so neither does.\n * - Anything else runs its children in order: a `sequence`, a `chain`'s plan,\n * a `fallback`'s primary before its backup, a `loop`'s body before its guard\n * within a round, and a kind this module doesn't know.\n * - A step that holds the gate starts before it.\n *\n * A checkpoint protects a step from a gate when it holds the step and not the\n * gate. One around both stores its result only after the gate resumes.\n *\n * What the tree can't show, this can't see: a model call that a step's body\n * makes without declaring it as an arm, a step that a `suspend`'s `combine`\n * hands back, and a gate that a loop reaches only in a later round.\n */\n\nimport { label_of } from './node_label.js'\nimport type { FlowNode } from './types.js'\n\n/**\n * A step that a resumed run can run again: its `id`, the `label` its row\n * carries in `describe.diagram`, and the ids of the gates it can run before,\n * in flow order.\n */\nexport type ReplayHint = {\n readonly id: string\n readonly label: string\n readonly gates: ReadonlyArray<string>\n}\n\ntype Turn = {\n readonly node: FlowNode\n readonly index: number\n}\n\n// A node with the turns that lead to it from the root: each ancestor, root\n// first, and the index of the child the path takes under it.\ntype Visit = {\n readonly node: FlowNode\n readonly trail: ReadonlyArray<Turn>\n}\n\n/**\n * Append `node` and every node under it to `out`, in reading order.\n */\nfunction walk(node: FlowNode, trail: ReadonlyArray<Turn>, out: Visit[]): void {\n out.push({ node, trail })\n for (const [index, child] of (node.children ?? []).entries()) {\n walk(child, [...trail, { node, index }], out)\n }\n}\n\n/**\n * True when, under a node of `kind`, the child at `first` can start before\n * the child at `second` within one pass.\n */\nfunction comes_first(kind: string, first: number, second: number): boolean {\n if (kind === 'branch') return false\n if (kind === 'parallel' || kind === 'step') return true\n // Stryker disable next-line EqualityOperator: two trails part where they take different children, so these indexes are never equal and <= reads like <.\n return first < second\n}\n\n/**\n * How many turns two trails share before they part, which is the depth of\n * the node where their paths split. A trail that runs out first is shared\n * whole.\n */\nfunction shared_depth(a: ReadonlyArray<Turn>, b: ReadonlyArray<Turn>): number {\n const parted = a.findIndex((turn, i) => turn.index !== b[i]?.index)\n return parted === -1 ? a.length : parted\n}\n\n/**\n * True when the marked step at `s` can run before the gate at `g` with no\n * checkpoint between them that holds the step and not the gate.\n */\nfunction runs_before(s: Visit, g: Visit): boolean {\n const depth = shared_depth(s.trail, g.trail)\n const split_s = s.trail[depth]\n const split_g = g.trail[depth]\n // The gate holds the step, which only a hand-built tree can arrange, or the\n // two are the same node. Either way the step can't start first.\n if (split_g === undefined) return false\n // The step holds the gate, so it starts first.\n if (split_s === undefined) return true\n if (!comes_first(split_s.node.kind, split_s.index, split_g.index)) return false\n return !s.trail.slice(depth + 1).some(({ node }) => node.kind === 'checkpoint')\n}\n\n/**\n * The gates each marked node can run before, by node, for every marked node\n * that has any. A gate that appears twice in the tree is listed once.\n */\nexport function replay_gates(root: FlowNode): ReadonlyMap<FlowNode, ReadonlyArray<string>> {\n const visits: Visit[] = []\n // Stryker disable next-line ArrayDeclaration: an extra entry at the head of every trail is one that all of them share, so it can't move where two trails part.\n walk(root, [], visits)\n const gates = visits.filter(({ node }) => node.kind === 'suspend')\n const found = new Map<FlowNode, ReadonlyArray<string>>()\n for (const visit of visits) {\n if (visit.node.meta?.side_effect !== true) continue\n const ids = [...new Set(gates.filter((gate) => runs_before(visit, gate)).map(({ node }) => node.id))]\n if (ids.length > 0) found.set(visit.node, ids)\n }\n return found\n}\n\n/**\n * Every step marked `side_effect` that a resumed run can run again before one\n * of the flow's gates, in flow order. A step that appears twice in the tree\n * gets one hint, with the gates of both places.\n */\nexport function find_replays(root: FlowNode): ReadonlyArray<ReplayHint> {\n const by_id = new Map<string, ReplayHint>()\n for (const [node, gates] of replay_gates(root)) {\n const seen = by_id.get(node.id)\n by_id.set(node.id, {\n id: node.id,\n label: label_of(node).label,\n gates: seen === undefined ? gates : [...new Set([...seen.gates, ...gates])],\n })\n }\n return [...by_id.values()]\n}\n","/**\n * The renderer behind `describe.diagram(step)`: a flow drawn as an annotated\n * box-drawing tree.\n *\n * It reads only the `FlowNode` tree that `describe.json` produces, so the same\n * flow renders to the same bytes wherever it is built, and an app can hold the\n * diagram in its `flow.ts` header to the code with one equality test.\n *\n * Each node gets one row. A row is labelled with the node's display name, then\n * an id the author chose, then its kind. A counter-generated id never appears,\n * because its number depends on what else the process built first. Roles come\n * from the parent's kind (a branch's `then` and `else`, a loop's `guard`, a\n * parallel member's key, a chain's stages), never from a config dump.\n * Descriptions share one column after the widest row. A composer's description\n * follows its kind (`branch: ...`), and a node without one shows its kind.\n * With `replays` set, a step that a resumed run can run again before a gate\n * ends its description with the gates it runs before.\n */\n\nimport { label_of } from './node_label.js'\nimport { replay_gates } from './replays.js'\nimport type { FlowNode, FlowValue } from './types.js'\n\nexport type DiagramOptions = {\n /** Throw `describe_cycle_error` on a cycle instead of drawing `<cycle>`, as `describe` does. */\n readonly strict?: boolean\n /** Wrap descriptions so that no line runs wider than this, `prefix` included. */\n readonly width?: number\n /** Written at the start of every line, for example `' * '` for a doc comment. */\n readonly prefix?: string\n /** Mark each step that `describe.replays` finds with the gates it can run again before. */\n readonly replays?: boolean\n /** Draw a named composite's internal steps instead of only the parts it was built from. */\n readonly internals?: boolean\n}\n\n// The gates each marked node can run before, by node, as `replay_gates`\n// finds them.\ntype Marks = ReadonlyMap<FlowNode, ReadonlyArray<string>>\n\n// What every row of one drawing shares: the replay marks, and whether a\n// composite's internals are drawn in place of its parts.\ntype Draw = {\n readonly marks: Marks\n readonly internals: boolean\n}\n\ntype Item = {\n readonly head: string\n readonly note: ReadonlyArray<string>\n readonly children: ReadonlyArray<Item>\n}\n\ntype Row = {\n readonly lead: string\n readonly head: string\n readonly note: ReadonlyArray<string>\n readonly wrap_lead: string\n}\n\nconst BRANCH_ROLES: ReadonlyArray<string> = ['then', 'else']\n\nconst STAGE_PREFIX = 'stage:'\n\nconst COLUMN_GAP = 2\n\n/**\n * Draw a `FlowNode` tree as rows of box-drawing glyphs, labels, and aligned\n * descriptions, joined with newlines and free of trailing whitespace.\n */\nexport function render_diagram(root: FlowNode, options?: DiagramOptions): string {\n const rows: Row[] = []\n const draw: Draw = {\n marks: options?.replays === true ? replay_gates(root) : new Map(),\n internals: options?.internals === true,\n }\n flatten(to_item(root, undefined, draw), '', '', rows)\n const column = Math.max(...rows.map((row) => row.lead.length + row.head.length)) + COLUMN_GAP\n const prefix = options?.prefix ?? ''\n const limit =\n options?.width === undefined ? Number.POSITIVE_INFINITY : options.width - prefix.length - column\n return rows\n .flatMap((row) => {\n const [first, ...rest] = wrap(row.note, limit)\n const head = `${row.lead}${row.head}`\n return [\n first === undefined ? head : `${head.padEnd(column)}${first}`,\n ...rest.map((line) => `${row.wrap_lead.padEnd(column)}${line}`),\n ]\n })\n .map((line) => `${prefix}${line}`)\n .join('\\n')\n}\n\n/**\n * Append `item` and its subtree to `rows` in reading order.\n *\n * `indent` is the glyph run this item's children are drawn after. A wrapped\n * description line reuses it, plus a bar when children follow, so the\n * vertical lines stay unbroken through the wrap.\n */\nfunction flatten(item: Item, lead: string, indent: string, rows: Row[]): void {\n const has_children = item.children.length > 0\n rows.push({\n lead,\n head: item.head,\n note: item.note,\n wrap_lead: has_children ? `${indent}│` : indent,\n })\n item.children.forEach((child, index) => {\n const last = index === item.children.length - 1\n flatten(child, `${indent}${last ? '└─ ' : '├─ '}`, `${indent}${last ? ' ' : '│ '}`, rows)\n })\n}\n\n/**\n * Break a description's words into lines no longer than `limit`. A word\n * longer than `limit` gets a line to itself rather than being split.\n */\nfunction wrap(words: ReadonlyArray<string>, limit: number): ReadonlyArray<string> {\n const lines: string[] = []\n let current = ''\n for (const word of words) {\n if (current === '') {\n current = word\n } else if (current.length + 1 + word.length <= limit) {\n current = `${current} ${word}`\n } else {\n lines.push(current)\n current = word\n }\n }\n if (current !== '') lines.push(current)\n return lines\n}\n\n/**\n * Convert one node into the item the layout draws. `role` is the name the\n * parent gives this child, and it is dropped when it only repeats the label.\n */\nfunction to_item(node: FlowNode, role: string | undefined, draw: Draw): Item {\n const { label, by_kind } = label_of(node)\n return {\n head: role === undefined || role === label ? label : `${role} ${label}`,\n note: [...note_of(node, by_kind), ...replay_note(draw.marks.get(node))],\n children: child_items(node, draw),\n }\n}\n\n/**\n * The words that mark a step a resumed run can run again, naming the gates\n * it runs before, or none for a step it can't.\n */\nfunction replay_note(gates: ReadonlyArray<string> | undefined): ReadonlyArray<string> {\n return gates === undefined ? [] : `(replays before ${gates.join(', ')})`.split(' ')\n}\n\n/**\n * The words of a row's description column.\n *\n * A row labelled by its kind shows only the description. A plain step shows\n * its description, or `step` without one. Any other node shows its kind, then\n * the description after a colon. Whitespace in a description collapses, so a\n * multi-line string still draws as one wrapped column.\n */\nfunction note_of(node: FlowNode, by_kind: boolean): ReadonlyArray<string> {\n const words = (node.meta?.description ?? '').split(/\\s+/).filter((word) => word !== '')\n if (by_kind) return words\n if (node.kind === 'step') return words.length > 0 ? words : ['step']\n return words.length > 0 ? [`${node.kind}:`, ...words] : [node.kind]\n}\n\n/**\n * Convert a node's children, naming each by the role its parent's kind gives\n * it.\n */\nfunction child_items(node: FlowNode, draw: Draw): ReadonlyArray<Item> {\n const children = node.children ?? []\n const parts = draw.internals ? [] : part_nodes(node)\n if (parts.length > 0) return parts.map(([role, part]) => to_item(part, role, draw))\n if (node.kind === 'branch') return children.map((child, i) => to_item(child, BRANCH_ROLES[i], draw))\n if (node.kind === 'loop') {\n return children.map((child, i) => to_item(child, i === 1 ? 'guard' : undefined, draw))\n }\n if (node.kind === 'parallel') {\n const keys = string_list(node.config?.['keys'])\n return children.map((child, i) => to_item(child, keys[i], draw))\n }\n if (node.kind === 'chain') return staged_items(children, string_list(node.config?.['plan']), draw)\n return children.map((child) => to_item(child, undefined, draw))\n}\n\n/**\n * The parts that a named composite records, by role, each resolved to the\n * node its path leads to. A composite that records none, or a path that leads\n * nowhere (a hand-edited tree, say), reads as no parts, and the composite's\n * own children are drawn instead.\n */\nfunction part_nodes(node: FlowNode): ReadonlyArray<readonly [string, FlowNode]> {\n const parts = node.config?.['parts']\n if (node.kind !== 'compose' || !is_flow_record(parts)) return []\n const resolved: Array<readonly [string, FlowNode]> = []\n for (const [role, path] of Object.entries(parts)) {\n const part = follow(node, path)\n if (part === undefined) return []\n resolved.push([role, part])\n }\n return resolved\n}\n\n/**\n * The node that a path of child indices leads to from `from`, or `undefined`\n * when the path isn't a list of indices that each name a child.\n */\nfunction follow(from: FlowNode, path: FlowValue): FlowNode | undefined {\n if (!Array.isArray(path)) return undefined\n const steps: ReadonlyArray<unknown> = path\n let current: FlowNode | undefined = from\n for (const index of steps) {\n if (typeof index !== 'number') return undefined\n current = current?.children?.[index]\n }\n return current === from ? undefined : current\n}\n\n/**\n * True for a config value that's a record rather than a list or a scalar. A\n * marker such as a function's reads as a record too, and `follow` turns it\n * away, since none of its values is a path.\n */\nfunction is_flow_record(value: FlowValue | undefined): value is Readonly<{ [key: string]: FlowValue }> {\n if (value === null || Array.isArray(value)) return false\n return typeof value === 'object'\n}\n\n/**\n * Convert a chain's children in plan order, nesting the entries after each\n * `.stage(name)` under a row for that stage, which is how the stage's span\n * encloses them in the trajectory. Children the plan does not account for\n * follow in order, so a node without a plan still draws every child.\n */\nfunction staged_items(\n children: ReadonlyArray<FlowNode>,\n plan: ReadonlyArray<string>,\n draw: Draw,\n): ReadonlyArray<Item> {\n const top: Item[] = []\n let target = top\n let next = 0\n for (const entry of plan) {\n if (entry.startsWith(STAGE_PREFIX)) {\n const members: Item[] = []\n top.push({ head: `stage ${entry.slice(STAGE_PREFIX.length)}`, note: [], children: members })\n target = members\n } else {\n const child = children[next]\n next += 1\n if (child !== undefined) target.push(to_item(child, undefined, draw))\n }\n }\n for (const child of children.slice(next)) target.push(to_item(child, undefined, draw))\n return top\n}\n\n/**\n * Read a config value as a list of strings, as `parallel` records its keys\n * and `chain` its plan. Anything else reads as an empty list.\n */\nfunction string_list(value: FlowValue | undefined): ReadonlyArray<string> {\n if (!Array.isArray(value)) return []\n const list: ReadonlyArray<unknown> = value\n return list.filter((entry): entry is string => typeof entry === 'string')\n}\n","/**\n * Typed errors for the composition layer.\n *\n * This is the only source file in the core layer that uses the `class`\n * keyword. `Error` is a built-in and `instanceof` branching is how composers\n * like `retry` and `fallback` distinguish failure modes.\n *\n * Every class declares an optional `path`: the chain of step ids the error\n * crossed while bubbling through dispatch. The runner attaches it via\n * Reflect.set (`prepend_path` in runner.ts), so the `declare` modifier types\n * what arrives without emitting a field; construction never sets it.\n */\n\nimport type { SchemaIssue } from '#schema'\n\nexport class timeout_error extends Error {\n readonly kind = 'timeout_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly timeout_ms: number;\n constructor(message: string, timeout_ms: number) {\n super(message)\n this.name = 'timeout_error'\n this.timeout_ms = timeout_ms\n }\n}\n\nexport class suspended_error extends Error {\n readonly kind = 'suspended_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly suspend_id: string;\n readonly payload: unknown;\n // How long the gate waits for its resume before its deadline passes, when it\n // set one. A driver that outlives the process schedules the timer from it.\n readonly deadline_ms: number | undefined;\n constructor(suspend_id: string, payload: unknown, message?: string, deadline_ms?: number) {\n super(message ?? `suspended at ${suspend_id}`)\n this.name = 'suspended_error'\n this.suspend_id = suspend_id\n this.payload = payload\n this.deadline_ms = deadline_ms\n }\n}\n\nexport class resume_validation_error extends Error {\n readonly kind = 'resume_validation_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly issues: ReadonlyArray<SchemaIssue>;\n // The gate whose resume data failed, so a driver can reject that one event\n // and leave the run waiting at the gate.\n readonly suspend_id: string | undefined;\n constructor(message: string, issues: ReadonlyArray<SchemaIssue>, suspend_id?: string) {\n super(message)\n this.name = 'resume_validation_error'\n this.issues = issues\n this.suspend_id = suspend_id\n }\n}\n\nexport class flow_changed_error extends Error {\n readonly kind = 'flow_changed_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly run_id: string;\n // Fingerprints of the flow's shape: the one the run started with, and the\n // one it was just asked to continue on.\n readonly started_on: string;\n readonly continued_on: string;\n constructor(run_id: string, started_on: string, continued_on: string) {\n super(\n `durable run ${run_id} started on a flow of another shape (${started_on}, now ${continued_on}): finish it on the flow it started with, delete it, or drive it with on_flow_change: 'replay'`,\n )\n this.name = 'flow_changed_error'\n this.run_id = run_id\n this.started_on = started_on\n this.continued_on = continued_on\n }\n}\n\n/**\n * What a `gate_result_error` says for `reason`: which gate resumed, why the\n * result it showed can't be served, and what to do about it.\n */\nfunction gate_result_message(\n suspend_id: string,\n reason: gate_result_error['reason'],\n cause: unknown,\n): string {\n if (reason === 'read_error') {\n const detail = cause instanceof Error ? cause.message : String(cause)\n return `gate ${suspend_id} resumed, and its store failed to read the result that it showed (${detail}): resume the run again once the store reads, since the approval is still in its resume data`\n }\n if (reason === 'missing') {\n return `gate ${suspend_id} resumed, and its store no longer holds the result that it showed: delete the run and start it again`\n }\n return `gate ${suspend_id} resumed with no store to serve the result that it showed: give the gate a store or the run a checkpoint_store, or use a plain suspend when the step is cheap and deterministic`\n}\n\nexport class gate_result_error extends Error {\n readonly kind = 'gate_result_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly suspend_id: string;\n // Why the result can't be served: the store failed the read (its error is\n // the `cause`), the store no longer holds it, or the gate has no store.\n readonly reason: 'read_error' | 'missing' | 'no_store';\n constructor(suspend_id: string, reason: gate_result_error['reason'], cause?: unknown) {\n super(gate_result_message(suspend_id, reason, cause), cause === undefined ? undefined : { cause })\n this.name = 'gate_result_error'\n this.suspend_id = suspend_id\n this.reason = reason\n }\n}\n\ntype DuplicateSuspendIdDetail = {\n // Each place's path of step ids from the root, for `declared_twice`.\n readonly paths?: ReadonlyArray<ReadonlyArray<string>>\n // How the message names each place, when a path alone doesn't tell two\n // places apart. Each path's ids, joined, by default.\n readonly labels?: ReadonlyArray<string>\n // Whether two of the places sit in different arms of one `branch`.\n readonly at_branch?: boolean\n}\n\n/**\n * What a `duplicate_suspend_id_error` says: where the id sits more than\n * once, or that a run reached it again on another input, and what to do\n * about it.\n */\nfunction duplicate_suspend_id_message(\n suspend_id: string,\n reason: duplicate_suspend_id_error['reason'],\n paths: ReadonlyArray<ReadonlyArray<string>>,\n detail: DuplicateSuspendIdDetail,\n): string {\n if (reason === 'reached_twice') {\n return `suspend ${suspend_id} was reached again in this run with another input, and its resume data answered the first one: a suspend takes one decision per run, so approve a map's batch at a gate before the map, or a loop's result at a gate after it`\n }\n const places = detail.labels ?? paths.map((path) => path.join(' > '))\n const arms =\n detail.at_branch === true\n ? \"; only one arm of a branch runs, but a resume replays its condition, so each arm's gate needs an id of its own\"\n : ''\n return `suspend id ${JSON.stringify(suspend_id)} is used in ${places.length} places (${places.join(', ')}): resume data is keyed by id, so give each suspend and gate an id of its own${arms}`\n}\n\nexport class duplicate_suspend_id_error extends Error {\n readonly kind = 'duplicate_suspend_id_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly suspend_id: string;\n // `declared_twice`: the flow holds the id in two or more places, refused\n // before the run starts. `reached_twice`: the run reached the id again on\n // another input, and its one datum answered the first.\n readonly reason: 'declared_twice' | 'reached_twice';\n // For `declared_twice`, each place's path of step ids from the root, and\n // empty for `reached_twice`.\n readonly paths: ReadonlyArray<ReadonlyArray<string>>;\n constructor(\n suspend_id: string,\n reason: duplicate_suspend_id_error['reason'],\n detail: DuplicateSuspendIdDetail = {},\n ) {\n const paths = detail.paths ?? []\n super(duplicate_suspend_id_message(suspend_id, reason, paths, detail))\n this.name = 'duplicate_suspend_id_error'\n this.suspend_id = suspend_id\n this.reason = reason\n this.paths = paths\n }\n}\n\nexport class run_not_found_error extends Error {\n readonly kind = 'run_not_found_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly run_id: string;\n constructor(run_id: string) {\n super(`no durable run ${run_id}: start it before resuming it`)\n this.name = 'run_not_found_error'\n this.run_id = run_id\n }\n}\n\nexport class describe_cycle_error extends Error {\n readonly kind = 'describe_cycle_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly step_id: string;\n constructor(step_id: string, message?: string) {\n super(message ?? `describe: cycle detected at step id: ${step_id}`)\n this.name = 'describe_cycle_error'\n this.step_id = step_id\n }\n}\n\nexport class aborted_error extends Error {\n readonly kind = 'aborted_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly reason?: unknown;\n // An engine tool-loop position, meaningful only when the abort interrupted a\n // model turn. Core-origin aborts (signals, caller AbortSignals) leave it\n // undefined rather than fabricating index 0.\n readonly step_index?: number;\n readonly tool_call_in_flight?: { id: string; name: string };\n constructor(\n message = 'aborted',\n metadata: {\n reason?: unknown\n step_index?: number\n tool_call_in_flight?: { id: string; name: string }\n } = {},\n ) {\n super(message)\n this.name = 'aborted_error'\n if (metadata.reason !== undefined) this.reason = metadata.reason\n if (metadata.step_index !== undefined) this.step_index = metadata.step_index\n if (metadata.tool_call_in_flight !== undefined) {\n this.tool_call_in_flight = metadata.tool_call_in_flight\n }\n }\n}\n\n/**\n * Control-flow signals are not application failures. `suspended_error` is a\n * human-approval gate pausing the run for later resume; `aborted_error` is\n * cancellation. Resilience composers (`retry`, `fallback`) must rethrow these\n * rather than retry past a suspend or run a backup under an aborted context.\n *\n * Kept internal to core: not re-exported by index.ts, so it does not\n * widen the public surface.\n */\nexport function is_control_flow_error(\n err: unknown,\n): err is suspended_error | aborted_error {\n return err instanceof suspended_error || err instanceof aborted_error\n}\n\n/**\n * Read the step-id path off any error that crossed the runner's dispatch.\n *\n * The runner attaches `path` to whatever escapes a step, including\n * user-thrown errors the declared class fields cannot type, so a catch block\n * needs a narrowing read rather than a cast. Returns the ids only when the\n * property is present and well-formed (an all-string array); anything else,\n * including non-object inputs, is `undefined`.\n */\nexport function error_path(err: unknown): ReadonlyArray<string> | undefined {\n if (err === null || typeof err !== 'object') return undefined\n const path: unknown = Reflect.get(err, 'path')\n if (!Array.isArray(path)) return undefined\n const entries: ReadonlyArray<unknown> = path\n const ids = entries.filter((v): v is string => typeof v === 'string')\n return ids.length === entries.length ? ids : undefined\n}\n","/**\n * is_step: structural Step check.\n *\n * Steps are plain objects with no brand symbol, so runtime detection is\n * structural: string `id`, string `kind`, callable `run`. Used by describe()\n * to render Step references and by combinators to validate arguments at\n * construction time.\n */\n\nimport type { AnyStep } from './types.js'\n\n/**\n * Check whether a value is structurally a `Step`.\n *\n * True when the value has a string `id`, a string `kind`, and a callable\n * `run`.\n */\nexport function is_step(value: unknown): value is AnyStep {\n if (typeof value !== 'object' || value === null) return false\n if (!('id' in value) || !('kind' in value) || !('run' in value)) return false\n const { id, kind, run } = value\n return typeof id === 'string' && typeof kind === 'string' && typeof run === 'function'\n}\n","/**\n * describe(step), describe.json(step), and describe.diagram(step):\n * composition introspection.\n *\n * `describe(step)` is the text-tree renderer. Multi-line string with\n * hierarchical indentation. Function values render as `<fn>` (or\n * `<fn:name>` when the function has a non-empty `name`); zod schemas\n * render as `<schema>`. A config entry that holds one of the node's own\n * children (a branch's `then` and `otherwise`) renders that child once, in\n * place of the config line, rather than again among the children.\n *\n * `describe.json(step)` returns a `FlowNode` tree (kind, id, config, children)\n * for tooling (the viewer, Mermaid renderers, diff tools). Function values\n * serialize as `{ kind: '<fn>', name? }` and schemas as `{ kind: '<schema>' }`.\n *\n * `describe.diagram(step)` draws the `describe.json` tree as an annotated\n * box-drawing diagram (see diagram.ts).\n *\n * `describe.replays(step)` reads the same tree for the steps marked\n * `side_effect` that a resumed run can run again before it reaches a gate\n * (see replays.ts).\n *\n * Every form detects cycles, since the diagram and the replay hints read the\n * `describe.json` tree. Under the default (loose) mode, back-references render\n * as `<cycle>(id)` in text and `{ kind: '<cycle>', id }` in JSON. Under\n * `{ strict: true }`, cycles throw `describe_cycle_error`.\n */\n\nimport { render_diagram, type DiagramOptions } from './diagram.js'\nimport { resolve_display_name } from './display_name.js'\nimport { describe_cycle_error } from './errors.js'\nimport { is_step } from './is_step.js'\nimport { find_replays, type ReplayHint } from './replays.js'\nimport type { AnyStep, FlowNode, FlowValue, Step, StepMetadata } from './types.js'\n\nconst INDENT = ' '\n\nexport type DescribeOptions = {\n readonly strict?: boolean\n}\n\ntype Path = Set<AnyStep>\n\n/**\n * Render a step tree as an indented multi-line string.\n */\nfunction describe_text<i, o>(root: Step<i, o>, options?: DescribeOptions): string {\n const lines: string[] = []\n const strict = Boolean(options?.strict)\n render_text(root, 0, lines, new Set(), strict)\n return lines.join('\\n')\n}\n\n/**\n * Render a step tree as a serializable `FlowNode` tree.\n */\nfunction describe_json<i, o>(root: Step<i, o>, options?: DescribeOptions): FlowNode {\n const strict = Boolean(options?.strict)\n return render_json(root, new Set(), strict)\n}\n\n/**\n * Render a step tree as an annotated box-drawing diagram. It is drawn from\n * the `describe.json` tree, so the output depends on the flow's shape alone.\n */\nfunction describe_diagram<i, o>(root: Step<i, o>, options?: DiagramOptions): string {\n return render_diagram(describe_json(root, options), options)\n}\n\n/**\n * Find the steps marked `side_effect` that a resumed run can run again before\n * it reaches a gate. Like the diagram, it reads the `describe.json` tree, so\n * it judges the flow's shape and runs nothing.\n */\nfunction describe_replays<i, o>(root: Step<i, o>, options?: DescribeOptions): ReadonlyArray<ReplayHint> {\n return find_replays(describe_json(root, options))\n}\n\n/**\n * Public entry point: `describe(step)` for text, `describe.json(step)` for\n * the `FlowNode` tree, `describe.diagram(step)` for the annotated diagram,\n * and `describe.replays(step)` for the steps a resume would pay for twice.\n */\nexport const describe: {\n <i, o>(root: Step<i, o>, options?: DescribeOptions): string\n json: <i, o>(root: Step<i, o>, options?: DescribeOptions) => FlowNode\n diagram: <i, o>(root: Step<i, o>, options?: DiagramOptions) => string\n replays: <i, o>(root: Step<i, o>, options?: DescribeOptions) => ReadonlyArray<ReplayHint>\n} = Object.assign(describe_text, { json: describe_json, diagram: describe_diagram, replays: describe_replays })\n\n/**\n * Append one node (label line, config lines, then children) to `lines`.\n *\n * `role` prefixes the label line when a parent's config entry names this\n * node. A config entry whose value is one of the node's own children renders\n * that child's whole subtree in its place, under the entry's key, and the\n * child is then skipped among the children so it appears once.\n *\n * `path` holds the steps on the current root-to-node path for cycle\n * detection; membership is added before recursing and removed in a `finally`\n * so shared (diamond) references are not misreported as cycles.\n */\nfunction render_text(\n node: AnyStep,\n depth: number,\n lines: string[],\n path: Path,\n strict: boolean,\n role = '',\n): void {\n const prefix = INDENT.repeat(depth)\n if (path.has(node)) {\n if (strict) throw new describe_cycle_error(node.id)\n lines.push(`${prefix}${role}<cycle>(${node.id})`)\n return\n }\n path.add(node)\n try {\n lines.push(`${prefix}${role}${resolve_display_name(node, node.kind)}(${node.id})`)\n const children = node.children ?? []\n const placed = new Set<AnyStep>()\n for (const [key, value] of Object.entries(node.config ?? {})) {\n if (key === 'display_name') continue\n if (is_step(value) && children.includes(value)) {\n placed.add(value)\n render_text(value, depth + 1, lines, path, strict, `${key}: `)\n } else {\n lines.push(`${prefix}${INDENT}${key}: ${render_value_text(value, path, strict)}`)\n }\n }\n for (const child of children) {\n if (!placed.has(child)) render_text(child, depth + 1, lines, path, strict)\n }\n } finally {\n path.delete(node)\n }\n}\n\n/**\n * Render a single config value for the text tree.\n *\n * Functions become `<fn>` or `<fn:name>`, zod schemas `<schema>`, and Step\n * references `kind(id)`; arrays and plain objects recurse. Strings are\n * JSON-quoted so empty and whitespace values stay visible.\n *\n * Steps, arrays, and renderable objects each own a branch; everything else\n * (functions, the empty markers, schemas, primitives) resolves through\n * `render_scalar_text`. The three object-shaped cases are mutually exclusive at\n * runtime, so their order relative to the scalar cases is immaterial.\n */\nfunction render_value_text(value: unknown, path: Path, strict: boolean): string {\n if (is_step(value)) return render_step_text(value, path, strict)\n if (Array.isArray(value)) {\n return `[${value.map((item: unknown) => render_value_text(item, path, strict)).join(', ')}]`\n }\n if (is_renderable_object(value)) {\n const entries = Object.entries({ ...value }).map(\n ([k, v]: [string, unknown]) => `${k}: ${render_value_text(v, path, strict)}`,\n )\n return `{ ${entries.join(', ')} }`\n }\n return render_scalar_text(value)\n}\n\n/**\n * Render a Step reference for the text tree: a back-reference on the current\n * path becomes `<cycle>(id)` (or throws under strict mode); otherwise `kind(id)`.\n */\nfunction render_step_text(value: AnyStep, path: Path, strict: boolean): string {\n if (path.has(value)) {\n if (strict) throw new describe_cycle_error(value.id)\n return `<cycle>(${value.id})`\n }\n return `${value.kind}(${value.id})`\n}\n\n/**\n * Render the non-recursive value cases for the text tree: functions (`<fn>` or\n * `<fn:name>`), the empty markers, zod schemas, and (via `render_primitive_text`)\n * raw primitives.\n */\nfunction render_scalar_text(value: unknown): string {\n if (typeof value === 'function') {\n const name = typeof value.name === 'string' && value.name.length > 0 ? value.name : ''\n return name ? `<fn:${name}>` : '<fn>'\n }\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n if (is_zod_schema(value)) return '<schema>'\n return render_primitive_text(value)\n}\n\n/**\n * Render a primitive (or unrecognized) value for the text tree. Strings are\n * JSON-quoted so empty and whitespace values stay visible; bigints keep an `n`\n * suffix; anything unexpected falls back to JSON.\n */\nfunction render_primitive_text(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value)\n if (typeof value === 'bigint') return `${value.toString()}n`\n if (typeof value === 'symbol') return value.toString()\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n return JSON.stringify(value)\n}\n\n/**\n * Convert one step node to a `FlowNode`, recursing into config and children.\n *\n * Uses the same path-based cycle detection as `render_text`: back-references\n * become `{ kind: '<cycle>', id }` in loose mode and throw in strict mode.\n */\nfunction render_json(\n node: AnyStep,\n path: Path,\n strict: boolean,\n): FlowNode {\n if (path.has(node)) {\n if (strict) throw new describe_cycle_error(node.id)\n return { kind: '<cycle>', id: node.id }\n }\n path.add(node)\n try {\n const result: {\n kind: string\n id: string\n config?: { [key: string]: FlowValue }\n children?: FlowNode[]\n meta?: StepMetadata\n anonymous?: boolean\n } = { kind: node.kind, id: node.id }\n if (node.config) {\n const config: { [key: string]: FlowValue } = {}\n for (const [key, value] of Object.entries(node.config)) {\n config[key] = render_value_json(value, path, strict)\n }\n result.config = config\n }\n if (node.children && node.children.length > 0) {\n result.children = node.children.map((child) => render_json(child, path, strict))\n }\n if (node.meta) {\n result.meta = node.meta\n }\n if (node.anonymous === true) {\n result.anonymous = true\n }\n return result\n } finally {\n path.delete(node)\n }\n}\n\n/**\n * Convert a single config value to a JSON-safe `FlowValue`.\n *\n * Functions serialize as `{ kind: '<fn>', name? }`, schemas as\n * `{ kind: '<schema>' }`, Step references as `{ kind, id }`. `undefined`\n * maps to `null` and bigints/symbols to strings so the result survives\n * `JSON.stringify` without loss.\n *\n * Mirrors `render_value_text`: steps, arrays, and renderable objects each own a\n * branch, and everything else resolves through `render_scalar_json`.\n */\nfunction render_value_json(value: unknown, path: Path, strict: boolean): FlowValue {\n if (is_step(value)) return render_step_json(value, path, strict)\n if (Array.isArray(value)) {\n return value.map((item: unknown) => render_value_json(item, path, strict))\n }\n if (is_renderable_object(value)) {\n const out: { [key: string]: FlowValue } = {}\n for (const [k, v] of Object.entries({ ...value })) {\n out[k] = render_value_json(v, path, strict)\n }\n return out\n }\n return render_scalar_json(value)\n}\n\n/**\n * Serialize a Step reference: a back-reference on the current path becomes\n * `{ kind: '<cycle>', id }` (or throws under strict mode); otherwise `{ kind, id }`.\n */\nfunction render_step_json(value: AnyStep, path: Path, strict: boolean): FlowValue {\n if (path.has(value)) {\n if (strict) throw new describe_cycle_error(value.id)\n return { kind: '<cycle>', id: value.id }\n }\n return { kind: value.kind, id: value.id }\n}\n\n/**\n * Serialize the non-recursive value cases: functions, the empty markers, zod\n * schemas, and (via `render_primitive_json`) raw primitives.\n */\nfunction render_scalar_json(value: unknown): FlowValue {\n if (typeof value === 'function') {\n const name = typeof value.name === 'string' && value.name.length > 0 ? value.name : ''\n return name ? { kind: '<fn>', name } : { kind: '<fn>' }\n }\n if (value === null) return null\n if (value === undefined) return null\n if (is_zod_schema(value)) return { kind: '<schema>' }\n return render_primitive_json(value)\n}\n\n/**\n * Serialize a primitive (or unrecognized) value. `undefined` already resolves\n * to `null` in `render_scalar_json`; bigints and symbols become strings so the\n * result survives `JSON.stringify` without loss.\n */\nfunction render_primitive_json(value: unknown): FlowValue {\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean') return value\n if (typeof value === 'bigint') return `${value.toString()}n`\n if (typeof value === 'symbol') return value.toString()\n return JSON.stringify(value)\n}\n\n/**\n * Detect a zod schema by its internal marker properties (`_zod` in zod 4,\n * `_def` in zod 3) without importing zod.\n */\nfunction is_zod_schema(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) return false\n return '_zod' in value || '_def' in value\n}\n\n/**\n * True for a plain object rendered by recursing into its own entries: an object\n * that is neither null nor a zod schema. The Step and array cases are checked\n * before this at every call site, so they never reach it.\n */\nfunction is_renderable_object(value: unknown): value is object {\n return typeof value === 'object' && value !== null && !is_zod_schema(value)\n}\n","/**\n * Streaming observation channel.\n *\n * `run.stream(flow, input)` is a secondary entry point returning\n * `{ events, result }`. Events are observed via an async iterable; the result\n * promise resolves once the flow completes. Streaming is purely\n * observational: composers do not know it exists, and `run` and `run.stream`\n * produce identical final results.\n *\n * The event buffer has a default high-water mark of 10,000. When the consumer\n * never iterates, emissions past the mark drop the oldest events and record a\n * single `events_dropped` marker. The `result` promise resolves regardless of\n * buffer pressure.\n */\n\nimport type { TrajectoryEvent, TrajectoryLogger } from './types.js'\n\nexport const STREAMING_HIGH_WATER_MARK = 10_000\n\nexport type StreamingChannel = {\n readonly logger: TrajectoryLogger\n readonly events: AsyncIterable<TrajectoryEvent>\n readonly close: () => void\n}\n\n/**\n * Build the logger/iterable pair backing `run.stream`.\n *\n * Wraps a base `TrajectoryLogger` so every recorded event is also enqueued\n * for the async iterable. A single pending `waiter` hands events straight to\n * a blocked consumer; otherwise events buffer up to `high_water_mark`, after\n * which the oldest are dropped and counted for the `events_dropped` marker\n * emitted at close.\n */\nexport function create_streaming_channel(\n base: TrajectoryLogger,\n high_water_mark = STREAMING_HIGH_WATER_MARK,\n): StreamingChannel {\n const buffer: TrajectoryEvent[] = []\n let dropped = 0\n let closed = false\n let marker_emitted = false\n let waiter: ((value: IteratorResult<TrajectoryEvent>) => void) | null = null\n\n function enqueue(event: TrajectoryEvent): void {\n if (closed) return\n if (waiter) {\n const resolve = waiter\n waiter = null\n resolve({ value: event, done: false })\n return\n }\n if (buffer.length >= high_water_mark) {\n buffer.shift()\n dropped += 1\n }\n buffer.push(event)\n }\n\n function close(): void {\n if (closed) return\n closed = true\n if (dropped > 0 && !marker_emitted) {\n marker_emitted = true\n buffer.push({ kind: 'events_dropped', count: dropped })\n }\n if (waiter) {\n const resolve = waiter\n waiter = null\n resolve({ value: undefined, done: true })\n }\n }\n\n const logger: TrajectoryLogger = {\n record: (event) => {\n base.record(event)\n enqueue(event)\n },\n start_span: (name, meta) => {\n const id = base.start_span(name, meta)\n enqueue({ kind: 'span_start', span_id: id, name, ...meta })\n return id\n },\n end_span: (id, meta) => {\n base.end_span(id, meta)\n enqueue({ kind: 'span_end', span_id: id, ...meta })\n },\n }\n\n const events: AsyncIterable<TrajectoryEvent> = {\n [Symbol.asyncIterator]() {\n return {\n next(): Promise<IteratorResult<TrajectoryEvent>> {\n if (buffer.length > 0) {\n const next_event = buffer.shift()\n if (next_event !== undefined) {\n return Promise.resolve({ value: next_event, done: false })\n }\n }\n if (closed) {\n return Promise.resolve({ value: undefined, done: true })\n }\n return new Promise<IteratorResult<TrajectoryEvent>>((resolve) => {\n waiter = resolve\n })\n },\n return(): Promise<IteratorResult<TrajectoryEvent>> {\n close()\n return Promise.resolve({ value: undefined, done: true })\n },\n }\n },\n }\n\n return { logger, events, close }\n}\n","/**\n * suspend_ids: one suspend id, one place in the flow.\n *\n * Resume data is keyed by suspend id, so a `suspend` finds its datum by id\n * alone, and a second `suspend` or `gate` with the same id would pass on the\n * first one's datum without pausing. `check_suspend_ids(flow)` walks the\n * declared tree before a run starts and throws `duplicate_suspend_id_error`\n * with `reason: 'declared_twice'` for the first id, in flow order, that sits\n * in two or more places. A `gate` counts through the `suspend` inside it, and\n * one `suspend` value placed twice counts in each place.\n *\n * The walk refuses an id in two arms of a `branch` as well. Only one arm runs\n * per pass, but a resume replays the branch's condition, and a condition that\n * comes out the other way would hand one arm's approval to the other.\n *\n * The walk reads `children` and guards against a cycle with the steps on the\n * current path from the root, the way `describe` does, so a step that two\n * paths reach counts once per path, and a step that is its own ancestor is\n * skipped where it comes back. A step never changes once it's built, so the\n * answer is kept per root step and each root is walked once.\n *\n * What the walk can't see, a run can: a `suspend` that a `loop` reaches in a\n * later round, or a `map` for its next item. `same_input_as(first)` is the\n * test the runner holds each later reach to, so a run takes each id's datum\n * once, or again on the same input, the way a `retry` runs a step again.\n */\n\nimport { duplicate_suspend_id_error } from './errors.js'\nimport type { AnyStep } from './types.js'\n\n// One step on the way to a suspend, with its position among its parent's\n// children, counted from 1, and 0 for the root.\ntype Frame = { readonly step: AnyStep; readonly position: number }\n\n// A suspend's place in the tree: the frames from the root down to it.\ntype Place = ReadonlyArray<Frame>\n\ntype Refusal = {\n readonly suspend_id: string\n readonly paths: ReadonlyArray<ReadonlyArray<string>>\n readonly labels: ReadonlyArray<string>\n readonly at_branch: boolean\n}\n\nconst refusals = new WeakMap<AnyStep, Refusal | null>()\n\n/**\n * Add the place of every `suspend` at or under `step` to `found`, by id, in\n * the order the walk meets them. `on_path` holds the steps between the root\n * and `step`, so a step met again among its own descendants is skipped.\n */\nfunction collect(\n step: AnyStep,\n trail: Place,\n on_path: Set<AnyStep>,\n found: Map<string, Place[]>,\n): void {\n if (on_path.has(step)) return\n if (step.kind === 'suspend') found.set(step.id, [...(found.get(step.id) ?? []), trail])\n on_path.add(step)\n // Stryker disable next-line ArrayDeclaration: a stray child seeded into a leaf is no suspend, and the path guard skips the same stray child beneath it, so it adds no place.\n for (const [index, child] of (step.children ?? []).entries()) {\n collect(child, [...trail, { step: child, position: index + 1 }], on_path, found)\n }\n on_path.delete(step)\n}\n\n/**\n * The depth at which two places first go separate ways. Both start at the\n * root, and two children of one parent at one position are the same step,\n * so the first position that differs is where they part, and -1 means one\n * place holds the other.\n */\nfunction parting_depth(a: Place, b: Place): number {\n return a.findIndex((frame, depth) => frame.position !== b[depth]?.position)\n}\n\n/**\n * How the refusal names `place`: its step ids from the root, with a step's\n * position under its parent added at each depth where the place parts from\n * a twin, another place whose ids read the same. A place among its own\n * twins parts from itself at -1, which marks no step.\n */\nfunction label_of(place: Place, twins: ReadonlyArray<Place>): string {\n const marked = new Set(twins.map((twin) => parting_depth(place, twin)))\n return place\n .map((frame, depth) => (marked.has(depth) ? `${frame.step.id} (step ${frame.position})` : frame.step.id))\n .join(' > ')\n}\n\n/**\n * The refusal for `suspend_id`, which sits at each of `places`.\n */\nfunction refusal_for(suspend_id: string, places: ReadonlyArray<Place>): Refusal {\n const paths = places.map((place) => place.map((frame) => frame.step.id))\n const keys = paths.map((path) => JSON.stringify(path))\n const labels = places.map((place, i) =>\n label_of(\n place,\n places.filter((_, j) => keys[j] === keys[i]),\n ),\n )\n // A parting depth of -1, for a place and itself or a place and one inside\n // it, reads index -2, which holds nothing, so it never parts at a branch.\n const at_branch = places.some((a) =>\n places.some((b) => a[parting_depth(a, b) - 1]?.step.kind === 'branch'),\n )\n return { suspend_id, paths, labels, at_branch }\n}\n\n/**\n * The refusal for the first id in flow order that sits in two or more places\n * under `root`, or `null` when every id sits in one.\n */\nfunction find_refusal(root: AnyStep): Refusal | null {\n const found = new Map<string, Place[]>()\n collect(root, [{ step: root, position: 0 }], new Set(), found)\n for (const [suspend_id, places] of found) {\n if (places.length > 1) return refusal_for(suspend_id, places)\n }\n return null\n}\n\n/**\n * Throw `duplicate_suspend_id_error` when `root` holds one suspend id in two\n * or more places. The runner calls this before the first step of every run,\n * and the answer is kept per root, so a flow is walked once however often it\n * runs.\n */\nexport function check_suspend_ids(root: AnyStep): void {\n let refusal = refusals.get(root)\n if (refusal === undefined) {\n refusal = find_refusal(root)\n refusals.set(root, refusal)\n }\n if (refusal !== null) {\n throw new duplicate_suspend_id_error(refusal.suspend_id, 'declared_twice', refusal)\n }\n}\n\n/**\n * Sort an object's keys as `JSON.stringify` meets it, so two objects that\n * hold the same entries in another order write the same JSON. An array keeps\n * its order, since its order is its content.\n */\nfunction sort_keys(_: string, value: unknown): unknown {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return value\n return Object.fromEntries(Object.keys(value).toSorted().map((key) => [key, Reflect.get(value, key)]))\n}\n\n/**\n * The stable JSON of `value`, its keys sorted, or `undefined` when JSON\n * can't hold it: `JSON.stringify` throws (a `BigInt`, a cycle) or writes\n * nothing (`undefined`, a function).\n */\nfunction stable_json(value: unknown): string | undefined {\n try {\n return JSON.stringify(value, sort_keys)\n } catch {\n // A value that makes JSON.stringify throw has no stable JSON.\n }\n return undefined\n}\n\n/**\n * A test of whether a later input is the same as `first`, which a resume\n * datum taken for `first` answers as well.\n *\n * `first` is snapshotted now, as stable JSON with its keys sorted, and a\n * later input matches when its stable JSON is the same, so a `retry` that\n * reaches a step again on a copy of its input passes, while an object that\n * a `loop` changed in place since doesn't, since the datum answered what the\n * object held then. When JSON can't hold `first`, a later input matches\n * only when it's the same value by `Object.is`.\n */\nexport function same_input_as(first: unknown): (next: unknown) => boolean {\n const snapshot = stable_json(first)\n if (snapshot === undefined) return (next) => Object.is(next, first)\n return (next) => stable_json(next) === snapshot\n}\n","/**\n * Runner.\n *\n * Dispatches a step to its kind-specific handler. `runner.ts` contains no\n * composer-specific logic beyond a Map lookup on `step.kind`; each composer\n * file registers its handler at module load via `register_traced_kind(...)`.\n *\n * `run(flow, input, options?)` constructs a fresh `RunContext` per top-level\n * call, installs process signal handlers (opt-out via options), forwards an\n * optional caller-supplied `AbortSignal` into the run, and guarantees cleanup\n * handlers execute in LIFO order on success, failure, or abort.\n *\n * A SIGINT or SIGTERM aborts only the runs that installed the handlers. A run\n * started with `install_signal_handlers: false` keeps going through a signal,\n * even while another run's handlers are installed, because opting out says\n * the host forwards cancellation itself, through `abort`.\n *\n * `run.stream(flow, input, options?)` is a secondary entry point returning\n * `{ events, result }`. Streaming is purely observational; the step graph is\n * identical to `run(...)`.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { create_cleanup_registry } from './cleanup.js'\nimport { describe } from './describe.js'\nimport { resolve_display_name } from './display_name.js'\nimport { aborted_error, duplicate_suspend_id_error, suspended_error } from './errors.js'\nimport { create_streaming_channel, STREAMING_HIGH_WATER_MARK } from './streaming.js'\nimport { check_suspend_ids, same_input_as } from './suspend_ids.js'\nimport type {\n AnyStep,\n CheckpointStore,\n RunContext,\n Step,\n TrajectoryEvent,\n TrajectoryLogger,\n} from './types.js'\n\ntype Dispatcher = (\n flow: AnyStep,\n input: unknown,\n ctx: RunContext,\n) => Promise<unknown>\n\nconst dispatch = new Map<string, Dispatcher>()\n\n// The gates each resumed run holds resume data for and hasn't reached yet, by\n// run id. A step marked `side_effect` that starts while its run still has one\n// is redoing work that an earlier attempt already did.\nconst unreached_gates = new Map<string, Set<string>>()\n\n// The resume data each run has taken, by run id: for each suspend id, the\n// test that a later reach's input has to pass, since the one datum answered\n// the input it was taken for.\nconst taken_data = new Map<string, Map<string, (input: unknown) => boolean>>()\n\n/**\n * Register the dispatch handler for a step kind.\n *\n * Composer files call this via `register_traced_kind` at module load, which is\n * how the runner stays free of composer-specific logic.\n */\nfunction register_kind(kind: string, fn: Dispatcher): void {\n dispatch.set(kind, fn)\n}\n\n/**\n * Register the standard span-wrapping dispatch handler for a composer kind.\n *\n * Every composer wraps `flow.run` in a span identically; this centralizes that\n * boilerplate and threads span parentage: the span opens with the current\n * `ctx.parent_span_id` as its parent, and `flow.run` receives a child context\n * whose `parent_span_id` is this span. Children dispatched from within\n * (including concurrent ones under `parallel`/`map`, which spread the context)\n * therefore nest correctly instead of leaving `parent_span_id` unpopulated.\n */\nexport function register_traced_kind(kind: string): void {\n register_kind(kind, async (flow, input, ctx) => {\n const label = resolve_display_name(flow, kind)\n const span_meta: Record<string, unknown> = { id: flow.id }\n if (ctx.parent_span_id !== undefined) {\n span_meta['parent_span_id'] = ctx.parent_span_id\n }\n const span_id = ctx.trajectory.start_span(label, span_meta)\n if (flow.meta?.side_effect === true) record_replay(flow, ctx, span_id)\n const child_ctx: RunContext = { ...ctx, parent_span_id: span_id }\n try {\n // The dispatch table is the type-erasure boundary: `dispatch_step`\n // pairs each step with the input its parent produced for it, a pairing\n // `AnyStep` (input `never`) cannot carry, so the call re-asserts it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const out = await flow.run(input as never, child_ctx)\n ctx.trajectory.end_span(span_id, { id: flow.id })\n return out\n } catch (err) {\n ctx.trajectory.end_span(span_id, { id: flow.id, ...error_meta(err) })\n throw err\n }\n })\n}\n\n/**\n * Record a `step_replayed` event for `flow`, a step marked `side_effect`, when\n * it starts before its run has reached every gate the run was resumed with.\n * The event names the gates still ahead, and it carries the step's own span.\n */\nfunction record_replay(flow: AnyStep, ctx: RunContext, span_id: string): void {\n const unreached = unreached_gates.get(ctx.run_id)\n if (unreached === undefined) return\n ctx.trajectory.record({\n kind: 'step_replayed',\n step_id: flow.id,\n span_id,\n suspend_ids: [...unreached],\n })\n}\n\n/**\n * Note that a run has reached `suspend_ids`: a `suspend` consumed its resume\n * data, or a checkpoint hit stood in for the gates inside it. Once a run has\n * reached all of them, nothing it runs afterwards is a replay.\n */\nexport function mark_gates_reached(ctx: RunContext, suspend_ids: Iterable<string>): void {\n const unreached = unreached_gates.get(ctx.run_id)\n if (unreached === undefined) return\n for (const id of suspend_ids) unreached.delete(id)\n if (unreached.size === 0) unreached_gates.delete(ctx.run_id)\n}\n\n/**\n * Note that a `suspend` took its resume datum for `input`. The first take of\n * `suspend_id` in a run keeps a test of its input. A later take on the same\n * input passes, since a `retry` ran the step again, and one on another input\n * throws `duplicate_suspend_id_error` with `reason: 'reached_twice'`, since\n * the run's one datum for the id answered the first.\n */\nexport function note_datum_taken(ctx: RunContext, suspend_id: string, input: unknown): void {\n const taken = taken_data.get(ctx.run_id) ?? new Map<string, (input: unknown) => boolean>()\n taken_data.set(ctx.run_id, taken)\n const same = taken.get(suspend_id)\n if (same === undefined) {\n taken.set(suspend_id, same_input_as(input))\n } else if (!same(input)) {\n throw new duplicate_suspend_id_error(suspend_id, 'reached_twice')\n }\n}\n\n/**\n * Start tracking the gates a run was resumed with, the ones `resume_data`\n * holds a value for. A run started without any is never replaying.\n */\nfunction track_resumed_gates(\n run_id: string,\n resume_data: Readonly<Record<string, unknown>> | undefined,\n): void {\n const resumed = Object.entries(resume_data ?? {})\n .filter(([, value]) => value !== undefined)\n .map(([id]) => id)\n if (resumed.length > 0) unreached_gates.set(run_id, new Set(resumed))\n}\n\n/**\n * Project an escaping error onto trajectory meta fields.\n *\n * `error` is always present (the message); `error_name` and `error_kind`\n * surface the class name and the `kind` discriminant the typed error classes\n * carry, so a consumer can classify a failure without regex-matching the\n * message. `error_path` is the chain of step ids the error crossed below this\n * point, already accumulated on the error by `prepend_path` as it bubbled up.\n */\nfunction error_meta(err: unknown): Record<string, unknown> {\n const meta: Record<string, unknown> = {\n error: err instanceof Error ? err.message : String(err),\n }\n if (err instanceof Error && err.name.length > 0) meta['error_name'] = err.name\n if (err !== null && typeof err === 'object') {\n const kind = Reflect.get(err, 'kind')\n if (typeof kind === 'string') meta['error_kind'] = kind\n const path = Reflect.get(err, 'path')\n if (Array.isArray(path)) {\n meta['error_path'] = path.filter((v): v is string => typeof v === 'string')\n }\n }\n return meta\n}\n\nexport type RunOptions = {\n // Default true. False keeps the run out of the set that a SIGINT or SIGTERM\n // aborts, and leaves the process's signal handling to the host.\n readonly install_signal_handlers?: boolean\n readonly trajectory?: TrajectoryLogger\n readonly checkpoint_store?: CheckpointStore\n readonly resume_data?: Readonly<Record<string, unknown>>\n // A caller-owned cancellation source (HTTP request, queue shutdown, MCP\n // request, AbortSignal.timeout). When it fires the run aborts with its\n // reason, composing with the internal controller and the process signal\n // handlers rather than replacing them.\n readonly abort?: AbortSignal\n}\n\nexport type StreamingRunHandle<o> = {\n readonly events: AsyncIterable<TrajectoryEvent>\n readonly result: Promise<o>\n}\n\n// Only the runs that installed the signal handlers, so a signal never aborts\n// a run whose host opted out.\nconst signal_runs = new Set<AbortController>()\nlet signal_handler_installed = false\nlet sigint_handler: (() => void) | null = null\nlet sigterm_handler: (() => void) | null = null\n\n/**\n * Build the handler for one process signal: it aborts every run that installed\n * the handlers with an `aborted_error` that names the signal.\n */\nfunction abort_all_on(signal_name: string): () => void {\n return () => {\n for (const controller of signal_runs) {\n controller.abort(new aborted_error(`received ${signal_name}`, { reason: { signal: signal_name } }))\n }\n }\n}\n\n/**\n * Install process-wide SIGINT/SIGTERM handlers once.\n *\n * The handlers abort every run that installed them with an `aborted_error`\n * naming the signal, so a Ctrl-C tears down those flows through the normal\n * abort/cleanup path instead of killing the process mid-step.\n */\nfunction ensure_signal_handlers(): void {\n if (signal_handler_installed) return\n signal_handler_installed = true\n sigint_handler = abort_all_on('SIGINT')\n sigterm_handler = abort_all_on('SIGTERM')\n process.on('SIGINT', sigint_handler)\n process.on('SIGTERM', sigterm_handler)\n}\n\n/**\n * Remove the process signal handlers once the last run that installed them\n * settles.\n *\n * Keeps a library embed from leaving stray `process.on` listeners behind\n * after all runs complete.\n */\nfunction release_signal_handlers(): void {\n if (!signal_handler_installed) return\n if (signal_runs.size > 0) return\n signal_handler_installed = false\n if (sigint_handler) process.off('SIGINT', sigint_handler)\n if (sigterm_handler) process.off('SIGTERM', sigterm_handler)\n sigint_handler = null\n sigterm_handler = null\n}\n\nconst noop_logger: TrajectoryLogger = {\n record: () => {},\n start_span: (name) => `${name}:${randomUUID().slice(0, 8)}`,\n end_span: () => {},\n}\n\n/**\n * Wrap a logger so every emitted event automatically carries `run_id` and a\n * `ts` (epoch milliseconds) stamped at emission.\n *\n * The viewer and other downstream consumers multiplex events across runs by\n * `run_id` and reconstruct real timing from `ts` instead of fabricating it at\n * ingest. Either field already present on an event or its meta is preserved;\n * we never overwrite a caller-supplied value.\n */\nfunction decorate_logger(inner: TrajectoryLogger, run_id: string): TrajectoryLogger {\n const stamp_meta = (\n meta: Record<string, unknown> | undefined,\n ): Record<string, unknown> => {\n const out: Record<string, unknown> = { ...meta }\n if (!('run_id' in out)) out['run_id'] = run_id\n if (!('ts' in out)) out['ts'] = Date.now()\n return out\n }\n return {\n record: (event) => {\n if ('run_id' in event && 'ts' in event) {\n inner.record(event)\n return\n }\n const extra: Record<string, unknown> = {}\n if (!('run_id' in event)) extra['run_id'] = run_id\n if (!('ts' in event)) extra['ts'] = Date.now()\n inner.record({ ...event, ...extra })\n },\n start_span: (name, meta) => inner.start_span(name, stamp_meta(meta)),\n end_span: (id, meta) => {\n inner.end_span(id, stamp_meta(meta))\n },\n }\n}\n\n/**\n * Route a step to its registered kind handler.\n *\n * This is the single entry point composers use to run children. On failure\n * the step's id is prepended to the error's `path`, so an error surfacing\n * from a deep tree carries the chain of step ids it crossed.\n */\nexport async function dispatch_step<i, o>(\n flow: Step<i, o>,\n input: i,\n ctx: RunContext,\n): Promise<o> {\n const handler = dispatch.get(flow.kind)\n if (!handler) {\n throw new Error(`unknown step kind: ${flow.kind} (step id: ${flow.id})`)\n }\n try {\n const result = await handler(flow, input, ctx)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return result as o\n } catch (err) {\n prepend_path(err, flow.id)\n throw err\n }\n}\n\n/**\n * Prepend a step id to the `path` array carried on an error object.\n *\n * Mutates the error in place so the path accumulates as the error bubbles up\n * through nested dispatches. Non-object errors are left untouched.\n */\nfunction prepend_path(err: unknown, id: string): void {\n if (err === null || typeof err !== 'object') return\n const existing = Reflect.get(err, 'path')\n const next: string[] = Array.isArray(existing)\n ? [id, ...existing.filter((v): v is string => typeof v === 'string')]\n : [id]\n Reflect.set(err, 'path', next)\n}\n\n/**\n * Throw the abort reason if the context has been cancelled. Composers that\n * iterate over children (`sequence`, `scope`, `loop`) call this between steps\n * so a pending abort is honored before the next child starts, not only when a\n * downstream dispatch happens to observe it.\n */\nexport function throw_if_aborted(ctx: RunContext): void {\n if (!ctx.abort.aborted) return\n const reason = ctx.abort.reason\n throw reason instanceof Error ? reason : new aborted_error('aborted', { reason })\n}\n\n/**\n * Install a fan-out abort listener over a set of child controllers: when\n * `ctx.abort` fires, every controller currently in `controllers` is aborted\n * with the same reason. An already-aborted parent fires immediately instead\n * of registering a listener.\n *\n * Concurrent composers (`map`, `parallel`) use this to propagate a parent\n * abort into each in-flight child's composed signal. `controllers` is read by\n * reference, so a caller that appends to the array after installing (as\n * `map` does per newly started item) is still covered by later aborts.\n * Returns the listener so the caller can remove it once its children settle.\n */\nexport function install_abort_fan_out(\n ctx: RunContext,\n controllers: ReadonlyArray<AbortController>,\n): () => void {\n const on_parent_abort = (): void => {\n for (const c of controllers) c.abort(ctx.abort.reason)\n }\n if (ctx.abort.aborted) {\n on_parent_abort()\n } else {\n ctx.abort.addEventListener('abort', on_parent_abort, { once: true })\n }\n return on_parent_abort\n}\n\n/**\n * Forward a caller-owned AbortSignal into the run's internal controller and\n * return an unlink function. The reason is preserved so the original\n * cancellation cause propagates out of `run`. The listener is `once` and the\n * returned unlink is called when the run settles, so a long-lived host (an MCP\n * server, an HTTP worker) firing many short runs against one external signal\n * does not accumulate listeners.\n */\nfunction link_external_abort(\n controller: AbortController,\n external: AbortSignal | undefined,\n): () => void {\n if (external === undefined) return () => {}\n if (external.aborted) {\n controller.abort(external.reason)\n return () => {}\n }\n const on_abort = (): void => {\n controller.abort(external.reason)\n }\n external.addEventListener('abort', on_abort, { once: true })\n return () => {\n external.removeEventListener('abort', on_abort)\n }\n}\n\ntype StartResult<o> = {\n readonly events: AsyncIterable<TrajectoryEvent>\n readonly result: Promise<o>\n}\n\n/**\n * Construct a run context and execute a flow to settlement.\n *\n * Shared engine behind `run` and `run.stream`; `high_water_mark` selects the\n * mode (null means no streaming channel). Owns the full run lifecycle:\n * abort wiring, logger decoration, cleanup registration, signal handlers,\n * the `flow_structure` event that opens an observed run, and the\n * settle-time teardown ordering (cleanup handlers first, then unlinking and\n * stream close).\n */\nfunction start_run<i, o>(\n flow: Step<i, o>,\n input: i,\n options: RunOptions,\n high_water_mark: number | null,\n): StartResult<o> {\n const install_signal_handlers = options.install_signal_handlers !== false\n const base_logger = options.trajectory ?? noop_logger\n const streaming = high_water_mark !== null\n\n const controller = new AbortController()\n const unlink_abort = link_external_abort(controller, options.abort)\n const run_id = randomUUID()\n\n let stream_events: AsyncIterable<TrajectoryEvent> = empty_async_iterable()\n let close_stream: (() => void) | null = null\n let inner: TrajectoryLogger = base_logger\n\n if (streaming) {\n // Decorate must wrap the streaming channel, not the reverse: the channel\n // enqueues a copy of each event for `run.stream` consumers, so it has to\n // see the events after `decorate_logger` has stamped `ts` and `run_id`.\n const channel = create_streaming_channel(base_logger, high_water_mark)\n inner = channel.logger\n stream_events = channel.events\n close_stream = channel.close\n }\n\n const logger: TrajectoryLogger = decorate_logger(inner, run_id)\n\n // Structure is worth its one describe() walk only when something will see\n // it: a real logger, or a run.stream() consumer reading the channel.\n if (options.trajectory !== undefined || streaming) {\n logger.record({ kind: 'flow_structure', structure: describe.json(flow) })\n }\n\n const cleanup = create_cleanup_registry(logger)\n\n const ctx: RunContext = {\n run_id,\n trajectory: logger,\n state: new Map(),\n abort: controller.signal,\n emit: (event) => {\n logger.record({ ...event, kind: 'emit' })\n },\n on_cleanup: (fn) => {\n cleanup.register(fn)\n },\n call<ci, co>(this: RunContext, s: Step<ci, co>, child_input: ci): Promise<co> {\n throw_if_aborted(this)\n return dispatch_step(s, child_input, this)\n },\n checkpoint_store: options.checkpoint_store,\n resume_data: options.resume_data,\n streaming,\n }\n\n track_resumed_gates(run_id, options.resume_data)\n if (install_signal_handlers) {\n signal_runs.add(controller)\n ensure_signal_handlers()\n }\n\n const result = (async (): Promise<o> => {\n let terminal: TrajectoryEvent = { kind: 'run_end', status: 'done' }\n try {\n // Honor an external signal that was already aborted at call time, so the\n // run rejects without dispatching even when the flow is a single leaf\n // step that never reaches a cooperative abort check.\n throw_if_aborted(ctx)\n // A flow that holds one suspend id in two places is refused before any\n // step runs, and the refusal ends the run as failed like any other.\n check_suspend_ids(flow)\n return await dispatch_step(flow, input, ctx)\n } catch (err) {\n let thrown: unknown = err\n if (controller.signal.aborted && !(err instanceof aborted_error)) {\n const reason = controller.signal.reason\n if (reason instanceof aborted_error) thrown = reason\n }\n // A caller may abort with a plain-Error cause, which surfaces verbatim\n // rather than as aborted_error; identity with the signal reason is what\n // marks that ending as a cancellation rather than a failure.\n const was_aborted =\n thrown instanceof aborted_error ||\n (controller.signal.aborted && thrown === controller.signal.reason)\n terminal = run_end_event(thrown, was_aborted)\n throw thrown\n } finally {\n try {\n await cleanup.run_all()\n } finally {\n // Recorded after cleanup so run_end is the true last event of the\n // run, and before the stream closes so `run.stream` consumers see it.\n logger.record(terminal)\n unreached_gates.delete(run_id)\n // Stryker disable next-line CallExpression: a run id is never used again, so a note left behind changes no later run, and dropping it only keeps the map from growing.\n taken_data.delete(run_id)\n unlink_abort()\n signal_runs.delete(controller)\n release_signal_handlers()\n if (close_stream) close_stream()\n }\n }\n })()\n\n return { events: stream_events, result }\n}\n\n/**\n * Build the terminal `run_end` event for a run that did not complete.\n *\n * Control-flow endings get their own statuses (`aborted`, `suspended`) so a\n * consumer never has to sniff error text to tell a cancellation or a pending\n * approval from a real failure; only `failed` carries the full error meta.\n */\nfunction run_end_event(err: unknown, was_aborted: boolean): TrajectoryEvent {\n if (err instanceof suspended_error) {\n return { kind: 'run_end', status: 'suspended', suspend_id: err.suspend_id }\n }\n if (was_aborted) {\n return {\n kind: 'run_end',\n status: 'aborted',\n error: err instanceof Error ? err.message : String(err),\n }\n }\n return { kind: 'run_end', status: 'failed', ...error_meta(err) }\n}\n\n/**\n * Build an async iterable that is immediately done.\n *\n * Non-streaming runs hand this to callers so the `events` field always has\n * the same shape regardless of mode.\n */\nfunction empty_async_iterable(): AsyncIterable<TrajectoryEvent> {\n return {\n [Symbol.asyncIterator]() {\n return {\n next: (): Promise<IteratorResult<TrajectoryEvent>> =>\n Promise.resolve({ value: undefined, done: true } as IteratorResult<TrajectoryEvent>),\n }\n },\n }\n}\n\n/**\n * Execute a flow and resolve with its final output.\n */\nasync function run_impl<i, o>(\n flow: Step<i, o>,\n input: i,\n options: RunOptions = {},\n): Promise<o> {\n const { result } = start_run(flow, input, options, null)\n return result\n}\n\n/**\n * Execute a flow while exposing its trajectory events as an async iterable.\n */\nfunction run_stream<i, o>(\n flow: Step<i, o>,\n input: i,\n options: RunOptions = {},\n): StreamingRunHandle<o> {\n const { events, result } = start_run(flow, input, options, STREAMING_HIGH_WATER_MARK)\n return { events, result }\n}\n\nexport type RunOutcome<o> =\n | { readonly kind: 'done'; readonly output: o }\n | {\n readonly kind: 'suspended'\n readonly id: string\n // Whatever the suspend gate raised (for the built-in `suspend` composer,\n // `{ input }`), so a driver loop can render what awaits approval without\n // re-running the flow. `unknown` because gates declare no payload type.\n readonly payload: unknown\n // How long the gate waits before its deadline passes, present when the\n // gate set one. The caller owns the timer and the clock it starts.\n readonly deadline_ms?: number\n readonly resume: (data: unknown) => Promise<RunOutcome<o>>\n }\n\n/**\n * Execute a flow, reporting suspension as a typed outcome instead of a\n * thrown `suspended_error`.\n *\n * Resolves `{ kind: 'done', output }` on completion. When a `suspend` gate\n * fires, resolves `{ kind: 'suspended', id, payload, resume }` where `id` is\n * the gate's suspend id, `payload` is what the gate raised on its\n * `suspended_error` (plus `deadline_ms`, when the gate set one), and\n * `resume(data)` re-runs the flow from the original\n * input with `resume_data[id] = data` merged over the caller's options: the\n * same full re-run semantics as calling `run` again yourself, so pure\n * prefixes replay and `checkpoint`ed steps are served from the store. The\n * returned promise resolves to the next outcome, so a flow with several\n * gates is driven by awaiting `resume` repeatedly. Real errors still throw,\n * from the initial call and from `resume` alike.\n */\nasync function run_until_suspended<i, o>(\n flow: Step<i, o>,\n input: i,\n options: RunOptions = {},\n): Promise<RunOutcome<o>> {\n try {\n return { kind: 'done', output: await run_impl(flow, input, options) }\n } catch (err) {\n if (!(err instanceof suspended_error)) throw err\n const id = err.suspend_id\n return {\n kind: 'suspended',\n id,\n payload: err.payload,\n ...(err.deadline_ms === undefined ? {} : { deadline_ms: err.deadline_ms }),\n resume: (data) =>\n run_until_suspended(flow, input, {\n ...options,\n resume_data: { ...options.resume_data, [id]: data },\n }),\n }\n }\n}\n\n/**\n * The public entry point for executing a flow.\n *\n * Callable as `run(flow, input, options?)` for a plain result,\n * `run.stream(flow, input, options?)` for `{ events, result }`, or\n * `run.until_suspended(flow, input, options?)` for a `RunOutcome` that\n * carries suspension as data. All share one implementation, so every entry\n * point runs the same graph identically.\n */\nexport const run: typeof run_impl & {\n stream: typeof run_stream\n until_suspended: typeof run_until_suspended\n} = Object.assign(run_impl, {\n stream: run_stream,\n until_suspended: run_until_suspended,\n})\n","/**\n * Validation against any Standard Schema implementation, and the one-line\n * rendering of its failures that repair prompts and error messages use.\n */\n\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type { AnySchema, SchemaIssue, ValidateOutcome } from './types.js'\n\n/**\n * Validate `value` against `schema`, returning the typed value or the issues.\n *\n * Always async, even for a validator that answers synchronously: the spec\n * permits `validate` to return either a result or a promise of one, and\n * Fascicle cannot know which a given vendor does. Awaiting a non-promise is\n * cheap; guessing wrong is a silent bug.\n */\nexport async function validate_schema<t>(\n schema: AnySchema<t>,\n value: unknown,\n): Promise<ValidateOutcome<t>> {\n const result = await schema['~standard'].validate(value)\n if (result.issues) return { ok: false, issues: result.issues.map(normalize_issue) }\n return { ok: true, value: result.value }\n}\n\n/**\n * Flatten one vendor issue into Fascicle's shape.\n *\n * The spec allows a path segment to be a bare key or a `{ key }` wrapper, and\n * allows the path to be absent entirely. Normalizing here means no consumer has\n * to know which vendor produced the issue.\n */\nfunction normalize_issue(issue: StandardSchemaV1.Issue): SchemaIssue {\n if (issue.path === undefined) return { message: issue.message }\n const path = issue.path.map((segment) =>\n typeof segment === 'object' ? segment.key : segment,\n )\n return { message: issue.message, path }\n}\n\n/**\n * Render issues as the single line that goes into an error message or a repair\n * prompt fed back to the model.\n *\n * Paths are dotted (`address.city`, `items.0.name`) rather than bracketed for\n * indices: the model reads it as a hint about which field to fix, and one\n * consistent separator is easier to follow than two.\n */\nexport function format_schema_issues(issues: ReadonlyArray<SchemaIssue>): string {\n if (issues.length === 0) return 'unknown schema issue'\n return issues.map(format_issue).join('; ')\n}\n\n/**\n * Render one issue as `path: message`, or just the message when the vendor\n * reported no path (a failure about the value as a whole).\n */\nfunction format_issue(issue: SchemaIssue): string {\n const path = issue.path\n if (path === undefined || path.length === 0) return issue.message\n return `${path.map((segment) => String(segment)).join('.')}: ${issue.message}`\n}\n","/**\n * durable: drive a flow that suspends across processes, one event at a time.\n *\n * `run.until_suspended` hands back a `resume` closure, and a closure dies\n * with its process. An app that resumes runs from events (a webhook, a\n * finished job, a deadline timer) needs the run to live in a store instead:\n * its input, the resume data its gates consumed, and where it stopped.\n * `durable({ store })` keeps exactly that under one scope per run id, and it\n * drives the flow again from the input whenever an event lands, so replay and\n * checkpoints behave the way they always do.\n *\n * Three things every event-driven app would otherwise write for itself, and\n * usually get wrong, are built in. A lease (a claim on the run's scope that\n * the driver renews while it drives) keeps two invocations from driving one\n * run at once, so a CI webhook and a deadline timer that land together can't\n * both run the same step, and the record's revision fences every write, so a\n * drive that stalled past its lease can't write over the drive that took the\n * run from it. An event that finds the lease taken waits in the run's inbox\n * under its gate's id, and whoever holds the lease takes it up once the run\n * reaches that gate, so the event is queued rather than dropped. And the run\n * records a fingerprint of the flow's shape, so a deploy that changes the\n * flow while a run waits fails loudly instead of replaying different steps\n * against old checkpoints.\n *\n * Everything the driver keeps (the input, resume data, gate payloads, and the\n * output) goes through the store, so it has to survive JSON, the same as any\n * checkpointed value.\n *\n * A run's scope holds its record under `record`, the events waiting on gates\n * in the `inbox` scope, the flow's checkpoints in the `flow` scope, and the\n * lease as the claim on `lease`. Deleting a run clears the whole scope.\n */\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { is_record } from '#schema'\nimport { describe } from './describe.js'\nimport { has_chosen_id } from './node_label.js'\nimport {\n aborted_error,\n flow_changed_error,\n resume_validation_error,\n run_not_found_error,\n} from './errors.js'\nimport { run, type RunOptions, type RunOutcome } from './runner.js'\nimport type { CheckpointStore, FlowNode, ScopedCheckpointStore, Step } from './types.js'\n\ntype Claims = Required<Pick<CheckpointStore, 'claim' | 'release'>>\n\n/**\n * A store `durable` can keep runs in: one that scopes, and whose scopes can\n * claim. `filesystem_store` from `fascicle/adapters` is one, and\n * `checkpoint_store_conformance` in `fascicle/testing` checks a store of\n * your own.\n */\nexport type DurableStore = {\n readonly scope: (prefix: string) => ScopedCheckpointStore & Claims\n}\n\nexport type DurableConfig = {\n readonly store: DurableStore\n /**\n * How long a drive owns its run before another invocation may take it\n * over, in milliseconds. The driver renews the lease every third of this\n * while it drives, so the lease only runs out once a drive stops answering\n * (its process died, or stalled for longer than this). Default 60 seconds.\n */\n readonly lease_ms?: number\n /**\n * What happens when a run's flow no longer has the shape the run started\n * on. `'fail'` (the default) throws `flow_changed_error`. `'replay'` takes\n * the new shape, records a `flow_changed` event, and drives on.\n */\n readonly on_flow_change?: 'fail' | 'replay'\n}\n\n/**\n * The `run` options a drive passes through. The driver owns the checkpoint\n * store and the resume data, so it leaves those two out.\n */\nexport type DurableRunOptions = Omit<RunOptions, 'checkpoint_store' | 'resume_data'>\n\nexport type DurableOutcome<o> =\n | { readonly kind: 'done'; readonly run_id: string; readonly output: o }\n | {\n readonly kind: 'suspended'\n readonly run_id: string\n readonly id: string\n readonly payload: unknown\n // When the gate's deadline passes, in epoch milliseconds, present when\n // the gate set one. Its clock started when the run stopped at the gate.\n readonly deadline_at?: number\n }\n // Another invocation holds the run. Resume data this call brought waits in\n // the run's inbox, where the holder takes it up, or, should the holder die\n // first, the next call on the run does.\n | { readonly kind: 'busy'; readonly run_id: string }\n\nexport type DurableRunState =\n | Exclude<DurableOutcome<unknown>, { readonly kind: 'busy' }>\n // A drive is under way, or one died partway and the next event drives the\n // run again.\n | { readonly kind: 'running'; readonly run_id: string }\n // The last drive threw, with this message. The next event drives the run\n // again.\n | { readonly kind: 'failed'; readonly run_id: string; readonly error: string }\n\nexport type DurableRuns = {\n readonly start: <i, o>(\n run_id: string,\n flow: Step<i, o>,\n input: i,\n options?: DurableRunOptions,\n ) => Promise<DurableOutcome<o>>\n readonly resume: <i, o>(\n run_id: string,\n flow: Step<i, o>,\n resume_data: Readonly<Record<string, unknown>>,\n options?: DurableRunOptions,\n ) => Promise<DurableOutcome<o>>\n readonly get: (run_id: string) => Promise<DurableRunState | undefined>\n readonly delete: (run_id: string) => Promise<boolean>\n}\n\ntype RunScope = ScopedCheckpointStore & Claims\n\ntype Suspension = {\n readonly id: string\n readonly payload: unknown\n readonly deadline_at: number | null\n}\n\ntype RunBase = {\n readonly format: 1\n // Counts the record's writes. A drive writes only over the revision it last\n // read or wrote, which is what fences off a drive that lost its lease.\n readonly revision: number\n readonly input: unknown\n readonly flow: string\n readonly resume_data: Readonly<Record<string, unknown>>\n readonly output: unknown\n readonly error: string\n}\n\n// `suspended` is the gate the run waits at while it's suspended, and the last\n// gate it waited at otherwise, which is what a refused resume puts back.\ntype RunRecord = RunBase &\n (\n | { readonly status: 'running' | 'done' | 'failed'; readonly suspended: Suspension | null }\n | { readonly status: 'suspended'; readonly suspended: Suspension }\n )\n\ntype Waiting = Extract<RunRecord, { readonly status: 'suspended' }>\n\ntype Lease = {\n readonly signal: AbortSignal\n readonly lost: () => boolean\n // Mark the lease lost and abort the drive, returning the abort's reason.\n readonly lose: () => aborted_error\n // Renew now and throw once another drive holds the lease.\n readonly confirm: () => Promise<void>\n readonly end: () => Promise<void>\n}\n\ntype Drive<i, o> = {\n readonly run_id: string\n readonly scope: RunScope\n readonly flow: Step<i, o>\n readonly shape: string\n readonly options: DurableRunOptions\n readonly lease_ms: number\n readonly on_flow_change: 'fail' | 'replay'\n}\n\ntype Driver = {\n readonly store: DurableStore\n readonly lease_ms: number\n readonly on_flow_change: 'fail' | 'replay'\n}\n\nconst RECORD = 'record'\nconst LEASE = 'lease'\nconst INBOX = 'inbox'\nconst FLOW = 'flow'\nconst DEFAULT_LEASE_MS = 60_000\nconst STATUSES: ReadonlySet<unknown> = new Set(['running', 'suspended', 'done', 'failed'])\n\n/**\n * A short digest of the flow's shape: each node's kind, the id its author\n * chose, and how the nodes nest. Generated ids stay out, since they shift with\n * build order, and so do names, descriptions, and config. Rewording a step or\n * editing a prompt leaves the digest alone, while adding, removing, moving,\n * or renaming a step changes it.\n */\nfunction fingerprint<i, o>(flow: Step<i, o>): string {\n const shape = JSON.stringify(shape_of(describe.json(flow)))\n return createHash('sha256').update(shape).digest('hex').slice(0, 16)\n}\n\n/**\n * One node of the shape that `fingerprint` digests.\n */\nfunction shape_of(node: FlowNode): unknown {\n return [node.kind, has_chosen_id(node) ? node.id : null, (node.children ?? []).map(shape_of)]\n}\n\n/**\n * Read a stored suspension back, or `null` when the value isn't one.\n */\nfunction as_suspension(value: unknown): Suspension | null {\n if (!is_record(value)) return null\n const { id, payload, deadline_at } = value\n if (typeof id !== 'string') return null\n return { id, payload, deadline_at: typeof deadline_at === 'number' ? deadline_at : null }\n}\n\n/**\n * Read a stored run record back, or `undefined` when the value isn't one this\n * driver wrote. `start` treats an unreadable record as no record and begins\n * the run again from its input, where its checkpoints still serve.\n */\nfunction as_record(value: unknown): RunRecord | undefined {\n if (!is_record(value) || value['format'] !== 1) return undefined\n const { revision, input, flow, resume_data, output, error, status } = value\n if (typeof revision !== 'number' || typeof flow !== 'string') return undefined\n if (!is_record(resume_data) || !STATUSES.has(status)) return undefined\n const base: RunBase = {\n format: 1,\n revision,\n input,\n flow,\n resume_data,\n output,\n error: typeof error === 'string' ? error : '',\n }\n const suspended = as_suspension(value['suspended'])\n if (status !== 'suspended') {\n // STATUSES holds only the four statuses, and this one isn't 'suspended'.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return { ...base, status: status as 'running' | 'done' | 'failed', suspended }\n }\n return suspended === null ? undefined : { ...base, status, suspended }\n}\n\n/**\n * The outcome a finished run reports to the call that drove it.\n */\nfunction done_view<i, o>(drive: Drive<i, o>, record: RunRecord): DurableOutcome<o> {\n // The driver stored this output from a run of the same flow.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return { kind: 'done', run_id: drive.run_id, output: record.output as o }\n}\n\n/**\n * The outcome a run waiting at `gate` reports.\n */\nfunction suspended_view(\n run_id: string,\n gate: Suspension,\n): Extract<DurableOutcome<never>, { readonly kind: 'suspended' }> {\n return {\n kind: 'suspended',\n run_id,\n id: gate.id,\n payload: gate.payload,\n ...(gate.deadline_at === null ? {} : { deadline_at: gate.deadline_at }),\n }\n}\n\n/**\n * What `get` reports for a stored run.\n */\nfunction state_of(run_id: string, record: RunRecord): DurableRunState {\n if (record.status === 'suspended') return suspended_view(run_id, record.suspended)\n if (record.status === 'done') return { kind: 'done', run_id, output: record.output }\n if (record.status === 'failed') return { kind: 'failed', run_id, error: record.error }\n return { kind: 'running', run_id }\n}\n\n/**\n * Take the run's lease for a fresh owner and renew it every third of\n * `lease_ms` until `end`.\n *\n * A renewal that finds another owner holding the lease marks it lost, stops\n * renewing, and aborts the drive through `signal`, so a drive that outlived\n * its lease stops instead of running a step twice. Loss is final: a lost\n * lease never renews again, even once the key is free. A renewal that throws\n * is retried on the next tick. `end` waits out the renewals still in flight\n * before it releases, so a late one can't take the lease back afterwards.\n */\nasync function take_lease(scope: RunScope, lease_ms: number): Promise<Lease | undefined> {\n const owner = randomUUID()\n if (!(await scope.claim(LEASE, owner, lease_ms))) return undefined\n const controller = new AbortController()\n let lost = false\n let renewals: Promise<void> = Promise.resolve()\n let timer: ReturnType<typeof setInterval> | undefined\n const lose = (): aborted_error => {\n lost = true\n // Stryker disable next-line CallExpression: a tick after a loss finds `renew` short-circuit on `lost` and only aborts an aborted controller again, and `end` clears the timer anyway.\n clearInterval(timer)\n const err = new aborted_error('another drive took over this run')\n controller.abort(err)\n return err\n }\n const renew = async (): Promise<boolean> => !lost && (await scope.claim(LEASE, owner, lease_ms))\n timer = setInterval(() => {\n renewals = renewals.then(renew).then(\n (held) => {\n if (!held) lose()\n },\n () => {},\n )\n }, lease_ms / 3)\n timer.unref()\n return {\n signal: controller.signal,\n lost: () => lost,\n lose,\n confirm: async () => {\n if (!(await renew())) throw lose()\n },\n end: async () => {\n clearInterval(timer)\n await renewals\n await scope.release(LEASE, owner)\n },\n }\n}\n\n/**\n * Write the run's record and resolve the record as written.\n *\n * The write goes through only while this drive holds the lease and the\n * stored record is still the revision that `next` was built from. A drive\n * that lost the lease, or that stalled while another drive moved the run on,\n * finds the revision moved, loses the lease, and leaves the record alone.\n */\nasync function save(scope: RunScope, lease: Lease, next: RunRecord): Promise<RunRecord> {\n await lease.confirm()\n const stored = as_record(await scope.get(RECORD))\n if (stored === undefined || stored.revision !== next.revision) throw lease.lose()\n const saved: RunRecord = { ...next, revision: next.revision + 1 }\n await scope.set(RECORD, saved)\n return saved\n}\n\n/**\n * Hold a run to the flow shape it started on. A run on the same shape passes\n * through. A changed shape throws `flow_changed_error`, unless the driver\n * replays, in which case the run records a `flow_changed` event and adopts\n * the new shape.\n */\nasync function check_shape<i, o>(\n drive: Drive<i, o>,\n lease: Lease,\n record: RunRecord,\n): Promise<RunRecord> {\n if (record.flow === drive.shape) return record\n if (drive.on_flow_change === 'fail') {\n throw new flow_changed_error(drive.run_id, record.flow, drive.shape)\n }\n drive.options.trajectory?.record({\n kind: 'flow_changed',\n run_id: drive.run_id,\n started_on: record.flow,\n continued_on: drive.shape,\n ts: Date.now(),\n })\n return save(drive.scope, lease, { ...record, flow: drive.shape })\n}\n\n/**\n * The resume data waiting in the run's inbox for `gate_id`, if any arrived.\n */\nasync function read_inbox(\n scope: RunScope,\n gate_id: string,\n): Promise<{ readonly data: unknown } | undefined> {\n const entry = await scope.scope(INBOX).get(gate_id)\n return is_record(entry) && 'data' in entry ? { data: entry['data'] } : undefined\n}\n\n/**\n * Leave `data` in the run's inbox for `gate_id`, unless a datum already waits\n * there, another resume is leaving one, the run has already passed the gate,\n * or the run is gone.\n *\n * The reads and the write happen under a claim on the gate's inbox key, so of\n * two resumes that race for one gate, only the first to claim it writes, and\n * the other drops its datum as it would on finding one there. The inbox is\n * read before the record because `take_up` saves a gate's datum into the\n * record before it deletes the inbox entry, so a datum that's taken up between\n * the two reads still shows in the record. The claim lasts `lease_ms` and\n * comes off right after the write.\n *\n * Two windows stay open, because the store contract has no compare-and-set to\n * close them with. A resume that stalls past its claim, after its reads and\n * before its write, can still write once another resume has moved the run\n * past the gate. And a `delete` that lands between the record read and the\n * write leaves the datum in the cleared scope, where a new run under the same\n * id takes it up.\n */\nasync function deliver<i, o>(drive: Drive<i, o>, gate_id: string, data: unknown): Promise<void> {\n const key = `${INBOX}/${gate_id}`\n const owner = randomUUID()\n if (!(await drive.scope.claim(key, owner, drive.lease_ms))) return\n try {\n if ((await read_inbox(drive.scope, gate_id)) !== undefined) return\n const record = as_record(await drive.scope.get(RECORD))\n if (record === undefined || Object.hasOwn(record.resume_data, gate_id)) return\n await drive.scope.scope(INBOX).set(gate_id, { data })\n } finally {\n await drive.scope.release(key, owner)\n }\n}\n\n/**\n * Move the resume data waiting at the run's gate into the run, or resolve\n * `undefined` when none has arrived.\n *\n * The record is saved before the inbox entry is deleted, so a crash between\n * the two leaves the data in one place or the other and never in neither.\n */\nasync function take_up<i, o>(\n drive: Drive<i, o>,\n lease: Lease,\n record: Waiting,\n): Promise<RunRecord | undefined> {\n const gate = record.suspended.id\n const entry = await read_inbox(drive.scope, gate)\n if (entry === undefined) return undefined\n const current = await check_shape(drive, lease, record)\n const saved = await save(drive.scope, lease, {\n ...current,\n status: 'running',\n resume_data: { ...current.resume_data, [gate]: entry.data },\n })\n await drive.scope.scope(INBOX).delete(gate)\n return saved\n}\n\n/**\n * The record after a drive came to rest: done with its output, or waiting at\n * a gate with that gate's deadline, if it has one, counted from now.\n */\nfunction after_outcome<o>(record: RunRecord, outcome: RunOutcome<o>): RunRecord {\n if (outcome.kind === 'done') {\n return { ...record, status: 'done', output: outcome.output, suspended: null }\n }\n const deadline_at = outcome.deadline_ms === undefined ? null : Date.now() + outcome.deadline_ms\n const gate: Suspension = { id: outcome.id, payload: outcome.payload, deadline_at }\n return { ...record, status: 'suspended', suspended: gate }\n}\n\n/**\n * The record after a drive threw. A resume the gate refused is dropped, and\n * the run goes back to waiting at that gate, so one bad event can't wedge the\n * run. Anything else marks the run failed until the next event drives it\n * again.\n */\nfunction after_failure(record: RunRecord, err: unknown): RunRecord {\n const gate = record.suspended\n if (err instanceof resume_validation_error && gate !== null && err.suspend_id === gate.id) {\n const resume_data = Object.fromEntries(\n Object.entries(record.resume_data).filter(([id]) => id !== gate.id),\n )\n return { ...record, status: 'suspended', suspended: gate, resume_data }\n }\n return { ...record, status: 'failed', error: err instanceof Error ? err.message : String(err) }\n}\n\n/**\n * Run the flow from its input with every resume datum taken up so far, then\n * save where it came to rest. The run's abort signal fires when the lease is\n * lost, as well as when the caller's own signal does.\n *\n * A drive that throws surfaces its own error even when the store then fails\n * to save the failure. The record stays as it was in that case, and the next\n * event drives the run again, the way it would after a crash.\n */\nasync function drive_once<i, o>(\n drive: Drive<i, o>,\n lease: Lease,\n stored: RunRecord,\n): Promise<RunRecord> {\n const record = await check_shape(drive, lease, stored)\n const caller_abort = drive.options.abort\n let outcome: RunOutcome<o>\n try {\n // The driver stored this input when the run started on the same flow.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n outcome = await run.until_suspended(drive.flow, record.input as i, {\n ...drive.options,\n abort: caller_abort === undefined ? lease.signal : AbortSignal.any([caller_abort, lease.signal]),\n checkpoint_store: drive.scope.scope(FLOW),\n resume_data: record.resume_data,\n })\n } catch (err) {\n // A lost lease fails the save's own check, so a drive that lost its run\n // writes nothing here.\n await save(drive.scope, lease, after_failure(record, err)).catch(() => {})\n throw err\n }\n return save(drive.scope, lease, after_outcome(record, outcome))\n}\n\n/**\n * Drive the run until it's done or waiting at a gate with nothing in its\n * inbox for that gate.\n */\nasync function settle<i, o>(\n drive: Drive<i, o>,\n lease: Lease,\n loaded: RunRecord,\n): Promise<DurableOutcome<o>> {\n let record = loaded\n for (;;) {\n if (record.status === 'done') return done_view(drive, record)\n if (record.status === 'suspended') {\n const resumed = await take_up(drive, lease, record)\n if (resumed === undefined) return suspended_view(drive.run_id, record.suspended)\n record = resumed\n }\n record = await drive_once(drive, lease, record)\n }\n}\n\n/**\n * Take the lease, bring the run to rest, and let the lease go.\n *\n * An event that landed for the run's gate while this call held the lease\n * found it taken and left its data in the inbox. So once the lease is gone,\n * the call looks again and drives once more when something waits at the gate.\n * Another call that took the lease in between gets it first, and this one\n * reports the run busy.\n */\nasync function bring_to_rest<i, o>(\n drive: Drive<i, o>,\n load: () => Promise<RunRecord>,\n): Promise<DurableOutcome<o>> {\n for (;;) {\n const lease = await take_lease(drive.scope, drive.lease_ms)\n if (lease === undefined) return { kind: 'busy', run_id: drive.run_id }\n let outcome: DurableOutcome<o>\n try {\n outcome = await settle(drive, lease, await load())\n } catch (err) {\n if (lease.lost()) return { kind: 'busy', run_id: drive.run_id }\n throw err\n } finally {\n await lease.end()\n }\n if (outcome.kind !== 'suspended') return outcome\n if ((await read_inbox(drive.scope, outcome.id)) === undefined) return outcome\n }\n}\n\n/**\n * The scope that holds `run_id`, which has to be a non-empty string.\n */\nfunction scope_for(driver: Driver, run_id: string): RunScope {\n if (run_id.length === 0) throw new TypeError('durable: a run id must be a non-empty string')\n return driver.store.scope(run_id)\n}\n\n/**\n * The record of a run that has to exist, or `run_not_found_error`.\n */\nasync function existing_record(run_id: string, scope: RunScope): Promise<RunRecord> {\n const record = as_record(await scope.get(RECORD))\n if (record === undefined) throw new run_not_found_error(run_id)\n return record\n}\n\n/**\n * Collect what one call drives with.\n */\nfunction drive_for<i, o>(\n driver: Driver,\n run_id: string,\n flow: Step<i, o>,\n options: DurableRunOptions,\n): Drive<i, o> {\n return {\n run_id,\n scope: scope_for(driver, run_id),\n flow,\n shape: fingerprint(flow),\n options,\n lease_ms: driver.lease_ms,\n on_flow_change: driver.on_flow_change,\n }\n}\n\n/**\n * Start a run, or pick it up where it is when it already exists. A repeated\n * start (a webhook delivered twice) neither restarts the run nor changes its\n * input, though it does drive a run that failed, or whose drive died, once\n * more. The new record is read back before the first drive, so that drive\n * sees the input the way every later one will, after a trip through the\n * store.\n */\nasync function start_run<i, o>(\n driver: Driver,\n run_id: string,\n flow: Step<i, o>,\n input: i,\n options: DurableRunOptions,\n): Promise<DurableOutcome<o>> {\n const drive = drive_for(driver, run_id, flow, options)\n return bring_to_rest(drive, async () => {\n const existing = as_record(await drive.scope.get(RECORD))\n if (existing !== undefined) return existing\n const record: RunRecord = {\n format: 1,\n revision: 0,\n input,\n flow: drive.shape,\n resume_data: {},\n output: null,\n // Stryker disable next-line StringLiteral: a run's error is read only once the run has failed, and failing writes it.\n error: '',\n status: 'running',\n suspended: null,\n }\n await drive.scope.set(RECORD, record)\n return existing_record(run_id, drive.scope)\n })\n}\n\n/**\n * Hand resume data to a run and drive it as far as it goes.\n *\n * Each datum is written to the run's inbox before the lease is taken, so a\n * call that finds the run busy still leaves its data where the holder takes\n * it up. Data for a gate the run has already passed is dropped, because\n * changing it would change the replay, and so is data for a run that's gone,\n * and data for a gate whose inbox already holds some: the first datum to\n * reach a gate is the one it gets. Each of those checks happens under a claim\n * on the gate's inbox key, so it holds when two calls race for one gate, and\n * when another call moves the run past the gate or deletes the run before\n * this one claims. The claim lasts the driver's `lease_ms` and comes off\n * right after the write, so a call that dies between the two holds that\n * gate's data back until the claim lapses, and data sent for the gate in that\n * window is dropped. Without a compare-and-set in the store contract, two\n * windows stay open: a call that stalls past its claim can still write data\n * for a gate the run has passed since, and a `delete` that lands between the\n * call's record read and its write leaves the data for a new run under the\n * same id. `undefined` resumes nothing. A call with no new data still drives\n * a run that failed, or whose drive died, once more.\n */\nasync function resume_run<i, o>(\n driver: Driver,\n run_id: string,\n flow: Step<i, o>,\n resume_data: Readonly<Record<string, unknown>>,\n options: DurableRunOptions,\n): Promise<DurableOutcome<o>> {\n const drive = drive_for(driver, run_id, flow, options)\n const record = await existing_record(run_id, drive.scope)\n if (record.status === 'done') return done_view(drive, record)\n const fresh = Object.entries(resume_data).filter(([, data]) => data !== undefined)\n await Promise.all(fresh.map(([id, data]) => deliver(drive, id, data)))\n return bring_to_rest(drive, () => existing_record(run_id, drive.scope))\n}\n\n/**\n * Delete everything a run keeps, unless a drive holds it right now.\n */\nasync function delete_run(driver: Driver, run_id: string): Promise<boolean> {\n const scope = scope_for(driver, run_id)\n if (!(await scope.claim(LEASE, randomUUID(), driver.lease_ms))) return false\n await scope.clear()\n return true\n}\n\n/**\n * Keep the runs of flows that suspend in `config.store`, and drive them one\n * event at a time.\n *\n * `start(run_id, flow, input)` begins a run and drives it until it's done or\n * waiting at a gate. `resume(run_id, flow, { [gate]: data })` hands a run\n * the data its gate waits for and drives it on. Both report `busy` instead\n * when another invocation is driving the run, and both are safe to repeat.\n * `get(run_id)` reads where a run stands without driving it, and\n * `delete(run_id)` removes it, resolving false while a drive holds it.\n */\nexport function durable(config: DurableConfig): DurableRuns {\n const lease_ms = config.lease_ms ?? DEFAULT_LEASE_MS\n if (!Number.isFinite(lease_ms) || lease_ms <= 0) {\n throw new RangeError(`durable: lease_ms must be a positive number of milliseconds, got ${lease_ms}`)\n }\n const driver: Driver = {\n store: config.store,\n lease_ms,\n on_flow_change: config.on_flow_change ?? 'fail',\n }\n return {\n start: (run_id, flow, input, options = {}) => start_run(driver, run_id, flow, input, options),\n resume: (run_id, flow, resume_data, options = {}) =>\n resume_run(driver, run_id, flow, resume_data, options),\n get: async (run_id) => {\n const record = as_record(await scope_for(driver, run_id).get(RECORD))\n return record === undefined ? undefined : state_of(run_id, record)\n },\n delete: (run_id) => delete_run(driver, run_id),\n }\n}\n","/**\n * Step id validation.\n *\n * Every id in the system is constrained to a valid JavaScript identifier\n * rather than an arbitrary string, because ids are read back as property\n * names: `chain` merges each binding into a typed record under its name, and\n * a name you cannot destructure is a name the record cannot offer. Holding\n * one rule across `step`, `chain`, and the agent surface means a user learns\n * it once instead of discovering per-primitive exceptions.\n *\n * Prose is not constrained, because prose has its own channel: `meta.name`\n * on a step, `name` on a chain binding or composer.\n *\n * Nothing normalizes an id on the caller's behalf. A silent transformation\n * would map several distinct names onto one key ('my-id', 'my.id', and\n * 'my_id' all reduce to 'my_id') and would have to stay bug-for-bug in sync\n * with the equivalent type-level transformation. The suggestion in the\n * failure message is a courtesy for the reader, never a contract.\n */\n\n// `$` sits outside ID_Continue, so both classes name it explicitly.\nconst IDENTIFIER = /^[\\p{ID_Start}$_][\\p{ID_Continue}$]*$/u\n\n/**\n * Report whether `id` can be read back as a property name.\n */\nexport function is_valid_step_id(id: string): boolean {\n return IDENTIFIER.test(id)\n}\n\n/**\n * Render the closest identifier-shaped spelling of `raw`, for failure\n * messages only. Prefixes an underscore when the swap alone still leaves an\n * illegal leading character, so the suggestion is always usable as written.\n */\nexport function suggest_step_id(raw: string): string {\n const swapped = raw.replace(/[^\\p{ID_Continue}$]/gu, '_')\n return IDENTIFIER.test(swapped) ? swapped : `_${swapped}`\n}\n\n/**\n * Throw when `id` is not identifier-shaped. `subject` names the failing\n * surface so the message points at the call the reader actually wrote, and\n * `remedy` says where the prose spelling belongs instead.\n */\nexport function assert_valid_step_id(id: string, subject: string, remedy: string): void {\n if (is_valid_step_id(id)) return\n throw new TypeError(\n `${subject} ${JSON.stringify(id)} is not a valid identifier: ids are read back as property names, so use ${suggest_step_id(id)} and ${remedy}`,\n )\n}\n","/**\n * step() factory.\n *\n * Three forms:\n * step(id, fn): named step. id is rendered in trajectory spans and describe().\n * step(id, fn, options): named step carrying descriptive metadata. `name` is the\n * display channel: it labels the step's trajectory span and\n * its describe() line, leaving the id free to stay a stable\n * identifier. Nothing keys off it, so it is safe to reword.\n * `arm` declares the steps the body invokes via `ctx.call`.\n * step(fn): anonymous step. id is `step_<counter>`; cannot be checkpointed.\n *\n * Anonymous steps carry an internal `anonymous: true` flag so checkpoint can\n * reject them synchronously at flow construction time.\n *\n * An explicit id must be identifier-shaped: ids are read back as property\n * names wherever a step's output is bound (see step_id.ts). Free prose goes\n * in `meta.name`.\n */\n\nimport { is_step } from './is_step.js'\nimport { register_traced_kind } from './runner.js'\nimport { assert_valid_step_id } from './step_id.js'\nimport type { AnyStep, Step, StepFn, StepOptions } from './types.js'\n\nlet step_counter = 0\n\n/**\n * Generate a unique id of the form `step_<n>` for anonymous steps.\n */\nfunction next_step_id(): string {\n step_counter += 1\n return `step_${step_counter}`\n}\n\n/**\n * Normalize a declared arm (one step or several) to the children list.\n */\nfunction arm_children(arm: AnyStep | ReadonlyArray<AnyStep>): ReadonlyArray<AnyStep> {\n return is_step(arm) ? [arm] : arm\n}\n\n/**\n * Wrap a plain function as a `Step`, named or anonymous.\n *\n * The named form takes an explicit id (identity) and optional `options`\n * (display, description, and declared arms); the anonymous form generates a\n * `step_<n>` id and marks the step so checkpoint rejects it at construction\n * time. Declared arms become the step's children, which is all `describe`\n * reads; the body alone decides whether and when they run. The rest of\n * `options` is stored as `meta`, and left off entirely when nothing remains,\n * so `describe` never echoes an empty object.\n */\nexport function step<i, o>(id: string, fn: StepFn<i, o>, options?: StepOptions): Step<i, o>\nexport function step<i, o>(fn: StepFn<i, o>): Step<i, o>\nexport function step<i, o>(\n id_or_fn: string | StepFn<i, o>,\n maybe_fn?: StepFn<i, o>,\n options?: StepOptions,\n): Step<i, o> {\n if (typeof id_or_fn === 'function') {\n return {\n id: next_step_id(),\n kind: 'step',\n run: id_or_fn,\n anonymous: true,\n }\n }\n if (typeof maybe_fn !== 'function') {\n throw new TypeError('step(id, fn): fn must be a function')\n }\n assert_valid_step_id(id_or_fn, 'step id', 'put the label in meta.name')\n const { arm, ...meta }: StepOptions = options ?? {}\n return {\n id: id_or_fn,\n kind: 'step',\n run: maybe_fn,\n ...(Object.keys(meta).length > 0 ? { meta } : {}),\n ...(arm === undefined ? {} : { children: arm_children(arm) }),\n }\n}\n\nregister_traced_kind('step')\n","/**\n * sequence: chain child outputs.\n *\n * `sequence([a, b, c])` runs a, b, c in declared order. The input to sequence\n * is passed to the first child; each subsequent child receives the previous\n * child's output. The composer returns the last child's output.\n *\n * For a literal tuple of children, every joint is checked at compile time:\n * each child after the first must accept its predecessor's output, and a\n * mismatch resolves the offending element to a branded SequenceJointMismatch\n * so the error names the joint and both types. A spread segment inside a\n * tuple (`sequence([first, ...mids, last])`) is checked as a homogeneous\n * self-composing segment rather than index-zipped, since its positions are\n * not statically known. Arrays built at runtime carry no positional types,\n * so they must be homogeneous `ReadonlyArray<Step<T, T>>` and produce a\n * `Step<T, T>`; heterogeneous runtime arrays are rejected rather than\n * silently degrading to `Step<unknown, unknown>`.\n */\n\nimport { description_meta } from './display_name.js'\nimport { is_step } from './is_step.js'\nimport { dispatch_step, register_traced_kind, throw_if_aborted } from './runner.js'\nimport type { AnyStep, RunContext, Step, StepInput, StepOutput } from './types.js'\n\ntype FirstInput<children> = children extends readonly [Step<infer i, unknown>, ...unknown[]]\n ? i\n : unknown\n\ntype LastOutput<children> = children extends readonly [...unknown[], Step<never, infer o>]\n ? o\n : children extends readonly [Step<never, infer o>]\n ? o\n : unknown\n\ntype OutputOf<s> = StepOutput<s>\n\n// `never` fallback so a non-step can never satisfy a joint by accident.\ntype InputOf<s> = StepInput<s>\n\n// Branded impossible type for joint failures. A mismatched element's expected\n// type resolves to this interface, so the first line of the compile error\n// names the joint position and both types instead of burying them under a\n// structural Step assignability chain (which drags in irrelevant\n// exactOptionalPropertyTypes advice).\ninterface SequenceJointMismatch<at extends string, upstream_output, this_step_accepts> {\n readonly sequence_joint_mismatch: at\n readonly upstream_output: upstream_output\n readonly this_step_accepts: this_step_accepts\n}\n\n// The joint check: an element must be a step whose input accepts the\n// upstream output. `upstream` is bracketed to suppress union distribution,\n// since after a spread segment the upstream is a union and every constituent\n// must be accepted, not just one.\n//\n// The `unknown extends element` guard is load-bearing. While `children` is\n// being inferred, the checker computes contextual types for the array literal\n// from this parameter type instantiated with degenerate stand-ins (the type\n// parameter's constraint and the infer variables' constraints), under which\n// every element resolves to `unknown`. The guard collapses those\n// instantiations to the inert contextual type `unknown`, so an inline\n// generic leaf (a bare `model_step({ ... })`) resolves its own type\n// parameters from its arguments and defaults instead of absorbing `unknown`\n// from a step-shaped context. No concrete element is typed as exactly\n// `unknown`, so real elements always reach the checking branches.\ntype CheckedJoint<element, upstream, at extends string> = unknown extends element\n ? unknown\n : element extends AnyStep\n ? [upstream] extends [InputOf<element>]\n ? element\n : SequenceJointMismatch<at, upstream, InputOf<element>>\n : AnyStep\n\n// First position has no predecessor: any step passes, a non-step fails\n// against AnyStep. Guarded like CheckedJoint, for the same reason.\ntype CheckedFirst<element> = unknown extends element\n ? unknown\n : element extends AnyStep\n ? element\n : AnyStep\n\n// Index-zips the tail against the full tuple: `rest` is `children` shifted\n// left by one, so `children[k]` is the predecessor of `rest[k]`. A mapped\n// tuple instead of recursion, so length is unbounded. Only sound for tuples\n// without a spread segment, where `k` is a real position; CheckedChildren\n// routes spread-bearing tuples to CheckedSpreadTail instead.\ntype CheckedTail<children extends readonly unknown[], rest extends readonly unknown[]> = {\n readonly [k in keyof rest]: CheckedJoint<\n rest[k],\n OutputOf<k extends keyof children ? children[k] : never>,\n `after children[${k & string}]`\n >\n}\n\n// True only for spread segments and plain runtime arrays: any tuple with a\n// fixed element fails the mutual assignability probe on length grounds.\ntype IsPlainArray<t extends readonly unknown[]> = t extends readonly []\n ? false\n : t[number][] extends [...t]\n ? true\n : false\n\n// A spread segment admits any length including zero, so each element must\n// accept both the upstream output (it may run first) and its own output (it\n// may follow a sibling). `e` is bracketed against distribution so a union\n// element type is checked as a whole, where InputOf infers the intersection\n// of inputs and OutputOf the union of outputs, which is exactly the sound\n// requirement.\ntype CheckedSegment<seg extends readonly unknown[], e, upstream> = unknown extends e\n ? seg\n : [e] extends [AnyStep]\n ? [upstream | OutputOf<e>] extends [InputOf<e>]\n ? seg\n : readonly SequenceJointMismatch<'spread segment', upstream | OutputOf<e>, InputOf<e>>[]\n : readonly AnyStep[]\n\n// Peels fixed trailing elements off a spread-first remainder until only the\n// spread segment is left. The head-infer pattern fails on a leading spread,\n// so recursion arrives here exactly when the segment is at the front.\ntype SplitSpreadTrail<\n t extends readonly unknown[],\n trail extends readonly unknown[] = [],\n> = IsPlainArray<t> extends true\n ? [t, trail]\n : t extends readonly [...infer init, infer last_el]\n ? SplitSpreadTrail<init, [last_el, ...trail]>\n : [t, trail]\n\n// Position tracker for joint labels: a counting tuple while positions are\n// statically known, the 'spread' marker once a spread segment has consumed\n// the absolute indices.\ntype SpreadPos = readonly unknown[] | 'spread'\n\ntype JointAt<p extends SpreadPos> = p extends readonly unknown[]\n ? `after children[${p['length']}]`\n : 'after spread segment'\n\ntype NextPos<p extends SpreadPos> = p extends readonly unknown[] ? readonly [...p, unknown] : p\n\n// Walks a tuple that contains a spread segment. Fixed heads are joint-checked\n// with exact labels; the segment itself goes through CheckedSegment; fixed\n// elements after the segment are checked against the upstream widened by the\n// segment's output, because the segment may be empty at run time and both\n// paths must be sound. Recursion is fine here: spread-bearing tuples have few\n// fixed elements, while the unbounded fixed-tuple case keeps the mapped zip.\ntype CheckedSpreadTail<\n upstream,\n t extends readonly unknown[],\n p extends SpreadPos,\n> = t extends readonly []\n ? readonly []\n : IsPlainArray<t> extends true\n ? readonly [...CheckedSegment<t, t[number], upstream>]\n : t extends readonly [infer h, ...infer r]\n ? readonly [\n CheckedJoint<h, upstream, JointAt<p>>,\n ...CheckedSpreadTail<OutputOf<h>, r, NextPos<p>>,\n ]\n : SplitSpreadTrail<t> extends [\n infer seg extends readonly unknown[],\n infer trail extends readonly unknown[],\n ]\n ? readonly [\n ...CheckedSegment<seg, seg[number], upstream>,\n ...CheckedSpreadTail<upstream | OutputOf<seg[number]>, trail, 'spread'>,\n ]\n : never\n\n// Rejection brands: both are impossible to satisfy, so the checked overload\n// fails and the call either falls through to the homogeneous array overload\n// or errors with the brand's name and advice on the first line.\ninterface SequenceRuntimeChildrenMustBeHomogeneous<element> {\n readonly runtime_built_children: 'no tuple positions to check; use ReadonlyArray<Step<T, T>>'\n readonly element: element\n}\n\ninterface SequenceLeadingSpreadNeedsFixedFirst {\n readonly leading_spread: 'joint checking needs a fixed first element; a homogeneous ReadonlyArray<Step<T, T>> works via the array overload'\n}\n\n// `unknown[] extends children` is true only for the degenerate constraint\n// instantiation (and a genuine unknown[] argument), which must stay\n// contextually inert. Plain runtime arrays are rejected here so the call\n// falls through to the homogeneous overload instead of degrading to\n// `Step<unknown, unknown>`. `number extends length` detects a spread segment\n// somewhere in the tuple; the trailing `children` fallback only fires for\n// the empty tuple.\ntype CheckedChildren<children extends readonly unknown[]> = unknown[] extends children\n ? children\n : IsPlainArray<children> extends true\n ? SequenceRuntimeChildrenMustBeHomogeneous<children[number]>\n : number extends children['length']\n ? children extends readonly [infer first, ...infer rest]\n ? readonly [CheckedFirst<first>, ...CheckedSpreadTail<OutputOf<first>, rest, readonly []>]\n : SequenceLeadingSpreadNeedsFixedFirst\n : children extends readonly [infer first, ...infer rest]\n ? readonly [CheckedFirst<first>, ...CheckedTail<children, rest>]\n : children\n\nlet sequence_counter = 0\n\n/**\n * Generate a unique step id of the form `sequence_<n>`.\n */\nfunction next_id(): string {\n sequence_counter += 1\n return `sequence_${sequence_counter}`\n}\n\nexport type SequenceOptions = {\n readonly name?: string\n readonly description?: string\n}\n\n/**\n * Build a step that chains children, each feeding the next.\n *\n * The children parameter is checked joint by joint for literal tuples via\n * `CheckedChildren`; the intersection with the bare `children` parameter is\n * what lets inference read the precise tuple while the checked shape\n * constrains it. Runtime-built arrays carry no positional types, so the\n * second overload requires them to be homogeneous and self-composing, which\n * keeps `run` sound instead of degrading to the unknown boundary. Validates\n * every element up front so a non-Step (usually a bare function) fails at\n * construction with a pointed message rather than at run time. Checks\n * `ctx.abort` before each child so aborts land on step boundaries.\n *\n * The checked signature comes again after the array one. A call that matches\n * no overload is reported against the last one, so repeating the checked\n * signature there puts its `SequenceJointMismatch`, which names the joint, in\n * the error, where the array overload would only say that every step must be\n * a `Step<T, T>`. A call that does match still resolves in the order above.\n */\nexport function sequence<const children extends readonly unknown[]>(\n children: children & CheckedChildren<children>,\n options?: SequenceOptions,\n): Step<FirstInput<children>, LastOutput<children>>\nexport function sequence<t>(\n children: ReadonlyArray<Step<t, t>>,\n options?: SequenceOptions,\n): Step<t, t>\nexport function sequence<const children extends readonly unknown[]>(\n children: children & CheckedChildren<children>,\n options?: SequenceOptions,\n): Step<FirstInput<children>, LastOutput<children>>\nexport function sequence(children: readonly unknown[], options?: SequenceOptions): AnyStep {\n if (!Array.isArray(children)) {\n throw new TypeError(\n `sequence(children): children must be an array of Steps, got ${typeof children} — sequence takes a single array, e.g., sequence([a, b, c])`,\n )\n }\n children.forEach((child: unknown, index: number) => {\n if (is_step(child)) return\n const hint =\n typeof child === 'function'\n ? ' — wrap plain functions with step(fn), or use pipe(inner, fn) to transform output'\n : ''\n throw new TypeError(\n `sequence(children): children[${index}] is not a Step, got ${typeof child}${hint}`,\n )\n })\n\n const id = next_id()\n // Validation above guarantees every element is a Step; the compile-time\n // story lives in CheckedChildren, so the erased view is a plain step array.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const children_ref = children as readonly AnyStep[]\n const run_fn = async (input: unknown, ctx: RunContext): Promise<unknown> => {\n let acc: unknown = input\n for (const child of children_ref) {\n throw_if_aborted(ctx)\n // The erased list drops the joint types; the checked signature pairs\n // each child with its predecessor's output, so the dispatch re-asserts.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n acc = await dispatch_step(child, acc as never, ctx)\n }\n return acc\n }\n\n const config_meta: Record<string, unknown> | undefined =\n options?.name === undefined ? undefined : { display_name: options.name }\n\n return {\n id,\n kind: 'sequence',\n children: children_ref,\n ...(config_meta ? { config: config_meta } : {}),\n ...description_meta(options?.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('sequence')\n","/**\n * parallel: concurrent execution of named children.\n *\n * `parallel({ a, b })` runs a and b concurrently with the same input. Output\n * is an object keyed by the child name; all children must accept the same\n * input type.\n *\n * Cancellation: each child runs with a composed abort signal,\n * `AbortSignal.any([ctx.abort, child_local])`. On abort the composer awaits\n * all in-flight children (success, failure, or aborted) before rethrowing\n * `ctx.abort.reason`.\n *\n * When several children fail, a `suspended_error` is preferred over an\n * application error so a human-approval gate inside a branch stays resumable\n * rather than being masked by a sibling's failure. Otherwise the first error\n * in declared order propagates.\n */\n\nimport { description_meta } from './display_name.js'\nimport { suspended_error } from './errors.js'\nimport { dispatch_step, install_abort_fan_out, register_traced_kind, throw_if_aborted } from './runner.js'\nimport type { AnyStep, RunContext, Step, StepInput, StepOutput } from './types.js'\n\n// Intersects the members' inputs: the parallel step's input must satisfy every\n// child, since each receives it verbatim. Each member's input sits in a\n// parameter position before the intersection is inferred, so a member that\n// accepts a union keeps it whole, where pooling every input into one union\n// first would intersect that member's alternatives with each other.\ntype ParallelInput<children extends Record<string, AnyStep>> = {\n [k in keyof children]: (input: Accepted<StepInput<children[k]>>) => void\n}[keyof children] extends (input: infer i) => void\n ? i\n : never\n\n// A member whose input reads as `never` constrains nothing. That's what a\n// zero-parameter function infers once a generic wrapper (`stash`, a `branch`\n// arm) loses its input type, and the pooled union that came before dropped it.\ntype Accepted<i> = [i] extends [never] ? unknown : i\n\ntype ParallelOutputs<children extends Record<string, AnyStep>> = {\n [k in keyof children]: StepOutput<children[k]>\n}\n\nlet parallel_counter = 0\n\n/**\n * Generate a unique step id of the form `parallel_<n>`.\n */\nfunction next_id(): string {\n parallel_counter += 1\n return `parallel_${parallel_counter}`\n}\n\ntype Settled =\n | { readonly status: 'ok'; readonly key: string; readonly value: unknown }\n | { readonly status: 'err'; readonly key: string; readonly err: unknown }\n\n/**\n * Run one child under its own composed abort signal and settle it: an\n * `'ok'`/`'err'` record rather than a thrown error, so a sibling's failure\n * never short-circuits `Promise.all` before every child has finished.\n */\nasync function run_child(\n entry: readonly [string, AnyStep],\n local: AbortController | undefined,\n input: unknown,\n ctx: RunContext,\n): Promise<Settled> {\n const [key, child] = entry\n if (!local) throw new Error('parallel: missing controller')\n const composed = AbortSignal.any([ctx.abort, local.signal])\n const child_ctx: RunContext = { ...ctx, abort: composed }\n try {\n // The entry list erases child types; the public signature guarantees the\n // input satisfies every child, so the erased dispatch re-asserts it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const value = await dispatch_step(child, input as never, child_ctx)\n return { status: 'ok', key, value }\n } catch (err) {\n return { status: 'err', key, err }\n }\n}\n\ntype ErrorChoice = { readonly thrown: boolean; readonly err: unknown }\n\n/**\n * Choose which settled error (if any) `run_fn` should rethrow: a\n * `suspended_error` wins over any application error so a human-approval gate\n * inside a branch stays resumable rather than masked by a sibling's failure;\n * otherwise the first error in declared order propagates.\n */\nfunction pick_error(settled: ReadonlyArray<Settled>): ErrorChoice {\n let first_err: unknown\n let has_err = false\n let suspended: unknown\n let has_suspended = false\n for (const s of settled) {\n if (s.status !== 'err') continue\n if (!has_err) {\n first_err = s.err\n has_err = true\n }\n if (!has_suspended && s.err instanceof suspended_error) {\n suspended = s.err\n has_suspended = true\n }\n }\n if (has_suspended) return { thrown: true, err: suspended }\n if (has_err) return { thrown: true, err: first_err }\n return { thrown: false, err: undefined }\n}\n\nexport type ParallelOptions = {\n readonly name?: string\n readonly description?: string\n}\n\n/**\n * Build a step that runs named children concurrently on the same input.\n *\n * The step's input type is the intersection of the children's inputs, since\n * every child receives the input verbatim. Returns an object keyed by child\n * name. All children settle before any error propagates; a `suspended_error`\n * wins over application errors so a human-approval gate stays resumable\n * instead of being masked by a sibling's failure.\n */\nexport function parallel<children extends Record<string, AnyStep>>(\n members: children,\n options?: ParallelOptions,\n): Step<ParallelInput<children>, ParallelOutputs<children>> {\n const id = next_id()\n const entries: ReadonlyArray<readonly [string, AnyStep]> = Object.entries(members)\n const child_list: ReadonlyArray<AnyStep> = entries.map(([, s]) => s)\n const keys: ReadonlyArray<string> = entries.map(([k]) => k)\n\n const run_fn = async (\n input: ParallelInput<children>,\n ctx: RunContext,\n ): Promise<ParallelOutputs<children>> => {\n const controllers = entries.map(() => new AbortController())\n const on_parent_abort = install_abort_fan_out(ctx, controllers)\n\n try {\n const settled = await Promise.all(\n entries.map((entry, idx) => run_child(entry, controllers[idx], input, ctx)),\n )\n\n throw_if_aborted(ctx)\n\n const choice = pick_error(settled)\n if (choice.thrown) throw choice.err\n\n const out: Record<string, unknown> = {}\n for (const s of settled) {\n if (s.status === 'ok') out[s.key] = s.value\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return out as ParallelOutputs<children>\n } finally {\n ctx.abort.removeEventListener('abort', on_parent_abort)\n }\n }\n\n const config_meta: Record<string, unknown> = { keys }\n if (options?.name !== undefined) config_meta['display_name'] = options.name\n\n return {\n id,\n kind: 'parallel',\n children: child_list,\n config: config_meta,\n ...description_meta(options?.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('parallel')\n","/**\n * branch: conditional routing.\n *\n * `branch({ when, then, otherwise })` evaluates `when(input)`; if truthy, runs\n * `then`, else runs `otherwise`. The branch returns whichever arm ran, so its\n * output type is the union of the two arms' outputs, and naming one output\n * type, as in `branch<Pair, number | null>`, holds both arms to it.\n */\n\nimport { description_meta } from './display_name.js'\nimport { dispatch_step, register_traced_kind } from './runner.js'\nimport type { RunContext, Step } from './types.js'\n\n// The otherwise arm's output defaults to the then arm's, so a config named\n// with one output type holds both arms to it.\nexport type BranchConfig<i, o, otherwise_o = o> = {\n readonly name?: string\n readonly description?: string\n readonly when: (input: i) => boolean | Promise<boolean>\n readonly then: Step<i, o>\n readonly otherwise: Step<i, otherwise_o>\n}\n\nlet branch_counter = 0\n\n/**\n * Generate a unique step id of the form `branch_<n>`.\n */\nfunction next_id(): string {\n branch_counter += 1\n return `branch_${branch_counter}`\n}\n\n/**\n * Build a conditional-routing step.\n *\n * Evaluates `when(input)` at run time and dispatches to `then` or `otherwise`.\n * Both branches appear as children so `describe()` renders the full tree even\n * though only one branch runs.\n */\nexport function branch<i, o, otherwise_o = o>(\n config: BranchConfig<i, o, otherwise_o>,\n): Step<i, o | otherwise_o> {\n const id = next_id()\n const { when, then: then_step, otherwise: otherwise_step, name } = config\n\n const run_fn = async (input: i, ctx: RunContext): Promise<o | otherwise_o> => {\n const cond = await when(input)\n return cond ? dispatch_step(then_step, input, ctx) : dispatch_step(otherwise_step, input, ctx)\n }\n\n const config_meta: Record<string, unknown> = { when, then: then_step, otherwise: otherwise_step }\n if (name !== undefined) config_meta['display_name'] = name\n\n return {\n id,\n kind: 'branch',\n children: [then_step, otherwise_step],\n config: config_meta,\n ...description_meta(config.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('branch')\n","/**\n * map: per-item execution.\n *\n * `map({ items, do, concurrency? })` extracts an array via `items(input)`,\n * runs `do` once per element, returns an array in the same order as inputs.\n * `concurrency` caps simultaneous in-flight items (rounded down, and never\n * below 1); omitted means full parallelism, and NaN throws at construction.\n *\n * The first item that throws stops new items from starting, and its error\n * propagates once the in-flight items settle, so every result the other items\n * computed is lost. `settle: true` keeps them, the way a batch needs: every\n * item runs, and its slot in the output holds `{ ok: true, value }` or\n * `{ ok: false, error }`. The error is reduced to the fields that survive JSON\n * (`message`, `name`, `kind`, `path`), so a settled array can be checkpointed\n * and reads the same when a resumed run takes it from the store. Each failed\n * item also records a `map_item_failed` event. `suspended_error` and\n * `aborted_error` are control flow rather than failures, so they propagate in\n * both modes, and so does an error that `items` itself throws.\n *\n * Cancellation: each in-flight item runs with a composed abort signal via\n * `AbortSignal.any([ctx.abort, child_local])`.\n * On abort no new items start. The composer awaits all in-flight items before\n * rethrowing `ctx.abort.reason`.\n */\n\nimport { description_meta } from './display_name.js'\nimport { error_path, is_control_flow_error } from './errors.js'\nimport { dispatch_step, install_abort_fan_out, register_traced_kind, throw_if_aborted } from './runner.js'\nimport type { RunContext, Step } from './types.js'\n\nexport type MapConfig<input, item, result> = {\n readonly name?: string\n readonly description?: string\n readonly items: (input: input) => ReadonlyArray<item> | Promise<ReadonlyArray<item>>\n readonly do: Step<item, result>\n readonly concurrency?: number\n /**\n * Unset or `false`: the first item that throws fails the map. A map that\n * keeps every item's outcome takes a `MapSettleConfig` instead.\n */\n readonly settle?: false\n}\n\n/**\n * The config of a map that settles: every item runs, and the output holds one\n * `Settled` entry per item, in input order.\n */\nexport type MapSettleConfig<input, item, result> = Omit<MapConfig<input, item, result>, 'settle'> & {\n readonly settle: true\n}\n\n/**\n * What a settled item keeps of the error it threw: the `message`, plus the\n * `name`, `kind`, and step-id `path` when the error has them. All of it is\n * plain data, so it survives a checkpoint, and `kind` (`timeout_error`, for\n * example) is how to tell one failure from another once the class is gone.\n */\nexport type SettledError = {\n readonly message: string\n readonly name?: string\n readonly kind?: string\n readonly path?: ReadonlyArray<string>\n}\n\n/**\n * One item's outcome in the output of a map that settles.\n */\nexport type Settled<o> =\n | { readonly ok: true; readonly value: o }\n | { readonly ok: false; readonly error: SettledError }\n\nlet map_counter = 0\n\n/**\n * Generate a unique step id of the form `map_<n>`.\n */\nfunction next_id(): string {\n map_counter += 1\n return `map_${map_counter}`\n}\n\n/**\n * Reduce a thrown value to the fields of it that survive JSON. A value that\n * isn't an `Error` keeps only its string form, as the message.\n */\nfunction settled_error(err: unknown): SettledError {\n if (!(err instanceof Error)) return { message: String(err) }\n const kind: unknown = Reflect.get(err, 'kind')\n const path = error_path(err)\n return {\n message: err.message,\n ...(err.name.length > 0 ? { name: err.name } : {}),\n ...(typeof kind === 'string' ? { kind } : {}),\n ...(path === undefined ? {} : { path }),\n }\n}\n\n/**\n * Turn an item's error into its slot in a settled map's output, and record\n * the failure as a `map_item_failed` event, with the error's `kind` as\n * `error_kind` when it has one.\n */\nfunction settle_failure(err: unknown, index: number, step_id: string, ctx: RunContext): Settled<never> {\n const error = settled_error(err)\n ctx.trajectory.record({\n kind: 'map_item_failed',\n step_id,\n index,\n error: error.message,\n ...(error.kind === undefined ? {} : { error_kind: error.kind }),\n })\n return { ok: false, error }\n}\n\n/**\n * Build a map step that fills each item's slot with `fulfilled(value)`.\n * Given `rejected`, an item's application error fills its slot as well, and\n * without it the first error fails the map.\n */\nfunction build_map<input, item, result, slot>(\n config: MapConfig<input, item, result> | MapSettleConfig<input, item, result>,\n fulfilled: (value: result) => slot,\n rejected?: (err: unknown, index: number, step_id: string, ctx: RunContext) => slot,\n): Step<input, slot[]> {\n const { items, do: per_item, concurrency, name } = config\n // A NaN concurrency would start zero workers and return an array of holes,\n // so the misconfiguration fails at construction, not mid-run.\n if (Number.isNaN(concurrency)) {\n throw new TypeError(`map: concurrency must be a number, got ${concurrency}`)\n }\n const id = next_id()\n const concurrency_cap = concurrency === undefined ? undefined : Math.max(1, Math.floor(concurrency))\n\n const run_fn = async (input: input, ctx: RunContext): Promise<slot[]> => {\n const list = await items(input)\n if (list.length === 0) return []\n const results: slot[] = Array.from({ length: list.length })\n\n const limit = concurrency_cap ?? list.length\n const controllers: AbortController[] = []\n const on_parent_abort = install_abort_fan_out(ctx, controllers)\n\n let cursor = 0\n // A flag rather than an `undefined` sentinel, so an item that throws\n // `undefined` still stops the map.\n let has_worker_error = false\n let worker_error: unknown = undefined\n\n // Run one item into its slot. An error that stops the map is kept, the\n // first one only, for the throw that follows once in-flight items settle.\n const run_one = async (idx: number): Promise<void> => {\n const local = new AbortController()\n controllers.push(local)\n const composed = AbortSignal.any([ctx.abort, local.signal])\n const child_ctx: RunContext = { ...ctx, abort: composed }\n const item_value = list[idx]\n try {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const value = await dispatch_step(per_item, item_value as item, child_ctx)\n results[idx] = fulfilled(value)\n } catch (err) {\n // Control flow stops the map in either mode, and so does anything\n // thrown once the map is being aborted, since the map is going to\n // throw the abort and the item failed because of it.\n if (rejected !== undefined && !is_control_flow_error(err) && !ctx.abort.aborted) {\n results[idx] = rejected(err, idx, id, ctx)\n } else if (!has_worker_error) {\n has_worker_error = true\n worker_error = err\n }\n }\n }\n\n const worker = async (): Promise<void> => {\n while (true) {\n if (ctx.abort.aborted || has_worker_error) return\n const idx = cursor\n cursor += 1\n if (idx >= list.length) return\n await run_one(idx)\n }\n }\n\n try {\n const worker_count = Math.min(limit, list.length)\n const workers: Promise<void>[] = []\n for (let w = 0; w < worker_count; w += 1) {\n workers.push(worker())\n }\n await Promise.all(workers)\n\n throw_if_aborted(ctx)\n if (has_worker_error) throw worker_error\n\n return results\n } finally {\n ctx.abort.removeEventListener('abort', on_parent_abort)\n }\n }\n\n const config_meta: Record<string, unknown> = { items }\n if (concurrency !== undefined) config_meta['concurrency'] = concurrency\n if (rejected !== undefined) config_meta['settle'] = true\n if (name !== undefined) config_meta['display_name'] = name\n\n return {\n id,\n kind: 'map',\n children: [per_item],\n config: config_meta,\n ...description_meta(config.description),\n run: run_fn,\n }\n}\n\n/**\n * Build a per-item execution step.\n *\n * Extracts an array via `items(input)`, runs `do` once per element through a\n * bounded worker pool, and returns results in input order. The first item\n * failure stops new work and propagates after in-flight items settle. With\n * `settle: true` every item runs, and the output holds each one's `Settled`\n * outcome instead.\n */\nexport function map<input, item, result>(\n config: MapSettleConfig<input, item, result>,\n): Step<input, Settled<result>[]>\nexport function map<input, item, result>(config: MapConfig<input, item, result>): Step<input, result[]>\nexport function map<input, item, result>(\n config: MapConfig<input, item, result> | MapSettleConfig<input, item, result>,\n): Step<input, result[]> | Step<input, Settled<result>[]> {\n if (config.settle === true) {\n return build_map(config, (value): Settled<result> => ({ ok: true, value }), settle_failure)\n }\n return build_map(config, (value: result) => value)\n}\n\nregister_traced_kind('map')\n","/**\n * pipe: transform output.\n *\n * `pipe(inner, fn)` runs `inner`, passes its output to `fn`, returns `fn`'s\n * result. Use for shape adaptation when composing heterogeneous steps.\n */\n\nimport { description_meta } from './display_name.js'\nimport { is_step } from './is_step.js'\nimport { dispatch_step, register_traced_kind } from './runner.js'\nimport type { RunContext, Step } from './types.js'\n\nlet pipe_counter = 0\n\n/**\n * Generate a unique step id of the form `pipe_<n>`.\n */\nfunction next_id(): string {\n pipe_counter += 1\n return `pipe_${pipe_counter}`\n}\n\nexport type PipeOptions = {\n readonly name?: string\n readonly description?: string\n}\n\n/**\n * Build an output-transforming step around `inner`.\n *\n * The argument checks reject Steps passed where functions belong: `pipe` is\n * not variadic, and the early `TypeError`s point misuse at `step(fn)` or\n * `sequence([...])` instead of failing obscurely at run time.\n */\nexport function pipe<i, a, b>(\n inner: Step<i, a>,\n fn: (value: a) => b | Promise<b>,\n options?: PipeOptions,\n): Step<i, b> {\n if (!is_step(inner)) {\n const hint = typeof inner === 'function' ? ' — wrap plain functions with step(fn)' : ''\n throw new TypeError(`pipe(inner, fn): inner must be a Step, got ${typeof inner}${hint}`)\n }\n if (typeof fn !== 'function') {\n if (is_step(fn)) {\n throw new TypeError(\n 'pipe(inner, fn): fn must be a function, got a Step — pipe is not variadic; to chain Steps use sequence([...])',\n )\n }\n throw new TypeError(`pipe(inner, fn): fn must be a function, got ${typeof fn}`)\n }\n if (is_step(options)) {\n throw new TypeError(\n 'pipe(inner, fn, options): got a Step as the third argument — pipe is not variadic; to chain Steps use sequence([...])',\n )\n }\n\n const id = next_id()\n\n const run_fn = async (input: i, ctx: RunContext): Promise<b> => {\n const intermediate = await dispatch_step(inner, input, ctx)\n return fn(intermediate)\n }\n\n const config_meta: Record<string, unknown> = { fn }\n if (options?.name !== undefined) config_meta['display_name'] = options.name\n\n return {\n id,\n kind: 'pipe',\n children: [inner],\n config: config_meta,\n ...description_meta(options?.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('pipe')\n","/**\n * The backoff algebra shared by the composition layer and the engine.\n *\n * Both retry layers schedule delays between attempts, and this module is the\n * single algebra they express those delays through. Holding the exponential\n * arithmetic and the timer/abort-listener dance in one place is what keeps the\n * two from disagreeing about whether a delay jitters or caps.\n *\n * The zone sits at the bottom of the dependency DAG and imports nothing, which\n * is why `wait_with_abort` is handed the abort-error factory rather than\n * constructing one: the error taxonomy lives in core, and reaching for it from\n * here would close a cycle back through the callers.\n */\n\nexport type BackoffPolicy = {\n readonly initial_delay_ms: number\n readonly max_delay_ms: number\n readonly jitter: boolean\n}\n\n/**\n * Map an abort reason onto the error a wait rejects with.\n *\n * Each layer surfaces an abort as its own error, so the caller supplies the\n * mapping instead of this zone owning an error taxonomy it cannot import.\n *\n * The two callers pass genuinely different factories, and that is settled, not\n * pending: core propagates an `Error` reason verbatim so an upstream cause\n * survives, while the engine always wraps so its boundary can only ever throw\n * `aborted_error`. See the factories in `core/retry.ts` and `engine/retry.ts`\n * for what each one protects.\n * Collapsing them to one rule breaks one layer or the other.\n */\nexport type AbortErrorFactory = (reason: unknown) => Error\n\n/**\n * Compute the delay before retry attempt `attempt`, counted from zero.\n *\n * Exponential (`initial_delay_ms * 2^attempt`) plus up to one\n * `initial_delay_ms` of random jitter when `policy.jitter` is set, clamped to\n * `max_delay_ms`. The jitter spreads retries from concurrent callers apart so\n * they don't stampede in lockstep; a `max_delay_ms` of `Infinity` is uncapped.\n */\nexport function compute_backoff(policy: BackoffPolicy, attempt: number): number {\n const base = policy.initial_delay_ms * 2 ** attempt\n const jitter = policy.jitter ? Math.random() * policy.initial_delay_ms : 0\n return Math.min(base + jitter, policy.max_delay_ms)\n}\n\n/**\n * Sleep `ms`, rejecting the moment `signal` fires instead of serving out the\n * delay, so a pending abort never waits out a backoff.\n *\n * A non-positive `ms` resolves without arming a timer or consulting `signal`.\n * The rejection value is `to_error` applied to `signal.reason`.\n */\nexport function wait_with_abort(\n ms: number,\n signal: AbortSignal,\n to_error: AbortErrorFactory,\n): Promise<void> {\n if (ms <= 0) return Promise.resolve()\n return new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(to_error(signal.reason))\n return\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', on_abort)\n resolve()\n }, ms)\n const on_abort = (): void => {\n clearTimeout(timer)\n reject(to_error(signal.reason))\n }\n signal.addEventListener('abort', on_abort, { once: true })\n })\n}\n","/**\n * retry: re-run on failure.\n *\n * `retry(inner, { max_attempts, backoff_ms?, max_delay_ms?, jitter?, when?, on_error?, project? })`\n * runs `inner`. If it throws an application error, retries up to\n * `max_attempts - 1` more times with exponential backoff\n * (`backoff_ms * 2^(attempt-1)`), jittered by up to one `backoff_ms` and\n * clamped to `max_delay_ms` (default 30s) through the shared `#policy`\n * algebra. `jitter` defaults on: un-jittered concurrent retries stampede in\n * lockstep. `when` decides which application errors are retryable: one it\n * rejects propagates at once, untouched, without consuming an attempt or\n * firing `on_error`. `on_error` is called on every retryable failure. The\n * last error is rethrown if all attempts fail.\n *\n * `project` maps the `{ value, attempts, errors }` envelope into the step's\n * output, so a caller can record how the value was reached without a\n * mutable closure or a trajectory read. Omitted, the value is the output.\n *\n * Control-flow signals (`suspended_error`, `aborted_error`) are not failures:\n * they propagate immediately without consuming an attempt, firing `on_error`,\n * or scheduling a backoff. A suspend's `on()` side effect therefore runs once\n * per run, not once per attempt.\n *\n * Cancellation / cleanup: cleanup handlers registered by the inner step\n * accumulate across attempts. The parent `ctx.abort` is honored between\n * attempts; a pending abort short-circuits the backoff and propagates.\n */\n\nimport { description_meta } from './display_name.js'\nimport { aborted_error, is_control_flow_error } from './errors.js'\nimport { dispatch_step, register_traced_kind } from './runner.js'\nimport type { RunContext, Step } from './types.js'\nimport { compute_backoff, wait_with_abort } from '#policy'\nimport type { BackoffPolicy } from '#policy'\n\nconst DEFAULT_BACKOFF_MS = 1_000\nconst DEFAULT_MAX_DELAY_MS = 30_000\n\n/**\n * How a retry reached its value: `attempts` counts every dispatch including the\n * one that succeeded, and `errors` holds each failed attempt's error in order,\n * so `errors.length === attempts - 1`.\n */\nexport type RetryOutcome<o> = {\n readonly value: o\n readonly attempts: number\n readonly errors: ReadonlyArray<unknown>\n}\n\nexport type RetryConfig = {\n readonly name?: string\n readonly description?: string\n readonly max_attempts: number\n readonly backoff_ms?: number\n readonly max_delay_ms?: number\n readonly jitter?: boolean\n /**\n * Decide whether an application error is retryable. Returning false\n * propagates the error untouched, the way a control-flow signal does.\n * Omitted, every application error is retryable.\n */\n readonly when?: (err: unknown, attempt: number) => boolean\n readonly on_error?: (err: unknown, attempt: number) => void\n}\n\n/**\n * The `project` option `retry` accepts beside `RetryConfig`. It sits outside\n * `RetryConfig` so a config annotated as `RetryConfig` leaves the output type\n * to be inferred from the inner step.\n */\nexport type RetryProjection<o, projected> = {\n /**\n * Map the `RetryOutcome` envelope into the step's output inside the retry\n * step itself, so `describe` and the trajectory gain no wrapper node.\n * Omitted, the value is the output.\n */\n readonly project?: (outcome: RetryOutcome<o>) => projected\n}\n\nlet retry_counter = 0\n\n/**\n * Generate a unique step id of the form `retry_<n>`.\n */\nfunction next_id(): string {\n retry_counter += 1\n return `retry_${retry_counter}`\n}\n\n/**\n * Map an abort reason onto the error a retry rejects with, preserving an\n * `Error` reason verbatim rather than wrapping it in `aborted_error`.\n *\n * Core's convention, shared with `timeout`, `parallel`, `map`, the runner's\n * `throw_if_aborted`, and `bench`: this layer owns the signal chain, so the\n * cause set upstream has to survive it. Wrapping would turn `timeout`'s\n * `timeout_error` into an abort, and would flatten the runner's\n * `aborted_error('received SIGINT')` into a bare 'aborted' that\n * `runner.ts`'s catch cannot repair, since that repair only fires when the\n * escaping error is not already an `aborted_error`.\n *\n * The engine's retry deliberately does the opposite; `#policy`'s\n * `AbortErrorFactory` is where the two meet.\n */\nfunction to_abort_error(reason: unknown): Error {\n return reason instanceof Error ? reason : new aborted_error('aborted', { reason })\n}\n\ntype Settled<o> = { readonly ok: true; readonly value: o } | { readonly ok: false; readonly error: unknown }\n\n/**\n * Settle one attempt into a value or the error it threw, so the attempt loop\n * reads as a sequence of decisions instead of a nest of try/catch arms.\n */\nasync function settle<o>(attempt: Promise<o>): Promise<Settled<o>> {\n try {\n return { ok: true, value: await attempt }\n } catch (error) {\n return { ok: false, error }\n }\n}\n\n/**\n * Build a retrying step around `inner`.\n *\n * Runs `inner` up to `max_attempts` times with exponential backoff between\n * failures. Retryable application errors consume an attempt and fire\n * `on_error`; control-flow signals and errors `when` rejects propagate\n * untouched. `project` maps the outcome envelope into the output.\n */\nexport function retry<i, o, projected = o>(\n inner: Step<i, o>,\n config: RetryConfig & RetryProjection<o, projected>,\n): Step<i, projected> {\n // A NaN or Infinity max_attempts would make the attempt loop never run (or\n // never end), so the misconfiguration fails at construction, not mid-run.\n if (!Number.isFinite(config.max_attempts)) {\n throw new TypeError(\n `retry: max_attempts must be a finite number, got ${config.max_attempts}`,\n )\n }\n const id = next_id()\n const max_attempts = Math.max(1, Math.floor(config.max_attempts))\n const backoff_ms = config.backoff_ms ?? DEFAULT_BACKOFF_MS\n const max_delay_ms = config.max_delay_ms ?? DEFAULT_MAX_DELAY_MS\n const jitter = config.jitter ?? true\n const when = config.when\n const on_error = config.on_error\n // When `project` is omitted, `projected` defaults to `o`, so handing back\n // the bare value is sound; the cast records that default.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: RetryOutcome<o>) => r.value as unknown as projected)\n const backoff_policy: BackoffPolicy = { initial_delay_ms: backoff_ms, max_delay_ms, jitter }\n\n const is_retryable = (err: unknown, attempt: number): boolean =>\n !is_control_flow_error(err) && (when === undefined || when(err, attempt))\n\n const run_fn = async (input: i, ctx: RunContext): Promise<projected> => {\n const errors: unknown[] = []\n for (let attempt = 1; attempt <= max_attempts; attempt += 1) {\n if (ctx.abort.aborted) {\n throw to_abort_error(ctx.abort.reason)\n }\n const settled = await settle(dispatch_step(inner, input, ctx))\n // `project` runs outside the settled attempt, so an error it throws is\n // the caller's bug surfacing once rather than a failure that consumes\n // another attempt.\n if (settled.ok) return project({ value: settled.value, attempts: attempt, errors })\n if (!is_retryable(settled.error, attempt)) throw settled.error\n errors.push(settled.error)\n if (on_error) on_error(settled.error, attempt)\n if (attempt >= max_attempts) break\n const delay = compute_backoff(backoff_policy, attempt - 1)\n await wait_with_abort(delay, ctx.abort, to_abort_error)\n }\n // Stryker disable next-line all: the finiteness guard above forces max_attempts >= 1, so the loop always records an error before this throw; the ?? arm is unreachable belt and braces.\n throw errors.at(-1) ?? new Error('retry: no attempts executed')\n }\n\n const config_meta: Record<string, unknown> = { max_attempts, backoff_ms, max_delay_ms, jitter }\n if (when) config_meta['when'] = when\n if (on_error) config_meta['on_error'] = on_error\n if (config.project) config_meta['project'] = config.project\n if (config.name !== undefined) config_meta['display_name'] = config.name\n\n return {\n id,\n kind: 'retry',\n children: [inner],\n config: config_meta,\n ...description_meta(config.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('retry')\n","/**\n * fallback: primary-or-backup.\n *\n * `fallback(primary, backup)` runs `primary`. If it throws an application\n * error, runs `backup` with the same input, or with `handoff(input, err)`\n * when the `handoff` option is set, so the backup can be told why it is\n * running. If `backup` also throws, the `backup` error propagates with the\n * primary's error attached as its `cause` (unless it already carries one),\n * so the original failure stays diagnosable from the escaping error.\n * Control-flow signals (`suspended_error`, `aborted_error`) are not\n * failures: they propagate instead of triggering the backup, so a\n * human-approval gate is never silently bypassed and the backup never runs\n * under an aborted context. `handoff` is never called for them. The `when`\n * option narrows the set further: a primary error it rejects propagates the\n * same way, untouched.\n *\n * `project` maps the `{ value, source, primary_error }` envelope into the\n * step's output, so a caller can tell a backup's value from the primary's\n * without a mutable closure. Omitted, the value is the output.\n */\n\nimport { description_meta } from './display_name.js'\nimport { is_control_flow_error } from './errors.js'\nimport { dispatch_step, register_traced_kind } from './runner.js'\nimport type { RunContext, Step } from './types.js'\n\nlet fallback_counter = 0\n\n/**\n * Generate a unique step id of the form `fallback_<n>`.\n */\nfunction next_id(): string {\n fallback_counter += 1\n return `fallback_${fallback_counter}`\n}\n\n/**\n * Which leg produced a fallback's value. `primary_error` is the error that\n * sent the run to the backup, present only when `source` is `'backup'`.\n */\nexport type FallbackOutcome<o> =\n | { readonly value: o; readonly source: 'primary'; readonly primary_error?: undefined }\n | { readonly value: o; readonly source: 'backup'; readonly primary_error: unknown }\n\nexport type FallbackOptions<i = unknown> = {\n readonly name?: string\n readonly description?: string\n /**\n * Decide whether a primary error sends the run to the backup. Returning\n * false propagates the error untouched, the way a control-flow signal\n * does. Omitted, every application error does.\n */\n readonly when?: (err: unknown) => boolean\n readonly handoff?: (input: i, err: unknown) => i\n}\n\n/**\n * The `project` option `fallback` accepts beside `FallbackOptions`. It sits\n * outside `FallbackOptions` so options annotated as `FallbackOptions` leave\n * the output type to be inferred from the two legs.\n */\nexport type FallbackProjection<o, projected> = {\n /**\n * Map the `FallbackOutcome` envelope into the step's output inside the\n * fallback step itself, so `describe` and the trajectory gain no wrapper\n * node. Omitted, the value is the output.\n */\n readonly project?: (outcome: FallbackOutcome<o>) => projected\n}\n\n/**\n * Build a primary-or-backup step.\n *\n * Runs `primary`; on an application error `when` accepts, runs `backup` with\n * the same input, or with `handoff(input, err)` when the option is set.\n * Control-flow signals and errors `when` rejects propagate without\n * triggering the backup or the handoff. `project` maps the outcome envelope\n * into the output.\n */\nexport function fallback<i, o, projected = o>(\n primary: Step<i, o>,\n backup: Step<i, o>,\n options?: FallbackOptions<i> & FallbackProjection<o, projected>,\n): Step<i, projected> {\n const id = next_id()\n const when = options?.when\n const handoff = options?.handoff\n // When `project` is omitted, `projected` defaults to `o`, so handing back\n // the bare value is sound; the cast records that default.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = options?.project ?? ((r: FallbackOutcome<o>) => r.value as unknown as projected)\n\n const run_backup = async (input: i, primary_error: unknown, ctx: RunContext): Promise<o> => {\n const backup_input = handoff === undefined ? input : handoff(input, primary_error)\n try {\n return await dispatch_step(backup, backup_input, ctx)\n } catch (backup_err) {\n // When both legs fail, only the backup's error escapes; without this\n // the primary's failure would be lost entirely. Control-flow signals\n // are not failures and pass through unmodified, and an existing cause\n // is never clobbered.\n if (\n !is_control_flow_error(backup_err) &&\n backup_err instanceof Error &&\n !('cause' in backup_err)\n ) {\n backup_err.cause = primary_error\n }\n throw backup_err\n }\n }\n\n // Each leg's value is projected outside its try, so an error thrown by\n // `project` is the caller's bug surfacing once rather than a primary\n // failure that sends the run to the backup.\n const run_fn = async (input: i, ctx: RunContext): Promise<projected> => {\n let value: o\n try {\n value = await dispatch_step(primary, input, ctx)\n } catch (err) {\n if (is_control_flow_error(err)) throw err\n if (when !== undefined && !when(err)) throw err\n const backup_value = await run_backup(input, err, ctx)\n return project({ value: backup_value, source: 'backup', primary_error: err })\n }\n return project({ value, source: 'primary' })\n }\n\n const config_meta: Record<string, unknown> = {}\n if (when) config_meta['when'] = when\n if (handoff) config_meta['handoff'] = handoff\n if (options?.project) config_meta['project'] = options.project\n if (options?.name !== undefined) config_meta['display_name'] = options.name\n\n return {\n id,\n kind: 'fallback',\n children: [primary, backup],\n ...(Object.keys(config_meta).length > 0 ? { config: config_meta } : {}),\n ...description_meta(options?.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('fallback')\n","/**\n * timeout: bound execution.\n *\n * `timeout(inner, ms)` runs `inner` with a composed `AbortSignal` that fires\n * at `ms` milliseconds. If the inner step does not complete in time, throws\n * `timeout_error`. The inner step is responsible for honoring `ctx.abort`;\n * a step that ignores the signal still triggers `timeout_error` on schedule\n * but continues running in the background.\n *\n * Cancellation: the inner step runs with\n * `AbortSignal.any([ctx.abort, timeout_local])`. On timer expiry, the local\n * controller aborts with a `timeout_error` as its reason; on parent abort\n * the parent reason flows through. The timer is always cleared in a finally\n * block so it does not leak across retries.\n */\n\nimport { description_meta } from './display_name.js'\nimport { aborted_error, timeout_error } from './errors.js'\nimport { dispatch_step, register_traced_kind } from './runner.js'\nimport type { RunContext, Step } from './types.js'\n\nlet timeout_counter = 0\n\n/**\n * Generate a unique step id of the form `timeout_<n>`.\n */\nfunction next_id(): string {\n timeout_counter += 1\n return `timeout_${timeout_counter}`\n}\n\nexport type TimeoutOptions = {\n readonly name?: string\n readonly description?: string\n}\n\n/**\n * Build a deadline-bounded step around `inner`.\n *\n * Races the inner dispatch against a timer that aborts the composed signal\n * with `timeout_error`. The `timed_out` flag distinguishes timer expiry from\n * a parent abort so the right error propagates.\n */\nexport function timeout<i, o>(\n inner: Step<i, o>,\n ms: number,\n options?: TimeoutOptions,\n): Step<i, o> {\n const id = next_id()\n\n const run_fn = async (input: i, ctx: RunContext): Promise<o> => {\n const local = new AbortController()\n const composed = AbortSignal.any([ctx.abort, local.signal])\n const child_ctx: RunContext = { ...ctx, abort: composed }\n \n let timed_out = false\n const timer = setTimeout(() => {\n timed_out = true\n local.abort(new timeout_error(`timeout after ${ms}ms`, ms))\n }, ms)\n \n const deadline = new Promise<never>((_, reject) => {\n const on_local_abort = (): void => {\n if (timed_out) {\n reject(new timeout_error(`timeout after ${ms}ms`, ms))\n } else {\n const reason = ctx.abort.reason\n reject(reason instanceof Error ? reason : new aborted_error('aborted', { reason }))\n }\n }\n if (composed.aborted) {\n on_local_abort()\n return\n }\n composed.addEventListener('abort', on_local_abort, { once: true })\n })\n \n try {\n return await Promise.race([dispatch_step(inner, input, child_ctx), deadline])\n } finally {\n clearTimeout(timer)\n }\n }\n\n const config_meta: Record<string, unknown> = { ms }\n if (options?.name !== undefined) config_meta['display_name'] = options.name\n\n return {\n id,\n kind: 'timeout',\n children: [inner],\n config: config_meta,\n ...description_meta(options?.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('timeout')\n","/**\n * loop: bounded iteration with carry-state.\n *\n * `loop({ init, body, guard?, finish, max_rounds, name? })` runs `body` up to\n * `max_rounds` times, threading `state` through each iteration. After every\n * `body` call, an optional `guard` step inspects (and may transform) the state\n * and decides whether to stop; a bare `(state) => boolean` predicate is\n * accepted as shorthand for a guard that stops without transforming.\n * When `guard.stop` is true, the loop exits\n * \"converged\"; otherwise it continues until `max_rounds`. `finish` projects\n * the final state to the loop's output value, and is the loop's only output\n * channel: `loop` returns `Step<i, o>`, not an envelope around `o`.\n *\n * Non-convergence is data, not error, and `finish` is where that data arrives:\n * its second argument is the `LoopOutcome` (`{ converged, rounds }`), so a\n * projection can fold either field into its own result shape, the way\n * `adversarial` and `consensus` do. A projection that wants the whole outcome\n * verbatim writes `finish: (state, outcome) => ({ value: state, ...outcome })`.\n *\n * Cancellation: between rounds the parent `ctx.abort` is honored; a pending\n * abort short-circuits and propagates `ctx.abort.reason`. The body and guard\n * receive the parent context unchanged; their own dispatch routes already\n * thread cancellation per the runner contract.\n */\n\nimport { description_meta } from './display_name.js'\nimport { dispatch_step, register_traced_kind, throw_if_aborted } from './runner.js'\nimport { step } from './step.js'\nimport type { AnyStep, RunContext, Step } from './types.js'\n\nexport type LoopGuardResult<state> = {\n readonly stop: boolean\n readonly state: state\n}\n\nexport type LoopGuardPredicate<state> = (state: state) => boolean | Promise<boolean>\n\nexport type LoopOutcome = {\n readonly converged: boolean\n readonly rounds: number\n}\n\nexport type LoopConfig<i, state, o> = {\n readonly name?: string\n readonly description?: string\n readonly init: (input: i) => state\n readonly body: Step<state, state>\n readonly guard?: Step<state, LoopGuardResult<state>> | LoopGuardPredicate<state>\n readonly finish: (state: state, outcome: LoopOutcome) => o\n readonly max_rounds: number\n}\n\nlet loop_counter = 0\n\n/**\n * Generate a unique step id of the form `loop_<n>`.\n *\n * The display `name` deliberately stays out of the id. It is free prose, so\n * folding it in would both make a cosmetic rename move a trajectory id and\n * put an arbitrary string where an identifier is required.\n */\nfunction next_id(): string {\n loop_counter += 1\n return `loop_${loop_counter}`\n}\n\n/**\n * Normalize the guard config to its step form.\n *\n * A bare predicate is sugar for the state-preserving guard step, wrapped here\n * (with an id derived from the loop's, so trees with several loops stay\n * unambiguous) rather than special-cased in the run loop: the predicate form\n * then dispatches, traces, and terminates identically to a hand-written guard.\n * The wrapper is marked anonymous because its id carries the loop's counter,\n * which `describe.diagram` must never print.\n */\nfunction wrap_guard<state>(\n guard: Step<state, LoopGuardResult<state>> | LoopGuardPredicate<state> | undefined,\n loop_id: string,\n): Step<state, LoopGuardResult<state>> | undefined {\n if (guard === undefined) return undefined\n if (typeof guard !== 'function') return guard\n const wrapped = step(`${loop_id}_guard`, async (state: state) => ({\n stop: await guard(state),\n state,\n }))\n return { ...wrapped, anonymous: true }\n}\n\n/**\n * Build a bounded iteration step with carry-state.\n *\n * Threads `state` through up to `max_rounds` runs of `body`, lets the\n * optional `guard` stop early, then projects the final state through\n * `finish`. `finish` also receives `{ converged, rounds }`, so a projection\n * can tell a converged run from an exhausted one without the loop wrapping\n * its output.\n */\nexport function loop<i, state, o>(config: LoopConfig<i, state, o>): Step<i, o> {\n const { init, body, finish, name } = config\n // A NaN max_rounds would make the loop run zero rounds, so the\n // misconfiguration fails at construction, not mid-run. Infinity is a valid\n // bound for a loop that only its guard stops.\n if (Number.isNaN(config.max_rounds)) {\n throw new TypeError(`loop: max_rounds must be a number, got ${config.max_rounds}`)\n }\n const rounds_limit = Math.max(1, Math.floor(config.max_rounds))\n const id = next_id()\n const guard = wrap_guard(config.guard, id)\n\n const run_fn = async (input: i, ctx: RunContext): Promise<o> => {\n let state = init(input)\n let round = 0\n let converged = false\n \n while (round < rounds_limit) {\n throw_if_aborted(ctx)\n round += 1\n state = await dispatch_step(body, state, ctx)\n if (guard) {\n throw_if_aborted(ctx)\n const guard_out = await dispatch_step(guard, state, ctx)\n state = guard_out.state\n if (guard_out.stop) {\n converged = true\n break\n }\n }\n }\n \n return finish(state, { converged, rounds: round })\n }\n\n const config_meta: Record<string, unknown> = { max_rounds: rounds_limit }\n if (name !== undefined) config_meta['display_name'] = name\n const children: ReadonlyArray<AnyStep> = guard\n ? [body, guard]\n : [body]\n\n return {\n id,\n kind: 'loop',\n children,\n config: config_meta,\n ...description_meta(config.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('loop')\n","/**\n * compose: name a composite step.\n *\n * `compose(inner, { name })` wraps any step and labels its trajectory span\n * with `name`. The inner step's own span (for example, a `sequence`) appears\n * as a child of the compose span: the implementation tree is preserved while\n * the user's intent (\"this whole thing is an ensemble\") is surfaced in\n * observability.\n *\n * Used by the composites package to make built-in patterns appear under\n * their familiar names, and available to library consumers who want their own\n * named composites to show up in logs as first-class components.\n *\n * The primitive's `kind` is always `'compose'` and its id is `compose_<n>`.\n * The user-supplied label lives in `config.display_name`, is the span name\n * the dispatcher opens, and never reaches the id: it is free prose, so\n * folding it in would let a cosmetic rename move a trajectory id.\n */\n\nimport { description_meta } from './display_name.js'\nimport { dispatch_step, register_traced_kind } from './runner.js'\nimport type { AnyStep, RunContext, Step } from './types.js'\n\nexport type ComposeConfig = {\n readonly name: string\n // Admits an explicit undefined so a named composite can forward its own\n // optional description without a conditional spread.\n readonly description?: string | undefined\n // The steps, by role, that a reader should see when the composite is drawn.\n // Each has to sit somewhere inside `inner`. `describe.diagram` draws the\n // composite as one node over these, and `{ internals: true }` draws `inner`.\n readonly parts?: Readonly<Record<string, AnyStep>> | undefined\n}\n\nlet compose_counter = 0\n\n/**\n * Generate a unique step id of the form `compose_<n>`.\n */\nfunction next_id(): string {\n compose_counter += 1\n return `compose_${compose_counter}`\n}\n\n/**\n * Wrap `inner` in a named composite step.\n *\n * The step's `kind` is always `'compose'`; `config.name` becomes the\n * `display_name` used as the span label. Throws a `TypeError` when `name`\n * is not a non-empty string, catching the mistake at construction time.\n *\n * Each of `config.parts` is recorded as the path of child indices that leads\n * to it from the composite, so `describe.json` keeps the whole tree that the\n * viewer maps spans onto while `describe.diagram` can draw just the parts. A\n * part that isn't inside `inner` throws, since there would be no path to draw.\n */\nexport function compose<i, o>(inner: Step<i, o>, config: ComposeConfig): Step<i, o> {\n const name = config?.name\n if (typeof name !== 'string' || name.length === 0) {\n throw new TypeError('compose(inner, { name }): name must be a non-empty string')\n }\n const parts = part_paths(inner, config.parts)\n const id = next_id()\n\n const run_fn = (input: i, ctx: RunContext): Promise<o> | o => dispatch_step(inner, input, ctx)\n\n return {\n id,\n kind: 'compose',\n children: [inner],\n config: parts === undefined ? { display_name: name } : { display_name: name, parts },\n ...description_meta(config.description),\n run: run_fn,\n }\n}\n\n/**\n * The path of child indices from the composite to each part, by role, or\n * `undefined` when there are no parts. Every path starts at `inner`, the\n * composite's only child.\n */\nfunction part_paths(\n inner: AnyStep,\n parts: Readonly<Record<string, AnyStep>> | undefined,\n): Readonly<Record<string, ReadonlyArray<number>>> | undefined {\n if (parts === undefined) return undefined\n const paths: Record<string, ReadonlyArray<number>> = {}\n for (const [role, part] of Object.entries(parts)) {\n const path = path_to(inner, part, new Set())\n if (path === undefined) {\n throw new TypeError(\n `compose(inner, { parts }): part \"${role}\" (${part.kind} ${part.id}) is not inside inner, so the diagram would have nothing to draw for it`,\n )\n }\n paths[role] = [0, ...path]\n }\n return paths\n}\n\n/**\n * The child indices that lead from `from` to `target`, found depth first by\n * identity, or `undefined` when `target` isn't below it. `seen` keeps a shared\n * step from being walked twice.\n */\nfunction path_to(from: AnyStep, target: AnyStep, seen: Set<AnyStep>): ReadonlyArray<number> | undefined {\n if (from === target) return []\n if (seen.has(from)) return undefined\n seen.add(from)\n const children = from.children\n if (children === undefined) return undefined\n for (const [index, child] of children.entries()) {\n const rest = path_to(child, target, seen)\n if (rest !== undefined) return [index, ...rest]\n }\n return undefined\n}\n\nregister_traced_kind('compose')\n","/**\n * checkpoint: persist and resume.\n *\n * `checkpoint(inner, { key })` checks a persistent store for a completed\n * result at `key` before running `inner`. On a hit, returns the stored\n * value. On a miss, runs `inner`, persists its result at `key`, and returns\n * it. A corrupted read (the store throws on `get`) is a miss by default.\n * Every lookup records a `checkpoint` trajectory event with\n * `status: 'hit' | 'miss' | 'read_error'`.\n *\n * A failed write (store throws on `set`) doesn't fail the run either. It\n * records a `checkpoint` event with `status: 'write_error'` and returns the\n * inner result, because `inner` has already run and been paid for, and a\n * checkpoint is a cache, not the result. The next run with the same key\n * misses and runs `inner` again. `on_write_error: 'fail'` records the same\n * event and then throws the store's error, for a result that a `suspend`\n * hands to an approver, which has to be the one the store kept.\n *\n * `on_read_error: 'fail'` does the same for a failed read: it records the\n * `read_error` event and then throws the store's error rather than run\n * `inner`. A checkpoint whose result a `suspend` shows wants both, since a\n * resume that runs `inner` again would pass a new result through an approval\n * that covered the old one.\n *\n * Wrapping an anonymous inner step throws synchronously at construction time\n * with the message `checkpoint requires a named step, got anonymous`, because\n * a cached result must map back to a stable, identifiable step.\n *\n * A hit stands in for every `suspend` gate inside `inner` as well. Those gates\n * ran when the result was stored, so a resumed run that skips them has still\n * reached them, and the steps after the checkpoint aren't replays.\n */\n\nimport { description_meta } from './display_name.js'\nimport { dispatch_step, mark_gates_reached, register_traced_kind } from './runner.js'\nimport type { AnyStep, CheckpointStore, RunContext, Step, TrajectoryEvent } from './types.js'\n\nexport type CheckpointConfig<i> = {\n readonly name?: string\n readonly description?: string\n readonly key: string | ((input: i) => string)\n /**\n * What a failed `store.set` does. `'record'` (the default) records a\n * `write_error` event and returns the inner result. `'fail'` records the\n * same event and then throws the store's error, which is what a step whose\n * result a `suspend` hands to an approver wants, so the approval never\n * refers to a result that the store didn't keep.\n */\n readonly on_write_error?: 'record' | 'fail'\n /**\n * What a failed `store.get` does. `'miss'` (the default) records a\n * `read_error` event and runs `inner`, as today. `'fail'` records the same\n * event and then throws the store's error, which is what a checkpoint\n * whose result a `suspend` hands to an approver wants, so a resume never\n * runs `inner` again and passes the new result through.\n */\n readonly on_read_error?: 'miss' | 'fail'\n}\n\nlet checkpoint_counter = 0\n\n/**\n * Generate a unique step id of the form `checkpoint_<n>`.\n */\nfunction next_id(): string {\n checkpoint_counter += 1\n return `checkpoint_${checkpoint_counter}`\n}\n\n/**\n * The ids of every `suspend` gate in a step tree, the root included. `seen`\n * guards against a tree that reaches the same step twice.\n */\nfunction gates_within(root: AnyStep, seen: Set<AnyStep> = new Set()): string[] {\n // Stryker disable next-line ArrayDeclaration: a step met a second time already had its gates counted, and a stray extra id names no gate, so it marks nothing.\n if (seen.has(root)) return []\n seen.add(root)\n // Stryker disable next-line ArrayDeclaration: a stray child seeded into a leaf is no suspend step and has no children of its own, so it adds no gate.\n const inner = (root.children ?? []).flatMap((child) => gates_within(child, seen))\n return root.kind === 'suspend' ? [root.id, ...inner] : inner\n}\n\ntype EventMeta = Readonly<Record<string, unknown>>\n\n/**\n * The fields every `checkpoint` event of one lookup carries: the step `id`,\n * the store `key`, and the `span_id` of the checkpoint's span when there is\n * one, so a viewer can nest the event.\n */\nfunction event_meta(id: string, key: string, ctx: RunContext): EventMeta {\n const meta: Record<string, unknown> = { id, key }\n // Stryker disable next-line ConditionalExpression: the runner opens a span for every checkpoint it dispatches, so `parent_span_id` is always set here under `run`.\n if (ctx.parent_span_id !== undefined) meta['span_id'] = ctx.parent_span_id\n return meta\n}\n\n/**\n * The `checkpoint` event for a store call that threw, carrying its message.\n */\nfunction store_failure(\n status: 'read_error' | 'write_error',\n err: unknown,\n meta: EventMeta,\n): TrajectoryEvent {\n return {\n kind: 'checkpoint',\n status,\n error: err instanceof Error ? err.message : String(err),\n ...meta,\n }\n}\n\n/**\n * The value stored at `key` in `store`, or `undefined` on a miss, recording\n * exactly one `checkpoint` event so hits, misses, and read errors are all\n * visible in the trajectory. A stored `null` or `undefined` is a miss, which\n * is what lets `undefined` stand for one. A throwing `store.get` records\n * `status: 'read_error'` and behaves as a miss, so a broken store doesn't\n * fail the run, unless `fail_on_read` says to throw the store's error once\n * the event is recorded.\n */\nasync function look_up(\n store: CheckpointStore,\n key: string,\n meta: EventMeta,\n ctx: RunContext,\n fail_on_read: boolean,\n): Promise<unknown> {\n try {\n const value = await store.get(key)\n const hit = value !== null && value !== undefined\n ctx.trajectory.record({ kind: 'checkpoint', status: hit ? 'hit' : 'miss', ...meta })\n return hit ? value : undefined\n } catch (err) {\n ctx.trajectory.record(store_failure('read_error', err, meta))\n if (fail_on_read) throw err\n return undefined\n }\n}\n\n/**\n * Write `result` to `store` at `key`. A throwing `store.set` records\n * `status: 'write_error'` and leaves the result to the caller, since the\n * inner step that produced it has already run, unless `fail_on_write` says\n * to throw the store's error once the event is recorded.\n */\nasync function keep(\n store: CheckpointStore,\n key: string,\n result: unknown,\n meta: EventMeta,\n ctx: RunContext,\n fail_on_write: boolean,\n): Promise<void> {\n try {\n await store.set(key, result)\n } catch (err) {\n ctx.trajectory.record(store_failure('write_error', err, meta))\n if (fail_on_write) throw err\n }\n}\n\n/**\n * Wrap `inner` with persist-and-resume behavior keyed by `config.key`.\n *\n * `key` is a fixed string or a function of the input. Without a\n * `checkpoint_store` on the run context, the wrapper runs `inner` directly.\n * A stored `null` or `undefined` counts as a miss, so those values are\n * re-computed rather than replayed. Throws at construction time when `inner`\n * is anonymous.\n */\nexport function checkpoint<i, o>(inner: Step<i, o>, config: CheckpointConfig<i>): Step<i, o> {\n if (inner.anonymous === true) {\n throw new Error(\n \"checkpoint requires a named step, got anonymous — give the inner step an id with step('id', fn)\",\n )\n }\n\n const id = next_id()\n const key_spec = config.key\n const fail_on_write = config.on_write_error === 'fail'\n const fail_on_read = config.on_read_error === 'fail'\n const gates = gates_within(inner)\n\n const run_fn = async (input: i, ctx: RunContext): Promise<o> => {\n const key = typeof key_spec === 'function' ? key_spec(input) : key_spec\n const store = ctx.checkpoint_store\n if (!store) return dispatch_step(inner, input, ctx)\n\n const meta = event_meta(id, key, ctx)\n const cached = await look_up(store, key, meta, ctx, fail_on_read)\n if (cached !== undefined) {\n mark_gates_reached(ctx, gates)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return cached as o\n }\n\n const result = await dispatch_step(inner, input, ctx)\n await keep(store, key, result, meta, ctx, fail_on_write)\n return result\n }\n\n const config_meta: Record<string, unknown> = { key: key_spec }\n if (config.name !== undefined) config_meta['display_name'] = config.name\n\n return {\n id,\n kind: 'checkpoint',\n children: [inner],\n config: config_meta,\n ...description_meta(config.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('checkpoint')\n","/**\n * suspend: human-in-the-loop pause.\n *\n * `suspend({ id, on, resume_schema, combine })` pauses a flow waiting on\n * external input (a notification, an approval, an uploaded file). On first\n * encounter with no resume data, it calls `on(input, ctx)` (side effect),\n * records a `suspended` trajectory event, and throws `suspended_error`\n * carrying the run state. On resume (re-invocation\n * with `run_options.resume_data[id]` populated), the provided value is\n * validated against `resume_schema` and passed to `combine(input, resume,\n * ctx)`; the result is returned. Invalid resume data throws\n * `resume_validation_error` carrying the vendor-neutral issue list.\n *\n * A run takes each id's datum once. A run that reaches the suspend again on\n * the same input takes it again, the way a `retry` runs a step again, and\n * one that reaches it on another input, in a later round of a `loop` or for\n * the next item of a `map`, throws `duplicate_suspend_id_error` with\n * `reason: 'reached_twice'`, since the datum answered the first input.\n *\n * `deadline_ms` says how long the gate waits for its resume. The run can't\n * keep a clock of its own, since it unwinds as soon as it suspends, so the\n * value rides out on the `suspended_error` (and the outcome\n * `run.until_suspended` reports) for whoever drives the run to schedule a\n * timer that resumes the gate with whatever a timed-out resume means to it.\n */\n\nimport { validate_schema, type AnySchema } from '#schema'\nimport { description_meta } from './display_name.js'\nimport { resume_validation_error, suspended_error } from './errors.js'\nimport { is_step } from './is_step.js'\nimport { dispatch_step, mark_gates_reached, note_datum_taken, register_traced_kind } from './runner.js'\nimport { assert_valid_step_id } from './step_id.js'\nimport type { RunContext, Step } from './types.js'\n\nexport type SuspendConfig<i, o, resume> = {\n readonly id: string\n readonly name?: string\n readonly description?: string\n readonly deadline_ms?: number\n readonly on: (input: i, ctx: RunContext) => Promise<void> | void\n readonly resume_schema: AnySchema<resume>\n readonly combine: (\n input: i,\n resume: resume,\n ctx: RunContext,\n ) => Promise<o> | o | Step<i, o>\n}\n\n/**\n * The resume value addressed to `suspend_id`, read from the run's own resume\n * data only, so a gate named like an `Object.prototype` member (`toString`,\n * `constructor`) never mistakes the inherited member for a decision.\n */\nfunction resume_value_for(ctx: RunContext, suspend_id: string): unknown {\n const resume_data = ctx.resume_data\n return resume_data !== undefined && Object.hasOwn(resume_data, suspend_id)\n ? resume_data[suspend_id]\n : undefined\n}\n\n/**\n * Build a human-in-the-loop pause step.\n *\n * First run fires the `on` side effect and throws `suspended_error`; a resume\n * run validates `resume_data[id]` against `resume_schema` and feeds it to\n * `combine`. The step's id is the user-supplied suspend id so resume data can\n * be addressed to it, which is why it's held to the step id rule and throws\n * a `TypeError` when it's built if it isn't an identifier.\n */\nexport function suspend<i, o, resume>(config: SuspendConfig<i, o, resume>): Step<i, o> {\n assert_valid_step_id(config.id, 'suspend id', 'put the label in name')\n const suspend_id = config.id\n const deadline_ms = config.deadline_ms\n const on_fn = config.on\n const resume_schema = config.resume_schema\n const combine_fn = config.combine\n\n const run_fn = async (input: i, ctx: RunContext): Promise<o> => {\n const resume_value = resume_value_for(ctx, suspend_id)\n \n if (resume_value === undefined) {\n await on_fn(input, ctx)\n // Mark the suspension on the wire before the throw, so a consumer sees\n // the gate pause as its own event ahead of the span-end error the\n // runner records for the escaping suspended_error. step_id is the\n // suspend step's id (the suspend id), the join key back to the\n // flow_structure node.\n ctx.trajectory.record({\n kind: 'suspended',\n suspend_id,\n step_id: suspend_id,\n ...(deadline_ms === undefined ? {} : { deadline_ms }),\n })\n throw new suspended_error(suspend_id, { input }, undefined, deadline_ms)\n }\n\n note_datum_taken(ctx, suspend_id, input)\n mark_gates_reached(ctx, [suspend_id])\n const parsed = await validate_schema(resume_schema, resume_value)\n if (!parsed.ok) {\n throw new resume_validation_error(\n `resume data for ${suspend_id} failed validation`,\n parsed.issues,\n suspend_id,\n )\n }\n\n const result = await combine_fn(input, parsed.value, ctx)\n if (is_step(result)) {\n return dispatch_step(result, input, ctx)\n }\n return result\n }\n\n const config_meta: Record<string, unknown> = { id: suspend_id }\n if (deadline_ms !== undefined) config_meta['deadline_ms'] = deadline_ms\n if (config.name !== undefined) config_meta['display_name'] = config.name\n\n return {\n id: suspend_id,\n kind: 'suspend',\n config: config_meta,\n ...description_meta(config.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('suspend')\n","/**\n * scope / stash / use: named state.\n *\n * `scope([...children])` introduces a scope-local `Map<string, unknown>` and\n * runs its children in order, chaining outputs like `sequence`. `stash(key,\n * source)` runs `source`, writes its output to the scope's state at `key`,\n * and passes the value through. `use(keys, fn)` reads the named values from\n * state and runs `fn` with the projection. Inner scopes inherit outer state;\n * writes only affect the inner map.\n *\n * Using `stash` or `use` outside a `scope` is a runtime error with a clear\n * message.\n */\n\nimport { description_meta } from './display_name.js'\nimport { dispatch_step, register_traced_kind, throw_if_aborted } from './runner.js'\nimport type { AnyStep, RunContext, Step } from './types.js'\n\ntype LastOutput<children> = children extends readonly [...unknown[], Step<never, infer o>]\n ? o\n : children extends readonly [Step<never, infer o>]\n ? o\n : unknown\n\nconst scope_states = new WeakSet<ReadonlyMap<string, unknown>>()\n\n/**\n * Check whether a state map was created by `scope`.\n *\n * The root `RunContext.state` map is not registered in `scope_states`, which\n * is how `stash`/`use` detect they are running outside any scope.\n */\nfunction is_scope_state(state: ReadonlyMap<string, unknown>): boolean {\n return scope_states.has(state)\n}\n\nlet scope_counter = 0\nlet stash_counter = 0\nlet use_counter = 0\n\n/**\n * Generate a unique step id of the form `scope_<n>`.\n */\nfunction next_scope_id(): string {\n scope_counter += 1\n return `scope_${scope_counter}`\n}\n\n/**\n * Generate a unique step id of the form `stash_<n>`.\n */\nfunction next_stash_id(): string {\n stash_counter += 1\n return `stash_${stash_counter}`\n}\n\n/**\n * Generate a unique step id of the form `use_<n>`.\n */\nfunction next_use_id(): string {\n use_counter += 1\n return `use_${use_counter}`\n}\n\nexport type ScopeOptions = {\n readonly name?: string\n readonly description?: string\n}\n\nexport type StashOptions = {\n readonly name?: string\n readonly description?: string\n}\n\nexport type UseOptions = {\n readonly name?: string\n readonly description?: string\n}\n\n/**\n * Build a step that runs children in sequence under a fresh state map.\n *\n * The local map is seeded from the parent state (inner scopes read outer\n * values) and registered so `stash`/`use` inside recognize it; writes stay\n * local to this scope. Outputs chain like `sequence`.\n */\nexport function scope<const children extends readonly AnyStep[]>(\n children: children,\n options?: ScopeOptions,\n): Step<unknown, LastOutput<children>> {\n const id = next_scope_id()\n const children_ref = children\n\n const run_fn = async (input: unknown, ctx: RunContext): Promise<unknown> => {\n const local = new Map<string, unknown>(ctx.state)\n scope_states.add(local)\n const scope_ctx: RunContext = { ...ctx, state: local }\n \n let acc: unknown = input\n for (const child of children_ref) {\n throw_if_aborted(scope_ctx)\n // The children list erases step types; the chaining contract pairs each\n // child with its predecessor's output, so the dispatch re-asserts it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n acc = await dispatch_step(child, acc as never, scope_ctx)\n }\n return acc\n }\n\n const config_meta: Record<string, unknown> | undefined =\n options?.name === undefined ? undefined : { display_name: options.name }\n\n const built = {\n id,\n kind: 'scope',\n children,\n ...(config_meta ? { config: config_meta } : {}),\n ...description_meta(options?.description),\n run: run_fn,\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return built as Step<unknown, LastOutput<children>>\n}\n\n/**\n * Build a step that stores its source's output in scope state at `key`.\n *\n * Passes the value through unchanged so it composes mid-chain. Throws when\n * run outside a `scope`.\n */\nexport function stash<i, v>(\n key: string,\n source: Step<i, v>,\n options?: StashOptions,\n): Step<i, v> {\n const id = next_stash_id()\n\n const run_fn = async (input: i, ctx: RunContext): Promise<v> => {\n if (!is_scope_state(ctx.state)) {\n throw new Error(\n `stash('${key}') ran outside any scope(): wrap it and the steps that use() its key in scope([...])`,\n )\n }\n const value = await dispatch_step(source, input, ctx)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const state = ctx.state as Map<string, unknown>\n state.set(key, value)\n return value\n }\n\n const config_meta: Record<string, unknown> = { key }\n if (options?.name !== undefined) config_meta['display_name'] = options.name\n\n return {\n id,\n kind: 'stash',\n children: [source],\n config: config_meta,\n ...description_meta(options?.description),\n run: run_fn,\n }\n}\n\n/**\n * Build a step that projects named scope values into a function call.\n *\n * Reads `keys` from scope state (missing keys project as `undefined`) and\n * invokes `fn(projection, input, ctx)`. Throws when run outside a `scope`.\n */\nexport function use<const keys extends readonly string[], i, o>(\n keys: keys,\n fn: (\n state: { [k in keys[number]]: unknown },\n input: i,\n ctx: RunContext,\n ) => Promise<o> | o,\n options?: UseOptions,\n): Step<i, o> {\n const id = next_use_id()\n\n const run_fn = async (input: i, ctx: RunContext): Promise<o> => {\n if (!is_scope_state(ctx.state)) {\n const listed = keys.map((k) => `'${k}'`).join(', ')\n throw new Error(\n `use([${listed}]) ran outside any scope(): wrap it and the stash() steps that set its keys in scope([...])`,\n )\n }\n const projection: Record<string, unknown> = {}\n for (const k of keys) {\n projection[k] = ctx.state.get(k)\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return fn(projection as { [k in keys[number]]: unknown }, input, ctx)\n }\n\n const config_meta: Record<string, unknown> = { keys: [...keys] }\n if (options?.name !== undefined) config_meta['display_name'] = options.name\n\n return {\n id,\n kind: 'use',\n config: config_meta,\n ...description_meta(options?.description),\n run: run_fn,\n }\n}\n\nregister_traced_kind('scope')\n\nregister_traced_kind('stash')\n\nregister_traced_kind('use')\n","/**\n * chain: named steps over a growing record.\n *\n * `chain<i>(input_name?)` opens a builder whose threaded value is a record of\n * named outputs rather than a single value. The input type must be stated,\n * either as the type argument or via `.input<t>()` on the freshly opened\n * chain. An unannotated `chain()` takes a branded type that nothing satisfies,\n * so the omission fails at the first field read or the `run` call site, with\n * the fix spelled out in the message, instead of accepting anything. `.step(name, fn)`\n * runs `fn` over the record and merges its output back in under `name`;\n * `.stage(name, project?)` concludes a phase: it opens a grouping span in\n * the trajectory and, when `project` is given, replaces the record with the\n * projection so earlier bindings go out of scope; `.output(fn)` closes the\n * builder and returns an ordinary `Step<i, o>`.\n *\n * Each `.step` entry is a regular `step(name, fn)` whose input happens to be\n * the record, so anything true of steps (spans, error paths, abort checks\n * between entries) is true of chain entries, and the binding name doubles as\n * the entry's id in trajectories. A binding whose whole job is to invoke an\n * arm is `.step(name, arm, select)`: the chain projects the record through\n * `select`, dispatches the arm via `ctx.call`, and records it as the\n * binding's child, so what `describe` renders and what runs cannot diverge.\n * The escape hatch for bodies that need code around the call is\n * `.step(name, fn, { arm })`: the body does its own `ctx.call` and the arm\n * is metadata only, recorded for `describe` but never dispatched.\n *\n * Builder values are immutable: every method returns a new chain, so a\n * prefix can be shared and extended in different directions safely.\n */\n\nimport { is_step } from './is_step.js'\nimport { dispatch_step, register_traced_kind, throw_if_aborted } from './runner.js'\nimport { step } from './step.js'\nimport { assert_valid_step_id } from './step_id.js'\nimport type { AnyStep, RunContext, Step } from './types.js'\n\nlet chain_counter = 0\n\n/**\n * Generate a unique step id of the form `chain_<n>`.\n */\nfunction next_chain_id(): string {\n chain_counter += 1\n return `chain_${chain_counter}`\n}\n\ntype merge<a, b> = { readonly [k in keyof (a & b)]: (a & b)[k] }\n\nexport type ChainStepOptions = {\n readonly arm?: AnyStep | ReadonlyArray<AnyStep>\n /**\n * Display label for the binding's span and `describe` line. The binding\n * name is a record key and so must be identifier-shaped; this is where the\n * free prose goes, exactly as `meta.name` does for a plain `step`.\n */\n readonly name?: string\n /** What the binding is for, carried to `describe` as `meta.description`. */\n readonly description?: string\n}\n\n// The input type of a chain that wasn't told what it takes. No value is\n// assignable to it by accident, and an error that meets it prints the fix,\n// where `never` printed nothing to act on. `chain` names the instantiation\n// itself rather than through an alias, because the compiler prints an alias\n// by its name and would leave the fix out.\ninterface ChainInputUndeclared<fix extends string> {\n readonly chain_input_undeclared: fix\n}\n\nexport type Chain<i, acc> = {\n readonly step: {\n <k extends string, o>(\n name: k,\n fn: (s: acc, ctx: RunContext) => Promise<o> | o,\n options?: ChainStepOptions,\n ): Chain<i, merge<acc, { readonly [p in k]: o }>>\n <k extends string, a, o>(\n name: k,\n arm: Step<a, o>,\n select: (s: acc) => a,\n options?: ChainStepOptions,\n ): Chain<i, merge<acc, { readonly [p in k]: o }>>\n }\n readonly stage: {\n (name: string): Chain<i, acc>\n <next extends Record<string, unknown>>(\n name: string,\n project: (s: acc, ctx: RunContext) => Promise<next> | next,\n ): Chain<i, merge<next, unknown>>\n }\n readonly output: <o>(fn: (s: acc, ctx: RunContext) => Promise<o> | o) => Step<i, o>\n}\n\n/**\n * A freshly opened chain: `Chain` plus `.input<t>()`, which restates the\n * input type once with the binding name already fixed, so\n * `chain('q').input<Request>()` equals `chain<Request, 'q'>('q')`. The first\n * `.step` or `.stage` returns plain `Chain`, so refinement is only possible\n * before any entry is recorded.\n */\nexport type ChainOpen<i, k extends string, acc> = Chain<i, acc> & {\n readonly input: <t>() => Chain<t, { readonly [p in k]: t }>\n}\n\ntype LooseFn = (s: Record<string, unknown>, ctx: RunContext) => unknown\n\ntype LooseSelect = (s: Record<string, unknown>) => unknown\n\ntype ChainEntry =\n | { readonly kind: 'step'; readonly name: string; readonly node: Step<Record<string, unknown>, unknown> }\n | { readonly kind: 'stage'; readonly name: string; readonly project?: LooseFn }\n\ntype LooseChain = {\n readonly step: (\n name: string,\n fn_or_arm: LooseFn | AnyStep,\n options_or_select?: ChainStepOptions | LooseSelect,\n options?: ChainStepOptions,\n ) => LooseChain\n readonly stage: (name: string, project?: LooseFn) => LooseChain\n readonly output: (fn: LooseFn) => Step<unknown, unknown>\n}\n\n/**\n * Assemble the runnable chain Step from its entries and output node.\n *\n * Runs entries in order over a record seeded with the input under\n * `input_name`. Step entries merge their output under their name; stage\n * entries end the previous stage span, open a new one that subsequent\n * entries nest under, and, when projecting, replace the record. The output\n * node runs last and its value is the chain's output. `config.plan` lists\n * the entry names in order so `describe` shows the topology without running.\n *\n * The `Step<unknown, unknown>` return is the concrete type, not an erased\n * top type: the run function genuinely accepts any input, seeding the record\n * with whatever arrives. The typed `chain` surface narrows it at the cast.\n */\nfunction build_chain(\n input_name: string,\n entries: ReadonlyArray<ChainEntry>,\n output_node: Step<Record<string, unknown>, unknown>,\n): Step<unknown, unknown> {\n const id = next_chain_id()\n const plan = [\n ...entries.map((e) => (e.kind === 'stage' ? `stage:${e.name}` : e.name)),\n 'output',\n ]\n const children = [\n ...entries.flatMap((e) => (e.kind === 'step' ? [e.node] : [])),\n output_node,\n ]\n\n const run_fn = async (input: unknown, ctx: RunContext): Promise<unknown> => {\n let record: Record<string, unknown> = { [input_name]: input }\n let current_ctx = ctx\n let stage_span: string | undefined\n let stage_id: string | undefined\n\n const end_stage = (error?: string): void => {\n if (stage_span === undefined) return\n const meta: Record<string, unknown> = { id: stage_id }\n if (error !== undefined) meta['error'] = error\n ctx.trajectory.end_span(stage_span, meta)\n stage_span = undefined\n }\n\n try {\n for (const entry of entries) {\n throw_if_aborted(current_ctx)\n if (entry.kind === 'stage') {\n end_stage()\n stage_id = `stage:${entry.name}`\n const meta: Record<string, unknown> = { id: stage_id }\n if (ctx.parent_span_id !== undefined) meta['parent_span_id'] = ctx.parent_span_id\n stage_span = ctx.trajectory.start_span(entry.name, meta)\n current_ctx = { ...ctx, parent_span_id: stage_span }\n if (entry.project !== undefined) {\n // The typed surface constrains projections to return a record; the\n // runtime trusts that the same way `use` trusts its callback.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n record = (await entry.project(record, current_ctx)) as Record<string, unknown>\n }\n } else {\n const value = await dispatch_step(entry.node, record, current_ctx)\n record = { ...record, [entry.name]: value }\n }\n }\n throw_if_aborted(current_ctx)\n const out = await dispatch_step(output_node, record, current_ctx)\n end_stage()\n return out\n } catch (err) {\n end_stage(err instanceof Error ? err.message : String(err))\n throw err\n }\n }\n\n return {\n id,\n kind: 'chain',\n children,\n config: { input: input_name, plan },\n run: run_fn,\n }\n}\n\n/**\n * Build the binding node for the arm-first `.step(name, arm, select)` form.\n *\n * The chain owns the dispatch: the synthesized body projects the record\n * through `select` and hands the result to the arm via `ctx.call`, and the\n * same arm is declared as the binding's arm, so the subtree `describe`\n * renders and the step that runs are one value by construction.\n */\nfunction arm_node(\n name: string,\n arm: AnyStep,\n select: ChainStepOptions | LooseSelect | undefined,\n options: ChainStepOptions | undefined,\n): Step<Record<string, unknown>, unknown> {\n if (typeof select !== 'function') {\n throw new TypeError('chain.step(name, arm, select): select must be a function')\n }\n return step(\n name,\n (s: Record<string, unknown>, ctx: RunContext) =>\n // The typed surface pairs select's projection with the arm's input, a\n // pairing the erased AnyStep cannot carry, so the call re-asserts it.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ctx.call(arm, select(s) as never),\n { ...options, arm },\n )\n}\n\n/**\n * Build the binding node for the body form `.step(name, fn, { arm? })`.\n *\n * A declared arm is describe metadata only: `step` records it as the\n * binding's child, and the body's own `ctx.call` is what runs it.\n */\nfunction body_node(\n name: string,\n fn: LooseFn,\n options: ChainStepOptions | LooseSelect | undefined,\n): Step<Record<string, unknown>, unknown> {\n return step(name, fn, typeof options === 'function' ? undefined : options)\n}\n\n/**\n * Internal untyped builder behind `chain`.\n *\n * `bound` holds the binding names of the current stage segment so duplicate\n * names fail at build time (the typed surface would silently intersect\n * them); a projecting stage resets it because the projection's keys are only\n * known to the type system.\n */\nfunction make_chain(\n input_name: string,\n entries: ReadonlyArray<ChainEntry>,\n bound: ReadonlySet<string>,\n): LooseChain {\n return {\n step: (name, fn_or_arm, options_or_select, arm_options) => {\n assert_valid_step_id(\n name,\n 'chain.step: binding name',\n 'put the label in the options object as { name }',\n )\n if (bound.has(name)) {\n throw new TypeError(\n `chain.step: binding '${name}' is already defined in this stage; names are single-assignment`,\n )\n }\n const node = is_step(fn_or_arm)\n ? arm_node(name, fn_or_arm, options_or_select, arm_options)\n : body_node(name, fn_or_arm, options_or_select)\n return make_chain(\n input_name,\n [...entries, { kind: 'step', name, node }],\n new Set([...bound, name]),\n )\n },\n stage: (name, project) =>\n make_chain(\n input_name,\n [\n ...entries,\n project === undefined ? { kind: 'stage', name } : { kind: 'stage', name, project },\n ],\n project === undefined ? bound : new Set(),\n ),\n output: (fn) => build_chain(input_name, entries, step('output', fn)),\n }\n}\n\n/**\n * Open a chain builder whose record starts as `{ [input_name]: input }`.\n *\n * `input_name` defaults to `'input'`. The input type defaults to a branded\n * `ChainInputUndeclared` that no real input satisfies at `run`, and whose\n * name in an error says what to do; state it as the type argument or, when the\n * binding is renamed, once via `.input<t>()` on the fresh builder. Each\n * `.step` narrows subsequent callbacks to the record accumulated so far, and\n * `.stage` with a projection re-types the record to the projection's\n * return, so binding names and views are checked at compile time with no\n * declared state shape.\n */\nexport function chain<\n i = ChainInputUndeclared<'call .input<T>() on the chain to say what it takes'>,\n k extends string = 'input',\n>(\n input_name?: k,\n): ChainOpen<i, k, { readonly [p in k]: i }> {\n const name = input_name ?? 'input'\n assert_valid_step_id(name, 'chain: input name', 'rename the binding')\n const open = make_chain(name, [], new Set([name]))\n // `.input` is compile-time refinement over the same empty builder, so\n // returning it unchanged is the whole implementation.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return { ...open, input: () => open } as unknown as ChainOpen<i, k, { readonly [p in k]: i }>\n}\n\nregister_traced_kind('chain')\n"],"mappings":";;;AAYA,MAAM,qBAAqB;;;;;;;;;AAe3B,SAAgB,wBAAwB,YAA+C;CACrF,MAAM,WAAwB,CAAC;CAC/B,IAAI,MAAM;CAEV,SAAS,SAAS,IAAqB;EACrC,IAAI,KAAK;GACP,WAAW,OAAO,EAChB,MAAM,iCACR,CAAC;GACD;EACF;EACA,SAAS,KAAK,EAAE;CAClB;CAEA,eAAe,UAAyB;EACtC,IAAI,KAAK;EACT,MAAM;EACN,KAAK,IAAI,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,KAAK,GAAG;GAChD,MAAM,KAAK,SAAS;GACpB,IAAI,CAAC,IAAI;GACT,MAAM,QAAQ,IAAI,UAAU;EAC9B;CACF;CAEA,OAAO;EAAE;EAAU;CAAQ;AAC7B;;;;;;;;;;AAWA,eAAe,QAAQ,IAAe,YAA6C;CACjF,IAAI,aAAmD;CACvD,IAAI;EACF,MAAM,IAAI,SAAe,YAAY;GACnC,aAAa,iBAAiB;IAC5B,WAAW,OAAO;KAAE,MAAM;KAAmB,YAAY;IAAmB,CAAC;IAC7E,QAAQ;GACV,GAAG,kBAAkB;GAErB,QAAQ,QAAQ,CAAC,CACd,WAAW,GAAG,CAAC,CAAC,CAChB,WACO;IACJ,IAAI,YAAY,aA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