@agentproto/workflow-runtime 0.14.0 → 0.16.0
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/README.md +32 -0
- package/dist/index.d.ts +14 -2
- package/dist/index.mjs +125 -27
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/build-agent-step.ts","../src/validate-input.ts","../src/compile-workflow.ts","../src/ref-string.ts","../src/types.ts","../src/node-fs-port.ts","../src/knowledge.ts","../src/run-workflow.ts","../src/load-workflow.ts"],"names":["f","join","mkdir","writeFile","isAbsolute","stat","dirname","b","resolve","readFile","basename","out"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCO,SAAS,cAAA,CAAe,IAAY,MAAA,EAAoC;AAC7E,EAAA,MAAM,SAAS,MAAA,CAAO,MAAA;AACtB,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,OAAA;AAAA,IACN,EAAA;AAAA,IACA,GAAI,OAAO,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,EAAS,MAAA,CAAO,OAAA,EAAQ,GAAI,EAAC;AAAA,IAClE,GAAI,OAAO,GAAA,KAAQ,MAAA,GAAY,EAAE,GAAA,EAAK,MAAA,CAAO,GAAA,EAAI,GAAI,EAAC;AAAA,IACtD,GAAI,OAAO,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,MAAA,CAAO,KAAA,EAAM,GAAI,EAAC;AAAA,IAC5D,GAAI,OAAO,UAAA,KAAe,MAAA,GAAY,EAAE,UAAA,EAAY,MAAA,CAAO,UAAA,EAAW,GAAI,EAAC;AAAA,IAC3E,GAAI,OAAO,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,EAAS,MAAA,CAAO,OAAA,EAAQ,GAAI,EAAC;AAAA,IAClE,GAAI,MAAA,CAAO,SAAA,GAAY,EAAE,SAAA,EAAW,IAAA,KAAS,E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AAA,EAAO;AAAA,IACjD,SAAS,IAAA,CAAK,OAAA;AAAA,IACd,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,iBAAiB,IAAA,CAAK,eAAA;AAAA,IACtB,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,KAAK,IAAA,CAAK,GAAA;AAAA,IACV,eAAe,IAAA,CAAK,aAAA;AAAA,IACpB,WAAW,IAAA,CAAK,SAAA;AAAA,IAChB,cAAc,IAAA,CAAK,YAAA;AAAA,IACnB,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,YAAY,IAAA,CAAK,UAAA;AAAA,IACjB,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,aAAa,IAAA,CAAK,WAAA;AAAA,IAClB,gBAAgB,IAAA,CAAK,cAAA;AAAA,IACrB,eAAe,IAAA,CAAK,aAAA;AAAA,IACpB,cAAc,IAAA,CAAK,YAAA;AAAA,IACnB,gBAAgB,IAAA,CAAK,cAAA;AAAA,IACrB,cAAc,IAAA,CAAK;AAAA,GACrB,EAAG,KAAK,eAAe,CAAA;AACzB;ACllDO,SAAS,uBAAA,CACd,QACA,IAAA,EACiB;AACjB,EAAA,MAAM,QAAA,GAAW,sBAAsB,MAAM,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,qBAAqB,QAAQ,CAAA;AAC5C,EAAA,OAAO,eAAA,CAAgB,QAAQ,IAAI,CAAA;AACrC","file":"index.mjs","sourcesContent":["/**\n * Shared `AgentStep` construction — the one place that applies AgentStep's\n * defaults (`policy` → `{ awaiting: \"fail\" }`, a literal `prompt` wrapped as\n * a `Selector`). Used by both `compileWorkflow`'s declarative `kind:\"agent\"`\n * step and `@agentproto/runtime`'s `translateStages` (the `workflow_start` /\n * `WorkflowRunner` path), so the two authoring surfaces stay byte-identical\n * instead of drifting apart.\n */\n\nimport type { AgentHarness, AgentSandboxRef, AgentStep, Bindings, Selector } from \"./types.js\"\n\nexport interface AgentStepFields {\n /** A literal prompt string, or a per-run selector (declarative manifest\n * steps resolve `$steps.*` refs into one before calling this). */\n prompt: string | Selector<string>\n adapter?: string\n /** See {@link AgentStep.cwd}. */\n cwd?: Selector<string>\n model?: Selector<string> | string\n sessionRef?: string\n sandbox?: AgentSandboxRef\n cacheable?: boolean\n policy?: AgentStep[\"policy\"]\n outputSchema?: AgentStep[\"outputSchema\"]\n maxRetries?: number\n options?: Record<string, boolean | number | string>\n harness?: AgentHarness\n agentTools?: readonly string[]\n}\n\n/** Build a runtime {@link AgentStep} from field values, applying the same\n * defaults everywhere: `policy` defaults to `{ awaiting: \"fail\" }`. */\nexport function buildAgentStep(id: string, fields: AgentStepFields): AgentStep {\n const prompt = fields.prompt\n return {\n kind: \"agent\",\n id,\n ...(fields.adapter !== undefined ? { adapter: fields.adapter } : {}),\n ...(fields.cwd !== undefined ? { cwd: fields.cwd } : {}),\n ...(fields.model !== undefined ? { model: fields.model } : {}),\n ...(fields.sessionRef !== undefined ? { sessionRef: fields.sessionRef } : {}),\n ...(fields.sandbox !== undefined ? { sandbox: fields.sandbox } : {}),\n ...(fields.cacheable ? { cacheable: true } : {}),\n ...(fields.options !== undefined ? { options: fields.options } : {}),\n prompt: typeof prompt === \"function\" ? prompt : ((_b: Bindings) => prompt),\n policy: fields.policy ?? { awaiting: \"fail\" as const },\n ...(fields.outputSchema !== undefined ? { outputSchema: fields.outputSchema } : {}),\n ...(fields.maxRetries !== undefined ? { maxRetries: fields.maxRetries } : {}),\n ...(fields.harness !== undefined ? { harness: fields.harness } : {}),\n ...(fields.agentTools !== undefined ? { agentTools: fields.agentTools } : {}),\n }\n}\n","/**\n * AIP-58 §3 Outcome rule — \"invalid or missing required input is checked\n * before any step runs\". AIP-16 declares a workflow's `inputs` block as\n * JSON Schema, but most existing WORKFLOW.md authors write a shorthand flat\n * map instead (`inputs: { url: { type, description, default } }` — see\n * `youtube-transcriber`'s `transcribe/WORKFLOW.md`). This module normalizes\n * that shorthand into real JSON Schema, then validates a run's input\n * against it with the same ajv machinery `@agentproto/tool` already uses for\n * TOOL contracts (`define-tool.ts`'s `validateJsonSchema`).\n */\n\nimport Ajv from \"ajv\"\nimport type { ErrorObject, ValidateFunction } from \"ajv\"\nimport addFormats from \"ajv-formats\"\n\n/** One shorthand-form input property, e.g. `{ type: \"string\", default: \"en\" }`. */\ninterface ShorthandInputSpec {\n type?: string\n description?: string\n default?: unknown\n /** Non-standard: shorthand-only marker promoted to the schema's top-level\n * `required[]` — see {@link normalizeWorkflowInputsSchema}. */\n required?: boolean\n [k: string]: unknown\n}\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v)\n\n/** True when `inputs` is already an AIP-16 canonical JSON Schema object\n * (`{ type: \"object\", properties: {...} }`) rather than the shorthand flat\n * map many existing manifests use. */\nfunction isJsonSchemaObject(inputs: Record<string, unknown>): boolean {\n return inputs[\"type\"] === \"object\" && isPlainObject(inputs[\"properties\"])\n}\n\n/**\n * Normalize a WORKFLOW.md `inputs` field to a JSON Schema object.\n *\n * Already-canonical JSON Schema (`{ type: \"object\", properties, required?\n * }`) passes through unchanged — its own `required[]`, if any, is honored\n * as-is (this is the shape AIP-58's V1 vector authors directly).\n *\n * The shorthand flat map (`{ <name>: { type, description?, default?,\n * required? } }`) is lifted: each key becomes a `properties` entry (minus\n * its shorthand-only `required` marker); a property gets added to the\n * schema's `required[]` ONLY when its shorthand spec sets `required: true`\n * AND declares no `default` — a `default` always makes a field optional to\n * omit, regardless of `required`. A shorthand property with no `required`\n * marker at all stays optional, so normalizing an existing manifest that\n * never used the marker (e.g. `youtube-transcriber`'s `transcribe/\n * WORKFLOW.md`) never newly fails validation for it.\n */\nexport function normalizeWorkflowInputsSchema(inputs: unknown): Record<string, unknown> {\n if (!isPlainObject(inputs)) return { type: \"object\", properties: {} }\n if (isJsonSchemaObject(inputs)) return inputs\n\n const properties: Record<string, unknown> = {}\n const required: string[] = []\n for (const [key, rawSpec] of Object.entries(inputs)) {\n const spec: ShorthandInputSpec = isPlainObject(rawSpec) ? rawSpec : {}\n const { required: isRequired, ...schemaFields } = spec\n properties[key] = schemaFields\n if (isRequired === true && spec[\"default\"] === undefined) required.push(key)\n }\n return {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n }\n}\n\n// Shared Ajv instance + per-schema validator cache — same pattern as\n// `@agentproto/tool`'s `define-tool.ts` (`_ajv` / `_validatorCache`), plus\n// `ajv-formats` so a manifest's `format: \"uri\"` (as AIP-58's V1 vector\n// declares) actually validates instead of Ajv's strict mode rejecting the\n// unrecognized format keyword outright.\nconst _ajv = addFormats(new Ajv({ allErrors: true }))\nconst _validatorCache = new WeakMap<object, ValidateFunction>()\n\nfunction compile(schema: Record<string, unknown>): ValidateFunction {\n let validate = _validatorCache.get(schema)\n if (!validate) {\n validate = _ajv.compile(schema)\n _validatorCache.set(schema, validate)\n }\n return validate\n}\n\nfunction fieldFor(err: ErrorObject): string {\n if (err.keyword === \"required\") {\n return String((err.params as { missingProperty?: string }).missingProperty ?? \"\")\n }\n return err.instancePath.replace(/^\\//, \"\") || \"(root)\"\n}\n\nexport type WorkflowInputValidation =\n | { valid: true; schema: Record<string, unknown> }\n | {\n valid: false\n schema: Record<string, unknown>\n /** AIP-58 §10 error code — this validator only ever produces one. */\n code: \"invalid-input\"\n /** Missing/invalid field names (deduped), for a caller that wants to\n * point at exactly what's wrong without re-parsing `message`. */\n fields: readonly string[]\n /** Human-readable message naming the missing/invalid fields. */\n message: string\n }\n\n/**\n * AIP-58 §9 `run.requestInput`/`run.resume`: `true` when `schema` is a\n * usable JSON Schema (ajv can compile it) — a plain object is necessary but\n * not sufficient (e.g. `{ type: \"not-a-type\" }` compiles-fails). Used to\n * reject a malformed `schema` argument before it's ever recorded as a\n * step's `StepRecord.suspend.schema`.\n */\nexport function isCompilableJsonSchema(schema: unknown): schema is Record<string, unknown> {\n if (!isPlainObject(schema)) return false\n try {\n compile(schema)\n return true\n } catch {\n return false\n }\n}\n\n/** One structural (zod-`ZodIssue`-shaped) validation failure — the common\n * currency between ajv's `ErrorObject[]` and zod's `ZodError.issues`, see\n * {@link OutputSchemaLikeIssue}. */\nexport interface SchemaValidationIssue {\n path: readonly (string | number)[]\n message: string\n}\n\nfunction toIssue(err: ErrorObject): SchemaValidationIssue {\n const path = err.instancePath.replace(/^\\//, \"\").split(\"/\").filter((seg) => seg.length > 0)\n if (err.keyword === \"required\") {\n const missing = (err.params as { missingProperty?: string }).missingProperty\n if (missing) path.push(missing)\n }\n return { path, message: err.message ?? \"invalid\" }\n}\n\n/**\n * Generic JSON Schema validation, used both by AIP-58 §3/§9 (validate a\n * `run.resume` payload against the suspended step's `StepRecord.suspend\n * .schema` BEFORE the resume transition happens — an invalid payload MUST\n * leave the run suspended, never transition it) and by `compileAgentStep`\n * (adapt a WORKFLOW.md-authored JSON Schema `outputSchema` into the\n * {@link OutputSchemaLike} shape `execAgentStep` consumes). `issues` mirrors\n * zod's `ZodError.issues` shape so both call sites format errors the same\n * way regardless of which schema language declared the contract.\n */\nexport function validateAgainstJsonSchema(\n schema: Record<string, unknown>,\n value: unknown,\n): { valid: true } | { valid: false; message: string; issues: readonly SchemaValidationIssue[] } {\n const validate = compile(schema)\n if (validate(value)) return { valid: true }\n const errors = validate.errors ?? []\n const issues = errors.map(toIssue)\n const detail = errors.map((e) => `${e.instancePath || \"/\"} ${e.message}`).join(\"; \")\n return { valid: false, message: `does not match schema: ${detail}`, issues }\n}\n\n/**\n * Validate a run's `input` against a WORKFLOW.md's declared `inputs`\n * (shorthand or canonical JSON Schema — see\n * {@link normalizeWorkflowInputsSchema}). The caller is responsible for\n * calling this BEFORE dispatching any step and BEFORE spawning any session\n * on an invalid result — this function only judges the input, it doesn't\n * gate execution itself.\n */\nexport function validateWorkflowInput(inputsField: unknown, input: unknown): WorkflowInputValidation {\n const schema = normalizeWorkflowInputsSchema(inputsField)\n const validate = compile(schema)\n if (validate(input ?? {})) return { valid: true, schema }\n\n const errors = validate.errors ?? []\n const fields = [...new Set(errors.map(fieldFor).filter((f) => f.length > 0))]\n const detail = errors.map((e) => `${e.instancePath || \"/\"} ${e.message}`).join(\"; \")\n return {\n valid: false,\n schema,\n code: \"invalid-input\",\n fields,\n message: `invalid input${fields.length > 0 ? ` (${fields.join(\", \")})` : \"\"}: ${detail}`,\n }\n}\n","/**\n * Compile a declarative AIP-15 `WorkflowHandle` into a runnable\n * {@link RuntimeWorkflow} for {@link runWorkflow}. This is the bridge that makes\n * an authored WORKFLOW.md actually execute.\n *\n * AIP-15 leaves the IO seam (`step.inputs`, `map.over`, `loop.while`) to a\n * meta-validator. This compiler pins a concrete, minimal **reference grammar**\n * for it — the convention a manifest author writes:\n *\n * - data refs: `$input` · `$input.a.b` · `$steps.<id>` · `$steps.<id>.a`\n * · `$item` · `$item.a` · `$index` (`$$` escapes a literal `$`)\n * - prompts: the above refs PLUS mustache-style `{{name}}` /\n * `{{a.b}}` interpolation, `{{#name}}…{{/name}}` conditional\n * and `{{^name}}…{{/name}}` inverted sections (see\n * {@link interpolateTemplate})\n * - `step.inputs`: a JSON object whose leaf strings may be refs (resolved\n * recursively); non-`$` strings are literals\n * - `map.over`: a ref to an array\n * - `loop.while` / approval prompt: `<ref> <op> <literal>` (`== != < <= > >=`)\n * or a bare ref (truthiness)\n *\n * Scope: the **linear / structured subset** of AIP-15 — steps run in document\n * order; `map`/`loop`/`parallel` nest their child step lists. Non-linear `next`\n * gotos are rejected with a clear diagnostic. `kind:\"branch\"` compiles in its\n * **forward-only** form: every `branches[].next`/`default`/`join` must name a\n * later sibling in the SAME step list (not backward, not into a nested map/\n * loop/parallel body). Arms are EXCLUSIVE by default — exactly one arm body\n * runs, then execution continues at the join (see `compileExclusiveBranch`);\n * `fallthrough: true` opts into the legacy \"target + everything after it\"\n * semantics (see `compileBranchChain`). Compiling a full goto graph\n * (backward jumps, cross-scope targets) is a separable follow-up; hand-author\n * a `loop` step for retry-style control flow instead.\n */\n\nimport type { WorkflowHandle } from \"@agentproto/workflow\"\nimport { assertKnownStepRefs } from \"@agentproto/workflow\"\nimport type { DriverHandle } from \"@agentproto/driver\"\nimport type { ToolHandle } from \"@agentproto/tool\"\nimport type { AgentRefResolution, AgentStep, Bindings, GateStep, OutputSchemaLike, RunStep, RuntimeWorkflow, Selector } from \"./types.js\"\nimport { buildAgentStep } from \"./build-agent-step.js\"\nimport { resolveRefString } from \"./ref-string.js\"\nimport { isCompilableJsonSchema, validateAgainstJsonSchema } from \"./validate-input.js\"\n\nexport interface CompileWorkflowOptions {\n /** TOOL contracts by id — each `tool` step resolves its handle here. */\n tools: ReadonlyMap<string, ToolHandle> | Record<string, ToolHandle>\n /** DRIVER candidates the resolver dispatches over for every tool step. */\n candidates: readonly DriverHandle[]\n /** Resolve a tool step's injected context (live capabilities) from bindings. */\n contextFor?: (toolId: string, bindings: Bindings) => unknown\n /** Sub-workflows by id, for `subworkflow` steps. */\n workflows?:\n | ReadonlyMap<string, WorkflowHandle>\n | Record<string, WorkflowHandle>\n /** App-scoped agent ids for a declarative `kind:\"agent\"` step's\n * `agent.ref` — e.g. `{ \"@app/reviewer\": { adapter: \"mastra-agent\",\n * options: { agent: \"<dir>/.agentproto/agents/reviewer/AGENT.md\" } } }`.\n * Built by the host from its own app-install state (see\n * `@agentproto/runtime`'s `resolveAgentRefsForWorkflow`). A step using\n * `agent.ref` with this unset, or naming a ref this map doesn't have,\n * fails compilation — never the runtime. */\n agentRefs?: ReadonlyMap<string, AgentRefResolution> | Record<string, AgentRefResolution>\n}\n\nexport class WorkflowCompileError extends Error {\n constructor(message: string) {\n super(`compileWorkflow: ${message}`)\n this.name = \"WorkflowCompileError\"\n }\n}\n\n// ── reference + predicate resolution (the AIP-16 IO seam) ────────────\n\nconst get = <T>(\n m: ReadonlyMap<string, T> | Record<string, T>,\n key: string,\n): T | undefined =>\n m instanceof Map ? m.get(key) : (m as Record<string, T>)[key]\n\nfunction dig(value: unknown, path: readonly string[]): unknown {\n let v = value\n for (const seg of path) {\n if (v == null) return undefined\n v = (v as Record<string, unknown>)[seg]\n }\n return v\n}\n\nconst REF_RE = /^\\$(input|item|steps|run)((?:\\.[^.]+)*)$/\n\n/**\n * The prefix form of the ref grammar: a ref token at the START of a string\n * that continues with a literal suffix (e.g. `$input.bookDir/knowledge` —\n * resolve `$input.bookDir`, append `/knowledge` verbatim). The token's path\n * segments stop at the first `.`, `$`, or `/` — so `$input.a$b/c` resolves\n * `$input.a` with rest `$b/c`. `$index` is recognized as a whole token too.\n */\nconst REF_PREFIX_RE = /^\\$(?:input|item|steps|run|index)((?:\\.[^.$/]+)*)/\n\n/** Resolve a single `$…` reference string against the run bindings. */\nexport function resolveRef(ref: string, b: Bindings): unknown {\n if (ref === \"$index\") return b.index\n const m = ref.match(REF_RE)\n if (!m) throw new WorkflowCompileError(`bad reference '${ref}'`)\n const segs = m[2] ? m[2].slice(1).split(\".\") : []\n switch (m[1]) {\n case \"input\":\n return dig(b.input, segs)\n case \"item\":\n return dig(b.item, segs)\n case \"steps\": {\n const [stepId, ...rest] = segs\n if (!stepId) throw new WorkflowCompileError(`'$steps' needs a step id`)\n return dig(b.steps[stepId], rest)\n }\n // AIP-58 §4 — `$run.workspace`, a convenience alias for the run\n // workspace path (see `Bindings.run`).\n case \"run\":\n return dig(b.run, segs)\n }\n}\n\n/** Resolve the leading ref token of a string (see {@link REF_PREFIX_RE}):\n * if `value` starts with a `$input`/`$item`/`$steps`/`$index` reference\n * token, resolve it against the bindings and return the resolved value plus\n * the literal remainder (`rest`). Throws exactly like {@link resolveRef} for\n * a matched-but-malformed token; returns `undefined` when the string does\n * not START with a ref token at all (caller decides pass-through vs error). */\nexport function resolveRefPrefixed(\n value: string,\n b: Bindings,\n): { resolved: unknown; rest: string } | undefined {\n const m = value.match(REF_PREFIX_RE)\n if (!m) return undefined\n const token = value.slice(0, m[0].length)\n return { resolved: resolveRef(token, b), rest: value.slice(m[0].length) }\n}\n\n// ── mustache-style prompt interpolation ──────────────────────────────\n\n/** A `{{…}}` tag name: dotted identifier path (`url`, `a.b.c`). */\nconst TAG_NAME = \"(?:[\\\\w$-]+)(?:\\\\.(?:[\\\\w$-]+))*\"\nconst TAG_RE = new RegExp(`\\\\{\\\\{(${TAG_NAME})\\\\}\\\\}`, \"g\")\n/** `{{#name}}inner{{/name}}` (conditional) or `{{^name}}inner{{/name}}` (inverted). */\nconst SECTION_RE = new RegExp(\n `\\\\{\\\\{([#^])(${TAG_NAME})\\\\}\\\\}([\\\\s\\\\S]*?)\\\\{\\\\{/\\\\2\\\\}\\\\}`,\n)\n\n/** Resolve a `{{…}}` tag name against the bindings — the same paths the\n * `$…` ref grammar reaches: `input.x`, `item.x`, `steps.<id>.x`, `index`,\n * and a bare name as shorthand for a top-level workflow input. */\nfunction resolveTagName(name: string, b: Bindings): unknown {\n const segs = name.split(\".\")\n const head = segs[0]!\n if (head === \"input\") return segs.length === 1 ? b.input : dig(b.input, segs.slice(1))\n if (head === \"item\") return segs.length === 1 ? b.item : dig(b.item, segs.slice(1))\n if (head === \"steps\" && segs.length > 1)\n return dig(b.steps[segs[1]!], segs.slice(2))\n if (head === \"index\" && segs.length === 1) return b.index\n if (head === \"run\") return segs.length === 1 ? b.run : dig(b.run, segs.slice(1))\n return dig(b.input, segs)\n}\n\n/** Stringify an interpolated value: strings verbatim, objects/arrays as\n * JSON, everything else (numbers, booleans) via `String()`, null as \"\" —\n * mustache convention. */\nfunction stringifyValue(v: unknown): string {\n if (v === null) return \"\"\n if (typeof v === \"string\") return v\n if (typeof v === \"object\") return JSON.stringify(v)\n return String(v)\n}\n\n/**\n * Interpolate mustache-style `{{…}}` templates against the run bindings.\n *\n * - `{{name}}` / `{{a.b}}` → the resolved value stringified; a MISSING\n * value leaves the placeholder as-is (never crashes, never renders\n * \"undefined\" into an agent prompt).\n * - `{{#name}}…{{/name}}` renders the inner text only when `name` is\n * truthy; `{{^name}}…{{/name}}` only when falsy. When a section tag\n * sits alone on its line (only whitespace around it), the whole line\n * collapses too — so a dropped section doesn't leave blank lines behind.\n * - Sections nest: inner text is interpolated recursively.\n */\nexport function interpolateTemplate(template: string, b: Bindings): string {\n let out = template\n for (;;) {\n const m = out.match(SECTION_RE)\n if (!m) break\n const kind = m[1]!\n const name = m[2]!\n const inner = m[3]!\n const value = resolveTagName(name, b)\n const truthy = kind === \"#\" ? Boolean(value) : !value\n const start = m.index!\n const end = start + m[0].length\n const before = out.slice(0, start)\n const after = out.slice(end)\n // Standalone-line detection: only whitespace between the tag and the\n // enclosing newlines on both sides.\n const lineStart = before.lastIndexOf(\"\\n\") + 1\n const nl = after.indexOf(\"\\n\")\n const standalone =\n before.slice(lineStart).trim() === \"\" &&\n (nl === -1 ? after : after.slice(0, nl)).trim() === \"\"\n let replacement: string\n if (!truthy) {\n replacement = \"\"\n } else {\n replacement = interpolateTemplate(inner, b)\n if (standalone) {\n // The newline that terminated the open-tag line and the whitespace +\n // newline that began the close-tag line belong to the tags, not the\n // rendered body.\n replacement = replacement.replace(/^\\n/, \"\").replace(/\\n[ \\t]*$/, \"\")\n }\n }\n // Only a standalone section swallows its own line's leading whitespace;\n // an inline one keeps everything before it on the line.\n out =\n (standalone ? before.slice(0, lineStart) : before) +\n replacement +\n (standalone\n ? (truthy ? (nl === -1 ? after : after.slice(nl)) : after.slice(nl + 1))\n : after)\n }\n return out.replace(TAG_RE, (whole, name: string) => {\n const v = resolveTagName(name, b)\n return v === undefined ? whole : stringifyValue(v)\n })\n}\n\n/**\n * Render an agent/approval step prompt for a run: `$…` refs first (a whole\n * string that starts with a ref token resolves exactly as before — a\n * ref-prefixed string resolves the token and interpolates the literal rest),\n * then mustache interpolation over the remainder / non-ref strings.\n */\nfunction renderPrompt(raw: string, b: Bindings): string {\n if (raw.startsWith(\"$$\")) return raw.slice(1)\n if (raw.startsWith(\"$\")) {\n const pref = resolveRefPrefixed(raw, b)\n if (pref) {\n const head =\n pref.rest === \"\" ? String(pref.resolved) : stringifyValue(pref.resolved)\n return head + interpolateTemplate(pref.rest, b)\n }\n }\n return interpolateTemplate(raw, b)\n}\n\n/** Recursively resolve a value node: refs in strings, into arrays/objects. */\nexport function resolveValue(node: unknown, b: Bindings): unknown {\n if (typeof node === \"string\") {\n if (node.startsWith(\"$$\")) return node.slice(1) // $$ → literal $\n if (node.startsWith(\"$\")) return resolveRef(node, b)\n return node\n }\n if (Array.isArray(node)) return node.map((n) => resolveValue(n, b))\n if (node && typeof node === \"object\") {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(node as Record<string, unknown>))\n out[k] = resolveValue(v, b)\n return out\n }\n return node\n}\n\n/** Like {@link resolveRef} but reports whether the referenced path actually\n * exists in the bindings — a strict subworkflow projection uses this to turn\n * a silently-`undefined` reference into a named error instead. */\nfunction refPathExists(ref: string, b: Bindings): boolean {\n const m = ref.match(REF_RE)\n if (!m) return false\n const segs = m[2] ? m[2].slice(1).split(\".\") : []\n let v: unknown\n if (m[1] === \"steps\") {\n const [stepId, ...rest] = segs\n if (!stepId || !(stepId in b.steps)) return false\n v = b.steps[stepId]\n segs.length = 0\n segs.push(...rest)\n } else {\n v = m[1] === \"input\" ? b.input : m[1] === \"run\" ? b.run : b.item\n }\n for (const seg of segs) {\n if (v === null || typeof v !== \"object\") return false\n const o = v as Record<string, unknown>\n if (!(seg in o)) return false\n v = o[seg]\n }\n return true\n}\n\n/** Strict variant of {@link resolveValue} for a subworkflow step's input\n * projection: an exact `$…` reference that resolves to `undefined` AND names\n * a path that doesn't exist in the bindings is a hard error naming the step\n * and key — never a silent `undefined` handed to the child. */\nexport function resolveValueStrict(node: unknown, b: Bindings, label: string): unknown {\n if (typeof node === \"string\") {\n if (node.startsWith(\"$$\")) return node.slice(1) // $$ → literal $\n if (node.startsWith(\"$\")) {\n const v = resolveRef(node, b)\n if (v === undefined && !refPathExists(node, b)) {\n throw new WorkflowCompileError(\n `${label}: reference '${node}' resolves to nothing — the referenced field does not exist`,\n )\n }\n return v\n }\n return node\n }\n if (Array.isArray(node)) return node.map((n) => resolveValueStrict(n, b, label))\n if (node && typeof node === \"object\") {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(node as Record<string, unknown>))\n out[k] = resolveValueStrict(v, b, label)\n return out\n }\n return node\n}\n\nconst COMPARATORS: Record<string, (a: number, b: number) => boolean> = {\n \"<\": (a, c) => a < c,\n \"<=\": (a, c) => a <= c,\n \">\": (a, c) => a > c,\n \">=\": (a, c) => a >= c,\n}\n\nfunction literal(token: string, b: Bindings): unknown {\n if (token.startsWith(\"$\")) return resolveRef(token, b)\n if (token === \"true\") return true\n if (token === \"false\") return false\n if (token === \"null\") return null\n if (/^-?\\d+(\\.\\d+)?$/.test(token)) return Number(token)\n return token.replace(/^['\"]|['\"]$/g, \"\")\n}\n\n/** Evaluate a `while`/`when` predicate string against the bindings. */\nexport function evalPredicate(expr: string, b: Bindings): boolean {\n const m = expr.match(/^(.+?)\\s*(==|!=|<=|>=|<|>)\\s*(.+)$/)\n if (!m) return Boolean(literal(expr.trim(), b)) // bare ref → truthiness\n const left = literal(m[1]!.trim(), b)\n const right = literal(m[3]!.trim(), b)\n switch (m[2]) {\n case \"==\":\n return left === right\n case \"!=\":\n return left !== right\n default: {\n const cmp = COMPARATORS[m[2]!]!\n return cmp(Number(left), Number(right))\n }\n }\n}\n\n// ── step compilation ─────────────────────────────────────────────────\n\n/** AIP step ids may be paths/refs; the runtime key is the last segment. */\nfunction normalizeToolId(ref: string): string {\n let s = ref.trim()\n if (s.endsWith(\"/TOOL.md\")) s = s.slice(0, -\"/TOOL.md\".length)\n const slash = s.lastIndexOf(\"/\")\n return slash === -1 ? s : s.slice(slash + 1)\n}\n\n// AIP step frontmatter leaves IO fields as opaque `{}`; read them dynamically.\nconst f = <T>(step: object, key: string): T =>\n (step as Record<string, unknown>)[key] as T\n\nfunction assertLinear(steps: readonly { id: string; kind: string; next?: string }[]): void {\n steps.forEach((s, i) => {\n const next = (s as { next?: string }).next\n const followingId = steps[i + 1]?.id\n if (next && next !== followingId) {\n throw new WorkflowCompileError(\n `step '${s.id}' has a non-linear next='${next}' — the structured-subset ` +\n `compiler only runs steps in document order. Hand-author a BranchStep ` +\n `or nest structurally.`,\n )\n }\n })\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction collectStepIds(steps: any[], ids: Set<string> = new Set()): Set<string> {\n for (const s of steps) {\n if (typeof s?.id === \"string\") ids.add(s.id)\n if (Array.isArray(s?.steps)) collectStepIds(s.steps, ids)\n if (Array.isArray(s?.branches)) {\n for (const br of s.branches) {\n if (Array.isArray(br?.steps)) collectStepIds(br.steps, ids)\n }\n }\n }\n return ids\n}\n\n/** Per-compile context: the public options plus the full set of step ids\n * declared anywhere in THIS workflow (recomputed fresh for each nested\n * `subworkflow` child, which has its own id namespace). */\ninterface Ctx {\n opts: CompileWorkflowOptions\n knownStepIds: ReadonlySet<string>\n}\n\nexport function compileWorkflow(\n handle: WorkflowHandle,\n opts: CompileWorkflowOptions,\n): RuntimeWorkflow {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const steps = handle.steps as unknown as any[]\n if (handle.start && handle.start !== steps[0]?.id) {\n throw new WorkflowCompileError(\n `start='${handle.start}' is not the first step — structured-subset runs in order`,\n )\n }\n const ctx: Ctx = { opts, knownStepIds: collectStepIds(steps) }\n // `result` is the optional output value-expression (AIP-15): map it through\n // the same ref grammar as a step's inputs. Absent ⇒ no output selector, so\n // runWorkflow falls back to the final step's result.\n const result = (handle as { result?: unknown }).result\n const output =\n result !== undefined ? (b: Bindings) => resolveValue(result, b) : undefined\n // `finally`: entry-authored cleanup steps that always run (see\n // `RuntimeWorkflow.finally`). They may read any main step's output.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const finallySteps = (handle as { finally?: any[] }).finally\n const finallyCtx: Ctx = finallySteps?.length\n ? { opts, knownStepIds: new Set([...ctx.knownStepIds, ...collectStepIds(finallySteps)]) }\n : ctx\n // AIP-58 §4 — `outputsFiles` (AIP-16, amended with `required`) survives\n // unchanged onto the compiled RuntimeWorkflow; `checkOutputsFiles`\n // (run-workflow.ts) reads it once every top-level step has finished.\n const outputsFiles = (\n handle as { outputsFiles?: Record<string, { path: string; required?: boolean; contentType?: string }> }\n ).outputsFiles\n return {\n id: handle.id,\n description: handle.description,\n steps: compileSiblingsToSteps(steps, ctx),\n ...(finallySteps?.length ? { finally: compileSiblingsToSteps(finallySteps, finallyCtx) } : {}),\n ...(output ? { output } : {}),\n ...(outputsFiles ? { outputsFiles } : {}),\n }\n}\n\n/**\n * Compile a sibling step list in document order. A `kind:\"branch\"` step\n * owns the siblings that form its arm bodies: an exclusive branch (the\n * default — see {@link compileExclusiveBranch}) compiles to one runtime node\n * and the walk resumes at its join point; a legacy `fallthrough: true`\n * branch swallows every sibling after it (see {@link compileBranchChain}),\n * so the walk stops there.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileSiblingsToSteps(steps: any[], ctx: Ctx): RunStep[] {\n assertLinear(steps)\n const out: RunStep[] = []\n for (let i = 0; i < steps.length; i++) {\n const s = steps[i]\n if (s.kind === \"branch\") {\n if (s.fallthrough === true) {\n out.push(compileBranchChain(steps, i, ctx))\n return out\n }\n const { node, joinIdx } = compileExclusiveBranch(steps, i, ctx)\n out.push(node)\n i = joinIdx - 1\n continue\n }\n out.push(compileStep(s, ctx))\n }\n return out\n}\n\nfunction compileStepList(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n steps: any[],\n id: string,\n ctx: Ctx,\n): RunStep {\n const compiled = compileSiblingsToSteps(steps, ctx)\n if (compiled.length === 1) return compiled[0]!\n return { kind: \"group\", id, steps: compiled }\n}\n\n/** Resolve a branch `next`/`default`/`join` id to its index in `steps`,\n * which MUST be a later sibling of the branch at index `i`. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction resolveBranchTarget(steps: any[], i: number, targetId: string, label: string): number {\n const idx = steps.findIndex((s) => s.id === targetId)\n if (idx === -1 || idx <= i) {\n throw new WorkflowCompileError(\n `branch '${steps[i].id}' ${label} targets '${targetId}', which is not a sibling later in this ` +\n `step list — the forward-only branch compiler only supports jumping to a later sibling in the ` +\n `SAME list (not backward, and not into a nested map/loop/parallel body). Hand-author a 'loop' ` +\n `step for retry-style control flow instead.`,\n )\n }\n return idx\n}\n\n/**\n * Compile an exclusive `kind:\"branch\"` step (index `i` in `steps`) — the\n * default branch semantics. Every arm target (`branches[].next`, `default`)\n * MUST be a later sibling in this SAME list. Sorted by position, the targets\n * partition the siblings after the branch into arm BODIES:\n *\n * - an arm's body is its target sibling up to (not including) the next\n * arm's target — or, for the last arm, up to the JOIN;\n * - the join is the explicit `join:` sibling id if declared, else the\n * sibling right after the last arm's target (so without `join:` the\n * last arm's body is exactly its target step);\n * - with no `default`, a no-match runs the siblings between the branch\n * and the first arm target (the implicit default body — empty when the\n * first target is the very next sibling). An explicit `default` makes\n * those siblings unreachable, which fails compilation.\n *\n * Exactly one arm body runs (first truthy `when`, else the default body);\n * the caller resumes the walk at the join, so every sibling from the join on\n * runs once, whichever arm was taken. Arms sharing a target share a body.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileExclusiveBranch(steps: any[], i: number, ctx: Ctx): { node: RunStep; joinIdx: number } {\n const branchStep = steps[i]\n const branches = f<{ when: string; next: string }[]>(branchStep, \"branches\")\n const defaultTarget = f<string | undefined>(branchStep, \"default\")\n const joinTarget = f<string | undefined>(branchStep, \"join\")\n\n const armIdx = branches.map((br, k) => resolveBranchTarget(steps, i, br.next, `branches[${k}].next`))\n const defaultIdx =\n defaultTarget !== undefined ? resolveBranchTarget(steps, i, defaultTarget, \"default\") : undefined\n const starts = [...new Set([...armIdx, ...(defaultIdx !== undefined ? [defaultIdx] : [])])].sort(\n (a, b) => a - b,\n )\n const lastStart = starts[starts.length - 1]!\n const joinIdx =\n joinTarget !== undefined ? resolveBranchTarget(steps, i, joinTarget, \"join\") : lastStart + 1\n if (joinIdx <= lastStart) {\n throw new WorkflowCompileError(\n `branch '${branchStep.id}' join '${joinTarget}' must come after every arm target — ` +\n `'${steps[lastStart].id}' is an arm target at or after it`,\n )\n }\n if (defaultIdx !== undefined && starts[0]! > i + 1) {\n throw new WorkflowCompileError(\n `branch '${branchStep.id}': step '${steps[i + 1].id}' sits between the branch and its first arm ` +\n `target and belongs to no arm — with an explicit 'default' it can never run. Move it after the ` +\n `join, or make it an arm target.`,\n )\n }\n\n // One compiled body per distinct start index, so arms sharing a target\n // share the exact same RunStep objects.\n const bodies = new Map<number, RunStep[]>()\n const bodyAt = (start: number): RunStep[] => {\n let body = bodies.get(start)\n if (!body) {\n const pos = starts.indexOf(start)\n const end = pos + 1 < starts.length ? starts[pos + 1]! : joinIdx\n body = compileSiblingsToSteps(steps.slice(start, end), ctx)\n bodies.set(start, body)\n }\n return body\n }\n\n let otherwise: RunStep[] =\n defaultIdx !== undefined\n ? bodyAt(defaultIdx)\n : compileSiblingsToSteps(steps.slice(i + 1, starts[0]), ctx)\n for (let k = branches.length - 1; k >= 0; k--) {\n const condExpr = branches[k]!.when\n otherwise = [\n {\n kind: \"branch\",\n id: k === 0 ? branchStep.id : `${branchStep.id}__branch${k}`,\n ...(k === 0 ? {} : { sourceId: branchStep.id }),\n cond: (b: Bindings) => evalPredicate(condExpr, b),\n then: bodyAt(armIdx[k]!),\n ...(otherwise.length > 0 ? { otherwise } : {}),\n },\n ]\n }\n return { node: otherwise[0]!, joinIdx }\n}\n\n/**\n * Compile a legacy `fallthrough: true` `kind:\"branch\"` step (index `i` in\n * `steps`) into a nested runtime {@link BranchStep} chain: `branches[]`\n * evaluate in order, the first truthy `when` jumps to its `next` sibling and\n * falls through in document order from there (running every later arm's\n * steps too); no match jumps to `default` (or falls through to `i + 1`).\n * Every target MUST be a later sibling in this SAME list.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileBranchChain(steps: any[], i: number, ctx: Ctx): RunStep {\n const branchStep = steps[i]\n const branches = f<{ when: string; next: string }[]>(branchStep, \"branches\")\n const defaultTarget = f<string | undefined>(branchStep, \"default\")\n if (f<string | undefined>(branchStep, \"join\") !== undefined) {\n throw new WorkflowCompileError(\n `branch '${branchStep.id}' declares both 'fallthrough: true' and 'join' — a fall-through ` +\n `branch runs every later sibling, so it has no join point`,\n )\n }\n const resolveTarget = (targetId: string, label: string): number =>\n resolveBranchTarget(steps, i, targetId, label)\n\n const defaultIdx = defaultTarget !== undefined ? resolveTarget(defaultTarget, \"default\") : i + 1\n let otherwise: RunStep[] = compileSiblingsToSteps(steps.slice(defaultIdx), ctx)\n\n for (let k = branches.length - 1; k >= 0; k--) {\n const br = branches[k]!\n const targetIdx = resolveTarget(br.next, `branches[${k}].next`)\n const thenSteps = compileSiblingsToSteps(steps.slice(targetIdx), ctx)\n const condExpr = br.when\n const nodeId = k === 0 ? branchStep.id : `${branchStep.id}__branch${k}`\n otherwise = [\n {\n kind: \"branch\",\n id: nodeId,\n ...(k === 0 ? {} : { sourceId: branchStep.id }),\n cond: (b: Bindings) => evalPredicate(condExpr, b),\n then: thenSteps,\n ...(otherwise.length > 0 ? { otherwise } : {}),\n },\n ]\n }\n return otherwise[0]!\n}\n\n/** `true` when `value` already satisfies {@link OutputSchemaLike} — e.g. a\n * zod `ZodType` a TS-authored step (`buildAgentStep` callers, `entry.mjs`)\n * passed directly. A function-valued `safeParse` member is sufficient,\n * since that's the only member `execAgentStep` ever calls. */\nfunction hasSafeParse(value: unknown): value is OutputSchemaLike {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === \"function\"\n )\n}\n\n/**\n * Adapt a WORKFLOW.md-authored `outputSchema` — plain JSON Schema, the only\n * shape YAML frontmatter can express — into the {@link OutputSchemaLike}\n * `execAgentStep` calls `.safeParse` on, backed by the same ajv instance\n * `validate-input.ts` already uses for run-input validation. Without this\n * adapter, a manifest-declared `outputSchema` reaches `execAgentStep` as a\n * bare object with no `safeParse` method at all, and the AIP-58 §3\n * missing-output check throws instead of validating. An uncompilable\n * schema fails HERE, at compile time, never at the runtime spawn.\n */\nfunction compileOutputSchema(schema: unknown, stepId: string): OutputSchemaLike {\n if (!isCompilableJsonSchema(schema)) {\n throw new WorkflowCompileError(\n `agent step '${stepId}' has an invalid 'outputSchema' — not a compilable JSON Schema`,\n )\n }\n return {\n safeParse: (value: unknown) => {\n const result = validateAgainstJsonSchema(schema, value)\n return result.valid\n ? { success: true as const, data: value }\n : { success: false as const, error: { issues: result.issues } }\n },\n // F27: lets `describeOutputSchemaForPrompt` (run-workflow.ts) render the\n // EXACT WORKFLOW.md-authored schema into the agent's prompt.\n jsonSchema: schema,\n }\n}\n\n/**\n * Compile a declarative `kind:\"agent\"` manifest step — `{ agent: { ref },\n * prompt, adapter?, sessionRef?, sandbox?, cacheable?, policy?, outputSchema?,\n * maxRetries? }` — into a real {@link AgentStep}. `prompt` runs through the\n * same `$input`/`$steps.<id>` ref grammar as a `tool` step's `inputs`.\n * `agent.ref` resolves via `opts.agentRefs` — unresolvable (no map, or an id\n * the map doesn't have) fails HERE, at compile time, never at the runtime\n * spawn.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileAgentStep(step: any, id: string, ctx: Ctx): AgentStep {\n const opts = ctx.opts\n const prompt = f<string>(step, \"prompt\")\n if (typeof prompt !== \"string\" || prompt.length === 0) {\n throw new WorkflowCompileError(`agent step '${id}' needs a non-empty 'prompt'`)\n }\n\n let adapter: string | undefined = typeof step.adapter === \"string\" ? step.adapter : undefined\n let options: Record<string, boolean | number | string> | undefined =\n step.options !== undefined ? step.options : undefined\n let model: unknown = step.model\n let agentTools: readonly string[] | undefined\n\n const agentRef: unknown = step.agent?.ref\n if (agentRef !== undefined) {\n if (typeof agentRef !== \"string\" || agentRef.trim().length === 0) {\n throw new WorkflowCompileError(`agent step '${id}' has an empty 'agent.ref'`)\n }\n const resolved = opts.agentRefs ? get(opts.agentRefs, agentRef) : undefined\n if (!resolved) {\n const available = opts.agentRefs\n ? opts.agentRefs instanceof Map\n ? [...opts.agentRefs.keys()]\n : Object.keys(opts.agentRefs)\n : []\n throw new WorkflowCompileError(\n `agent step '${id}' references unknown agent ref '${agentRef}'` +\n (available.length > 0\n ? ` — available refs: ${available.join(\", \")}`\n : \" — no agent refs are configured for this compile (not running in an app context?)\"),\n )\n }\n // An explicit step-level declaration is the author's override; the\n // agent-ref resolution only supplies the DEFAULT.\n if (adapter === undefined) adapter = resolved.adapter\n if (model === undefined) model = resolved.model\n // `resolved.options` is shaped for `resolved.adapter` specifically (e.g.\n // mastra-agent's `agent` option) — only apply it when the step ends up\n // spawning THAT adapter. A step-level `adapter:` override to a\n // DIFFERENT adapter must not inherit an option id the new adapter's own\n // manifest never declared (the spawn rejects it loudly — see F26's\n // `resolveAgentRefsForWorkflow` doc).\n if (options === undefined && adapter === resolved.adapter) options = resolved.options\n // The agent's declared tools travel with it whatever adapter runs it —\n // they scope the host's tool gateway, not an adapter option.\n agentTools = resolved.tools\n }\n\n // AIP-58 §3 Outcome rule: a step declaring NEITHER an output schema NOR a\n // required artifact (artifacts are P4, not checked here) has a vacuous\n // contract — its turn ending is unconditional success, and this runtime\n // can never detect a missing output for it. Warn once per step at compile\n // time (never at runtime, and never a thrown error — existing manifests\n // that never declared one keep working exactly as before).\n let outputSchema: OutputSchemaLike | undefined\n if (step.outputSchema === undefined) {\n console.warn(\n `[workflow-runtime] agent step '${id}' declares no output contract; AIP-58 cannot detect a missing output`,\n )\n } else if (hasSafeParse(step.outputSchema)) {\n // A TS-authored step (or an `entry.mjs` handle) passed a zod schema (or\n // anything else already `safeParse`-shaped) directly — use it as-is.\n outputSchema = step.outputSchema\n } else {\n // WORKFLOW.md YAML frontmatter can only express plain JSON Schema —\n // adapt it so `execAgentStep`'s `.safeParse` call works the same way\n // it does for a TS-authored zod schema.\n outputSchema = compileOutputSchema(step.outputSchema, id)\n }\n\n // `cwd`: a selector function (entry handles) passes through; a string\n // resolves through the same `$input`/`$steps.<id>` ref grammar as a gate\n // step's cwd (a literal path passes through unchanged).\n const rawCwd: unknown = step.cwd\n const cwd: Selector<string> | undefined =\n typeof rawCwd === \"function\"\n ? (rawCwd as Selector<string>)\n : typeof rawCwd === \"string\"\n ? (b: Bindings) => resolveRefString(id, \"cwd\", rawCwd, b, \"error\")\n : undefined\n\n return buildAgentStep(id, {\n prompt: (b: Bindings) => renderPrompt(prompt, b),\n ...(adapter !== undefined ? { adapter } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n ...(step.sessionRef !== undefined ? { sessionRef: step.sessionRef } : {}),\n ...(model !== undefined ? { model: model as Selector<string> | string } : {}),\n ...(step.sandbox !== undefined ? { sandbox: step.sandbox } : {}),\n ...(step.cacheable ? { cacheable: true } : {}),\n ...(options !== undefined ? { options } : {}),\n policy: step.policy,\n ...(outputSchema !== undefined ? { outputSchema } : {}),\n ...(step.maxRetries !== undefined ? { maxRetries: step.maxRetries } : {}),\n ...(step.harness !== undefined ? { harness: step.harness } : {}),\n ...(agentTools !== undefined ? { agentTools } : {}),\n })\n}\n\n/**\n * Compile a declarative `kind:\"gate\"` manifest step — `{ command, args?,\n * cwd?, report?, timeout_ms?, retry?, on_fail? }` — into a real\n * {@link GateStep}. `command` is re-validated here (compile time) even\n * though `@agentproto/workflow`'s `defineWorkflow` already rejects an\n * empty one at LOAD time — an ENTRY-based handle that hand-builds a gate\n * step in TS bypasses that manifest-only check.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileGateStep(step: any, id: string): GateStep {\n const command = f<string>(step, \"command\")\n if (typeof command !== \"string\" || command.trim().length === 0) {\n throw new WorkflowCompileError(`gate step '${id}' needs a non-empty 'command'`)\n }\n const args = f<string[] | undefined>(step, \"args\")\n const cwd = f<string | undefined>(step, \"cwd\")\n const reportPath = f<string | undefined>(step, \"report\")\n const timeoutMs = f<number | undefined>(step, \"timeout_ms\")\n const retry = f<\n { max_attempts: number; backoff: \"fixed\" | \"exponential\"; initial_ms?: number } | undefined\n >(step, \"retry\")\n const onFail = f<{ reprompt: string; with?: Record<string, unknown> } | undefined>(\n step,\n \"on_fail\",\n )\n return {\n kind: \"gate\",\n id,\n command,\n ...(args !== undefined ? { args } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n ...(reportPath !== undefined ? { reportPath } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n ...(retry !== undefined\n ? {\n retry: {\n maxAttempts: retry.max_attempts,\n backoff: retry.backoff,\n ...(retry.initial_ms !== undefined ? { initialMs: retry.initial_ms } : {}),\n },\n }\n : {}),\n ...(onFail !== undefined\n ? { onFail: { reprompt: onFail.reprompt, ...(onFail.with !== undefined ? { with: onFail.with } : {}) } }\n : {}),\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileStep(step: any, ctx: Ctx): RunStep {\n const opts = ctx.opts\n const id: string = step.id\n switch (step.kind) {\n case \"tool\": {\n const ref = typeof step.tool === \"string\" ? step.tool : step.tool.entry\n const toolId = normalizeToolId(ref)\n const tool = get(opts.tools, toolId)\n if (!tool)\n throw new WorkflowCompileError(`no tool registered for '${toolId}'`)\n const inputs = f<unknown>(step, \"inputs\") ?? {}\n assertKnownStepRefs(inputs, ctx.knownStepIds, `tool step '${id}' inputs`, {\n makeError: (message) => new WorkflowCompileError(message),\n })\n return {\n kind: \"tool\",\n id,\n tool,\n candidates: opts.candidates,\n input: (b) => resolveValue(inputs, b),\n context: opts.contextFor\n ? (b) => opts.contextFor!(toolId, b)\n : undefined,\n ...(step.cacheable ? { cacheable: true } : {}),\n }\n }\n\n case \"map\": {\n const over = f<string>(step, \"over\")\n const inner = compileStepList(f(step, \"steps\"), `${id}__body`, ctx)\n const onError = f<\"throw\" | \"collect\" | undefined>(step, \"onError\")\n const maxConsecutiveSpawnFailures = f<number | undefined>(step, \"maxConsecutiveSpawnFailures\")\n return {\n kind: \"map\",\n id,\n parallelism: f<number | undefined>(step, \"parallelism\"),\n over: (b) => resolveRef(over, b) as readonly unknown[],\n body: () => inner,\n ...(onError !== undefined ? { onError } : {}),\n ...(maxConsecutiveSpawnFailures !== undefined ? { maxConsecutiveSpawnFailures } : {}),\n }\n }\n\n case \"loop\": {\n const whileExpr = f<string>(step, \"while\")\n return {\n kind: \"loop\",\n id,\n maxIterations: f<number>(step, \"max_iterations\"),\n while: (b) => evalPredicate(whileExpr, b),\n body: [compileStepList(f(step, \"steps\"), `${id}__body`, ctx)],\n }\n }\n\n case \"parallel\": {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const branches = f<any[]>(step, \"branches\")\n return {\n kind: \"parallel\",\n id,\n branches: branches.map((br) => ({\n id: br.id,\n steps: [compileStepList(br.steps, `${id}__${br.id}`, ctx)],\n })),\n }\n }\n\n case \"approval\": {\n const prompt = f<string>(step, \"prompt\")\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const approvers = (f<any[]>(step, \"approvers\") ?? []).map(\n (a) => a.role ?? a.userId ?? String(a),\n )\n const artifacts = f<string[]>(step, \"artifacts\")\n const timeoutMs = f<number>(step, \"timeout_ms\")\n return {\n kind: \"approval\",\n id,\n approvers,\n ...(artifacts !== undefined ? { artifacts } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n prompt: (b) => renderPrompt(prompt, b),\n }\n }\n\n case \"suspend\": {\n const resume = f<{ on: string[]; timeout_ms?: number }>(step, \"resume\")\n return { kind: \"suspend\", id, on: resume.on, timeoutMs: resume.timeout_ms }\n }\n\n case \"subworkflow\": {\n const wfId = f<string>(step, \"workflow\")\n const child = opts.workflows ? get(opts.workflows, wfId) : undefined\n if (!child)\n throw new WorkflowCompileError(\n `subworkflow '${wfId}' not found — pass it in opts.workflows`,\n )\n const compiledChild = compileWorkflow(child, opts)\n // `inputs` is an optional projection into the child's `$input` — the\n // same ref grammar as a `tool` step's `inputs` (refs resolved against\n // THIS (parent) workflow's bindings). Absent ⇒ today's behavior: the\n // child runs with the parent's own workflow input, unchanged.\n const inputs = f<unknown>(step, \"inputs\")\n if (inputs === undefined) {\n return { kind: \"subworkflow\", id, workflow: compiledChild }\n }\n assertKnownStepRefs(inputs, ctx.knownStepIds, `subworkflow step '${id}' inputs`, {\n makeError: (message) => new WorkflowCompileError(message),\n })\n const entries = Object.entries(inputs as Record<string, unknown>)\n return {\n kind: \"subworkflow\",\n id,\n workflow: compiledChild,\n // Each top-level key resolves strictly: a missing referenced field\n // throws at run time naming this step + key (no silent `undefined`).\n input: (b) => {\n const out: Record<string, unknown> = {}\n for (const [k, v] of entries)\n out[k] = resolveValueStrict(v, b, `subworkflow step '${id}' input key '${k}'`)\n return out\n },\n }\n }\n\n case \"agent\": {\n // Two shapes reach here under the same `kind:\"agent\"`: an ENTRY-based\n // handle's already-built runtime AgentStep (function-valued `prompt`\n // selector — nothing declarative left to resolve, pass through\n // unchanged), or a purely-declarative manifest step (`prompt` is a\n // plain string) that this compiler must turn into a real AgentStep,\n // the same way `translateStages` does for `workflow_start`.\n if (typeof step.prompt === \"function\") {\n const passthrough: RunStep = step\n return passthrough\n }\n return compileAgentStep(step, id, ctx)\n }\n\n case \"gate\":\n return compileGateStep(step, id)\n\n case \"artifact\": {\n // Entry-based handles may pass an already-built ArtifactStep straight\n // through (function-valued key/path); a declarative WORKFLOW.md step\n // gives plain strings — `path` resolves through the same `$…`\n // ref-string grammar a gate step's `cwd` uses (a literal path passes\n // through unchanged).\n if (typeof step.key === \"function\" || typeof step.path === \"function\") {\n const passthrough: RunStep = step\n return passthrough\n }\n const key = f<string>(step, \"key\")\n const rawPath = f<string>(step, \"path\")\n if (typeof key !== \"string\" || key.trim().length === 0) {\n throw new WorkflowCompileError(`artifact step '${id}' needs a non-empty 'key'`)\n }\n if (typeof rawPath !== \"string\" || rawPath.trim().length === 0) {\n throw new WorkflowCompileError(`artifact step '${id}' needs a non-empty 'path'`)\n }\n const contentType = f<string | undefined>(step, \"contentType\")\n return {\n kind: \"artifact\",\n id,\n key,\n path: (b: Bindings) => resolveRefString(id, \"path\", rawPath, b, \"error\"),\n ...(contentType !== undefined ? { contentType } : {}),\n }\n }\n\n case \"transform\": {\n // Not a declarative manifest kind — no string expression language for\n // `compute` — so it only reaches the compiler from an ENTRY-based\n // handle, already built as a runtime TransformStep (function-valued\n // `compute`). Passes through unchanged: this is what lets an entry.mjs\n // step shape/serialize an earlier tool step's output (e.g.\n // `JSON.stringify` a prior `$steps.<id>` value) for a later tool step\n // to consume as a plain string input, something the `$steps.*` ref\n // grammar alone can't do. `step` is `any`, so no cast is needed.\n const passthrough: RunStep = step\n return passthrough\n }\n\n case \"branch\":\n // Unreachable through the normal entry points: `compileSiblingsToSteps`\n // intercepts every `branch` step (a branch owns its arm-body siblings,\n // so it can only be compiled with the whole sibling list in view). A\n // direct call would be an internal invariant violation, not a\n // manifest problem.\n throw new WorkflowCompileError(\n `internal: branch step '${id}' reached compileStep directly — branch ` +\n `steps must be compiled via the sibling-list walker`,\n )\n\n default:\n throw new WorkflowCompileError(\n `unsupported step kind '${step.kind}' (step '${id}')`,\n )\n }\n}\n","/**\n * The shared string-ref resolver (AIP-16 ref grammar): ONE implementation for\n * every field that accepts \"a string that may START with a `$…` run-time\n * reference plus trailing literal text\" — `harness.knowledge[]` selector\n * strings, a `kind:\"gate\"` step's `args[]`, and its `cwd`.\n */\n\nimport { resolveRefPrefixed } from \"./compile-workflow.js\"\nimport type { Bindings } from \"./types.js\"\n\n/**\n * Resolve one string against the run bindings. Rule: refs are only\n * recognized at the START of the string. The leading reference token — the\n * shared AIP-16 prefix grammar in {@link resolveRefPrefixed} (it stops at\n * the first `/`, e.g. `$input.bookDir` in `$input.bookDir/knowledge`) — is\n * resolved against the bindings and `String()`-ed; the remainder of the\n * string is appended verbatim. A string that is exactly a ref resolves to\n * that value's string form. `$$` escapes to a literal `$`. A string without\n * a leading ref passes through untouched — unless `onUnmatched` is\n * `\"error\"` and the string starts with a `$` that does not open a known ref\n * token, in which case it throws (the gate `args`/`cwd` behavior: a literal\n * `$foo` handed to a subprocess is always a footgun, never intended). An\n * unresolvable or malformed ref throws naming the step and `field`\n * (e.g. `harness.knowledge[0].workspace`, `args[2]`, `cwd`).\n */\nexport function resolveRefString(\n stepId: string,\n field: string,\n value: string,\n b: Bindings,\n onUnmatched: \"passthrough\" | \"error\" = \"passthrough\",\n): string {\n if (value.startsWith(\"$$\")) return value.slice(1)\n let hit: ReturnType<typeof resolveRefPrefixed>\n try {\n hit = resolveRefPrefixed(value, b)\n } catch (err) {\n throw new Error(\n `step '${stepId}': ${field} '${value}' is not a valid reference — ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n if (!hit) {\n if (onUnmatched === \"error\" && value.startsWith(\"$\")) {\n throw new Error(\n `step '${stepId}': ${field} '${value}' is not a valid reference — a leading '$' must open a $input/$item/$steps.<id>/$index reference ('$$' escapes a literal '$')`,\n )\n }\n return value\n }\n const token = value.slice(0, value.length - hit.rest.length)\n if (hit.resolved === undefined) {\n throw new Error(\n `step '${stepId}': ${field} '${token}' resolves to nothing — the referenced field does not exist`,\n )\n }\n return String(hit.resolved) + hit.rest\n}\n","/**\n * Typed step algebra for AIP-15 WORKFLOW execution.\n *\n * The AIP-15 manifest leaves the IO-threading (`step.inputs`, `map.over`,\n * `branch.when`, `loop.while`) to a meta-validator — it never pins an\n * expression language. Rather than invent a stringly DSL, this runtime\n * expresses the AIP-16 IO seam as **typed selectors**: each step reads the\n * run-scoped {@link Bindings} (workflow input + every prior step's output, plus\n * the current item inside a `map`) through a plain `(bindings) => value`\n * function. Authoring stays in TypeScript; compiling a declarative manifest's\n * reference strings onto these selectors is a separable follow-up.\n */\n\nimport type { DriverHandle, ResolverContext } from \"@agentproto/driver\"\nimport type { ToolContext, ToolHandle } from \"@agentproto/tool\"\n\n/** The run-scoped data every selector reads from. */\nexport interface Bindings {\n /** The workflow's invocation input. */\n readonly input: unknown\n /** Each completed top-level step's output, keyed by step id. */\n readonly steps: Readonly<Record<string, unknown>>\n /** Present inside a `map` body — the element being processed. */\n readonly item?: unknown\n /** Present inside a `map` body — the element's index. */\n readonly index?: number\n /** AIP-58 §4 Run workspace — present when the host wires\n * {@link RunWorkflowArgs.workspace}. `$run.workspace` / `{{run.workspace}}`\n * is a convenience alias for the same absolute path AIP-16 injects as\n * `$input._workflowFsRoot` — steps may use either. */\n readonly run?: { readonly workspace: string }\n}\n\n/** The AIP-16 IO seam: read a value out of the run bindings. */\nexport type Selector<T> = (bindings: Bindings) => T\n\n/** Run a TOOL contract through the resolver; its output binds under `id`. */\nexport interface ToolStep<\n TInput = unknown,\n TOutput = unknown,\n TContext extends ToolContext = ToolContext,\n> {\n kind: \"tool\"\n id: string\n tool: ToolHandle<TInput, TOutput, TContext>\n candidates: readonly DriverHandle[]\n /** Derive the tool input from the run bindings. */\n input: Selector<TInput>\n /** Derive the injected per-call context (live capabilities) from bindings. */\n context?: Selector<TContext>\n resolverContext?: ResolverContext\n secrets?: Record<string, string>\n /** Cache this step's output under the run's cacheKey; only its `input` is hashed\n * (not `context`/secrets). Default false. */\n cacheable?: boolean\n}\n\n/** A pure in-run computation (combine / filter / shape) — no tool dispatch. */\nexport interface TransformStep {\n kind: \"transform\"\n id: string\n compute: Selector<unknown>\n}\n\n/**\n * One item's outcome inside a `map`/`pipeline` run with `onError: \"collect\"`.\n * Mirrors `Promise.allSettled`'s fulfilled/rejected split so a caller can tell\n * a legitimate `undefined` body output apart from a failure at that index.\n */\nexport type FanOutOutcome<T = unknown> =\n | { readonly status: \"fulfilled\"; readonly index: number; readonly value: T }\n | {\n readonly status: \"rejected\"\n readonly index: number\n readonly item: unknown\n /** `err.message` if the throw was an `Error`, else `String(err)`. */\n readonly error: string\n }\n | {\n /** Never started: either the fan-out's spawn circuit breaker opened\n * first (see {@link MapStep.maxConsecutiveSpawnFailures}), or the run\n * was cancelled while earlier items were still in flight. */\n readonly status: \"skipped\"\n readonly index: number\n readonly item: unknown\n /** `circuit-open: <first error of the failure streak>`, or\n * `run-cancelled: run cancelled`. */\n readonly reason: string\n }\n\n/**\n * The bound output of a `map`/`pipeline` step run with `onError: \"collect\"`:\n * every item's outcome, plus the counts a caller needs to answer \"how many\n * failed and why\" without re-scanning `results`.\n */\nexport interface TolerantFanOutResult<T = unknown> {\n readonly results: readonly FanOutOutcome<T>[]\n readonly succeeded: number\n readonly failed: number\n /** Items never started because the spawn circuit breaker opened. */\n readonly skipped: number\n /** Set when the breaker opened: the first error of the spawn-failure\n * streak that tripped it. */\n readonly circuitOpen?: { readonly error: string }\n}\n\n/** Default for {@link MapStep.maxConsecutiveSpawnFailures} /\n * {@link PipelineStep.maxConsecutiveSpawnFailures}. */\nexport const DEFAULT_MAX_CONSECUTIVE_SPAWN_FAILURES = 3\n\n/**\n * Run a sub-step once per element of an array, optionally with bounded\n * concurrency. The element + index are exposed to the body via `bindings.item`\n * / `bindings.index`; the collected outputs bind under this step's id.\n */\nexport interface MapStep {\n kind: \"map\"\n id: string\n over: Selector<readonly unknown[]>\n /** Max concurrent bodies (default 1 = sequential). */\n parallelism?: number\n body: (item: unknown, index: number, bindings: Bindings) => RunStep\n /**\n * `\"throw\"` (default): the first item to throw aborts the whole map — the\n * step's output is a bare array, one entry per item, same as before this\n * field existed. `\"collect\"`: every item runs to completion; the step's\n * output becomes a {@link TolerantFanOutResult} instead of a bare array, so\n * a failure is visible to the caller rather than aborting or getting\n * silently dropped.\n */\n onError?: \"throw\" | \"collect\"\n /**\n * `\"collect\"` only: once this many items IN A ROW fail because an agent\n * step's session could not be spawned ({@link AgentSpawnError}), stop\n * starting new items — the failure is systemic, not per-item. In-flight\n * items finish; every item not yet started is reported skipped\n * (`circuit-open: <first error>`) and the map returns normally. A settled\n * item that isn't a spawn failure resets the streak. Default\n * {@link DEFAULT_MAX_CONSECUTIVE_SPAWN_FAILURES}; `0` disables the breaker.\n * (`\"throw\"` already stops at the first failure of any kind.)\n */\n maxConsecutiveSpawnFailures?: number\n}\n\n/**\n * Run N items through K sequential stage bodies with NO cross-item barrier:\n * each item flows through the stages as its own chain, independent of siblings.\n * Only `concurrency` (max item-chains in flight) is shared. The per-item final\n * output binds under this step's id, ordered by the item's index.\n */\nexport interface PipelineStep {\n kind: \"pipeline\"\n id: string\n over: Selector<readonly unknown[]>\n /** Max concurrent item-chains (default: all items at once). */\n concurrency?: number\n /** Ordered stage bodies; each item flows through them in order. `prevOutput`\n * is the previous stage's output for THIS item (undefined for stage 0). */\n stages: readonly ((\n item: unknown,\n index: number,\n prevOutput: unknown,\n bindings: Bindings,\n ) => RunStep)[]\n /** Same semantics as {@link MapStep.onError}: `\"throw\"` (default) aborts\n * the whole pipeline on the first item whose chain throws at any stage;\n * `\"collect\"` runs every item's chain to completion and binds a\n * {@link TolerantFanOutResult} instead of a bare array. */\n onError?: \"throw\" | \"collect\"\n /** Same semantics as {@link MapStep.maxConsecutiveSpawnFailures}. */\n maxConsecutiveSpawnFailures?: number\n}\n\n/** Run one of two branches based on a predicate over the bindings. */\nexport interface BranchStep {\n kind: \"branch\"\n id: string\n cond: Selector<boolean>\n then: readonly RunStep[]\n otherwise?: readonly RunStep[]\n /** The authored step this node was compiled from, when it differs from\n * `id` — a multi-arm manifest `kind: branch` compiles to a chain of\n * nodes (`<id>`, `<id>__branch1`, …); skip reports name `<id>`. */\n sourceId?: string\n}\n\n/** Repeat a body while a predicate holds, up to a hard iteration ceiling. */\nexport interface LoopStep {\n kind: \"loop\"\n id: string\n while: Selector<boolean>\n maxIterations: number\n body: readonly RunStep[]\n}\n\n/** Run several independent branches concurrently; outputs bind by branch id. */\nexport interface ParallelStep {\n kind: \"parallel\"\n id: string\n branches: readonly { id: string; steps: readonly RunStep[] }[]\n}\n\n/**\n * AIP-7 human-in-the-loop gate. The host's injected `approve` callback decides;\n * the chosen `onApprove` / `onReject` sub-steps then run. Default (no callback)\n * auto-approves. The step's own output is `{ approved }`.\n */\nexport interface ApprovalStep {\n kind: \"approval\"\n id: string\n prompt: Selector<string>\n approvers?: readonly string[]\n /** Artifacts attached to the approval request (e.g. paths to review). */\n artifacts?: readonly string[]\n /** Give up waiting after this long — the step resolves as REJECTED with\n * `who: \"timeout\"` (the host decides; the runtime enforces it). */\n timeoutMs?: number\n onApprove?: readonly RunStep[]\n onReject?: readonly RunStep[]\n}\n\n/**\n * Pause until an external event resumes the run. The host's injected `resume`\n * callback supplies the resume payload (bound under this step's id). With no\n * callback the run throws {@link WorkflowSuspendedError} — the durable-suspend\n * path a host persists and re-enters later.\n */\nexport interface SuspendStep {\n kind: \"suspend\"\n id: string\n on: readonly string[]\n timeoutMs?: number\n}\n\n/** Run an ordered list of steps as one unit; its output is the last step's. */\nexport interface GroupStep {\n kind: \"group\"\n id: string\n steps: readonly RunStep[]\n}\n\n/** Run a nested workflow with its own isolated bindings; its output binds here. */\nexport interface SubworkflowStep {\n kind: \"subworkflow\"\n id: string\n workflow: RuntimeWorkflow\n /** Input for the child (default: the parent's workflow input). */\n input?: Selector<unknown>\n}\n\n/**\n * Harness pinning for an {@link AgentStep}'s spawn (AIP-15 P2) — mirrors\n * `@agentproto/workflow`'s manifest `Harness` block, compiled onto the\n * runtime step. Precedence when a field is also set elsewhere: this block\n * (highest) > the resolved AGENT.md's own frontmatter > `app_run` caller\n * args > the adapter's own default (lowest).\n */\nexport interface AgentHarness {\n /** Model id override for this spawn. */\n model?: string\n /** Reasoning-effort override for this spawn (adapter-defined vocabulary). */\n effort?: string\n /** Spawn-time role — governs the child's tool-policy disposition. */\n role?: string\n /** Per-spawn tool allowlist. Applied where the resolved adapter supports a\n * generic per-spawn allowlist mechanism; where it doesn't, the host MUST\n * record `toolsApplied: false` on the step's output and emit a warning\n * rather than silently ignoring the field. */\n tools?: readonly string[]\n /** Skill ids auto-mounted into the spawn. */\n skills?: readonly string[]\n /** Working directory override for this step's spawn — takes precedence\n * over {@link AgentStep.cwd} and the run-level `ctx.cwd`. */\n cwd?: string\n /** sha256 (hex) of the `harness.promptFile` this step's prompt was read\n * from, computed by `@agentproto/workflow-loader` at load time. Absent\n * when the step's prompt was authored inline. */\n promptSha?: string\n /** AIP-10 corpus knowledge materialized into the step's cwd (under\n * `.knowledge/`) before the session runs. See\n * {@link HarnessKnowledgeSelector}. */\n knowledge?: readonly HarnessKnowledgeSelector[]\n}\n\n/**\n * One AIP-10 corpus workspace attachment on an {@link AgentStep}'s\n * `harness.knowledge[]` — mirrors `@agentproto/workflow`'s manifest\n * `KnowledgeSelector`, with the `workspace` path already resolved to an\n * absolute path by `@agentproto/workflow-loader` (or authored absolute).\n */\nexport interface HarnessKnowledgeSelector {\n /** Absolute path to an AIP-10 corpus workspace root. */\n workspace: string\n /** Tags with OR semantics (maps to `resolveKnowledge`'s `query.tags`). */\n anyOf?: readonly string[]\n /** Tags that must ALL be present (post-filter after `anyOf`). */\n allOf?: readonly string[]\n /** Refined-kind filter. */\n kinds?: readonly string[]\n /** Cap on materialized entries after slug-ascending sort. Default 50. */\n maxEntries?: number\n /** Materialization mode — v1 supports only `\"files\"`. */\n mode?: \"files\"\n /** Internal — set by `@agentproto/workflow-loader` when a selector string\n * carries `$…` run-time references that must be resolved against the run\n * bindings before materialization. Not user-authored; the loader rejects\n * an authored `deferred`, and resolution strips the flag. */\n deferred?: boolean\n}\n\n/** Per-selector materialization record on an agent step's run output. */\nexport interface KnowledgeAppliedRecord {\n /** The (absolute) corpus workspace root the selector resolved against. */\n workspace: string\n /** Entries matching the selector after allOf + kind filtering. */\n matched: number\n /** Entries actually written (≤ matched, after the `maxEntries` cap). */\n written: number\n}\n\n/**\n * Where an {@link AgentStep}'s session runs when not on the host: a sandbox\n * provider slug (e.g. `\"local\"`, `\"e2b\"`) or an inline AIP-36 SandboxSpec-like\n * object (`{ provider, config, env?, … }`). This runtime stays structural —\n * the injected {@link AgentSessionHost} interprets the value (the daemon host\n * forwards it to the same sandbox boot path `agent_start.sandbox` uses).\n */\nexport type AgentSandboxRef = string | { provider: string; [k: string]: unknown }\n\n/**\n * The minimal structural contract {@link AgentStep.outputSchema} must\n * satisfy — exactly the `safeParse` shape `execAgentStep` consumes (never\n * `.parse`, `._def`, or any other zod-specific member). A real zod\n * `ZodType` satisfies this automatically (structural typing — zod's own\n * `SafeParseReturnType` is a superset of this shape), so a TS-authored step\n * can still pass a zod schema directly. `compileAgentStep` additionally\n * builds one of these from a WORKFLOW.md-authored JSON Schema object (ajv\n * `validateAgainstJsonSchema`-backed) for the declarative manifest path,\n * where `outputSchema` is plain JSON Schema, not a zod instance.\n */\nexport interface OutputSchemaLike {\n safeParse(value: unknown):\n | { success: true; data: unknown }\n | { success: false; error: { issues: readonly { path: readonly PropertyKey[]; message: string }[] } }\n /** Set by `compileAgentStep`'s declarative (WORKFLOW.md) path to the raw\n * JSON Schema object it wrapped — lets F27's prompt-affordance render the\n * EXACT schema text instead of re-deriving it from the `safeParse`\n * closure. Absent on a TS-authored zod schema (rendered via\n * `z.toJSONSchema` instead — see `describeOutputSchemaForPrompt`). */\n jsonSchema?: unknown\n}\n\n/**\n * Spawn or reuse an agent session and send it a prompt, waiting for the\n * turn to complete. The host injects an {@link AgentSessionHost} — this\n * runtime has no knowledge of concrete session registries or event buses.\n */\nexport interface AgentStep {\n kind: \"agent\"\n id: string\n /** Adapter slug to spawn a NEW session. Omit to reuse via sessionRef. */\n adapter?: Selector<string> | string\n /** Reuse an earlier AgentStep's spawned session, by that step's id. Inside\n * a `map`/`pipeline` body, a `{{index}}` placeholder resolves to the\n * current item index — `\"review[{{index}}]\"` names the session THIS item's\n * `review` step spawned (the host indexes every fan-out spawn under its\n * `stepKey`, `<stepId>[<index>]`), where a bare `\"review\"` would resolve to\n * whichever item spawned last. */\n sessionRef?: string\n /** Model id override for this spawn — same semantics as `agent_start.model`\n * (a literal string or a per-run selector resolving to one; `undefined` ⇒\n * unchanged behaviour, the adapter keeps its default). Forwarded to the\n * spawn through the harness slot; an explicit `harness.model` pinning\n * (AIP-15 P2) still wins. Only meaningful with `adapter`; ignored on a\n * `sessionRef` reuse. */\n model?: Selector<string> | string\n /** Working directory for this spawn. Omit to fall back to the run-level `ctx.cwd`. */\n cwd?: Selector<string>\n /** Run this step's session inside a sandbox instead of on the host — a\n * provider slug or inline spec (see {@link AgentSandboxRef}), or a selector\n * resolving to one (`undefined` ⇒ host spawn, same as omitting the field).\n * Only meaningful when `adapter` is set (a `sessionRef` reuse inherits the\n * referenced session's placement). Hosts without sandbox support MUST fail\n * the spawn loudly rather than silently running on the host. */\n sandbox?: Selector<AgentSandboxRef | undefined> | AgentSandboxRef\n /** Prompt to send. */\n prompt: Selector<string>\n policy?:\n | { awaiting: \"auto-allow\"; prompt: string }\n | { awaiting: \"escalate\"; webhookUrl?: string; timeoutMs?: number }\n | { awaiting: \"fail\" }\n /** Validate the session's final message against this schema; re-prompt on\n * mismatch. A zod `ZodType` (TS-authored steps) or anything else\n * satisfying {@link OutputSchemaLike} (a WORKFLOW.md-authored JSON\n * Schema object compiles into one of these — see `compileAgentStep`). */\n outputSchema?: OutputSchemaLike\n /** Re-prompt-and-retry attempts on schema mismatch before failing. Default 2. */\n maxRetries?: number\n /** Cache this step's output under the run's cacheKey; the resolved prompt +\n * adapter + model + sessionRef are hashed. Default false — most agent steps have\n * side effects. */\n cacheable?: boolean\n /** Manifest-declared adapter option id → value, forwarded to a NEW spawn's\n * `startSession({ options })` — e.g. mastra-agent's `agent` option, set by\n * {@link CompileWorkflowOptions.agentRefs} resolution when this step's\n * declarative `agent.ref` names an app-scoped agent. Only meaningful with\n * `adapter`; ignored on a `sessionRef` reuse. */\n options?: Record<string, boolean | number | string>\n /** Harness pinning for this step's spawn. See {@link AgentHarness}. */\n harness?: AgentHarness\n /** The resolved agent manifest's declared `tools` (AGENT.md `tools:`), set\n * by {@link CompileWorkflowOptions.agentRefs} resolution. Forwarded to the\n * host's `spawn` so it can mount its own tool gateway scoped to this list\n * (names the gateway doesn't serve — harness-native tools — match\n * nothing). Unset ⇒ the agent declared no tools list. Only meaningful\n * with `adapter`; ignored on a `sessionRef` reuse. */\n agentTools?: readonly string[]\n}\n\n/**\n * AIP-58 §4 Run workspace — declare a file under the run workspace\n * (`$run.workspace` / `_workflowFsRoot`) as a run artifact: hashed, sized,\n * and copied into the host's `artifactsDir` (`<runsRoot>/<runId>/artifacts/`).\n * Bound output (and the value passed to {@link RunWorkflowArgs.onArtifact})\n * is the resulting {@link ArtifactEntry}.\n *\n * Cache-aware when the run has `cache`/`cacheKey` wired (independent of any\n * `cacheable` flag — there is none on this step; declaring the same key/path\n * again under the same cacheKey is always cheap to re-verify): a hit COPIES\n * the previously-cached file forward from its original `artifactsDir` into\n * THIS run's own — never shares a directory across runs (AIP-58 §4 \"two runs\n * MUST NEVER share a workspace\") — so a step declaring an artifact from a\n * cache-hit-replayed upstream step still works. See `run-workflow.ts`'s\n * `case \"artifact\"` for the exact mechanics.\n */\nexport interface ArtifactStep {\n kind: \"artifact\"\n id: string\n /** Artifact key — identifies this artifact for `workflow_artifact_get`/\n * `workflow_publish`. Its on-disk filename under `artifactsDir` is\n * `path`'s own basename (sanitized), not the key — see {@link\n * ArtifactEntry.path} — unless another key's file shares the same\n * basename, in which case the key disambiguates it (F42). */\n key: Selector<string> | string\n /** Path to the source file. Relative to `$run.workspace`; MUST resolve\n * inside it (an absolute path or a `..`-escaping relative one throws). */\n path: Selector<string> | string\n contentType?: Selector<string> | string\n}\n\n/**\n * AIP-58 §4/§1 `ArtifactEntry` — one run-scoped copy of a declared output\n * file. `path` is `\"artifacts/<basename>\"` (F42: the declared source file's\n * OWN basename, sanitized — e.g. `outputsFiles.pdf: {path: transcript.pdf}`\n * ⇒ `artifacts/transcript.pdf` — keeping the extension, unlike the bare key),\n * relative to the RUN WORKSPACE ROOT (`<runsRoot>/<runId>/`, the parent of\n * `$run.workspace` itself) — never the original in-workspace location the\n * file was read from. Two keys whose files share a basename get the SECOND\n * one's name prefixed with its own sanitized key instead (deterministic,\n * never a silent overwrite) — always read `path` back rather than assuming\n * `artifacts/<key>` or `artifacts/<basename(path)>`.\n */\nexport interface ArtifactEntry {\n key: string\n path: string\n sha256: string\n size: number\n stepId: string\n contentType?: string\n}\n\n/**\n * `kind: \"gate\"` — run a shell command through the host's subprocess runner\n * as a deterministic pass/fail check (AIP-15 P3 / AIP-17). Exit code 0 is a\n * pass; any other code is a failure. Bound output is `{ ok, exitCode, report\n * }`; `report` is the process' stdout (if it parses as JSON) or the file at\n * `reportPath` (relative to `cwd`), parsed as JSON.\n */\nexport interface GateStep {\n kind: \"gate\"\n id: string\n command: string\n /** Command arguments. Each element (selector or string) resolves per-run\n * against the bindings: a LEADING `$input|$item|$steps.<id>|$index` token\n * (AIP-16 prefix grammar) resolves and any trailing text is appended\n * verbatim (`\"$input.bookDir/knowledge\"` → `\"<resolved>/knowledge\"`); a\n * string that is exactly a ref resolves to that value's string form;\n * `$$…` stays a literal `$`; a ref that resolves to nothing (or a `$…`\n * string that opens no known ref token) throws naming the step and the\n * arg index. */\n args?: readonly (Selector<string> | string)[]\n /** Working directory. Selector form resolves per-run. A string may carry\n * the same leading-`$…` ref rule as `args` (leading token + trailing\n * text, `$$` escape, unresolvable ref throws). The RESOLVED cwd is made\n * absolute: absolute stays absolute; relative (incl. `.`) resolves\n * against the run's own `ctx.cwd` — never the daemon process cwd.\n * Omit for the run's `ctx.cwd`. */\n cwd?: Selector<string> | string\n /** Path (relative to `cwd`), of a JSON report file, consulted when stdout\n * doesn't itself parse as JSON. */\n reportPath?: string\n /** Hard wall-clock cap for a single command invocation, in ms. */\n timeoutMs?: number\n /** Re-run on a failing exit code, up to `maxAttempts` (default 1 = no\n * retry — a single attempt, fail immediately on a non-zero exit). */\n retry?: {\n maxAttempts: number\n backoff: \"fixed\" | \"exponential\"\n initialMs?: number\n }\n /** Re-prompt-and-rerun on a failing attempt, BEFORE each retry after the\n * first: send the named prior {@link AgentStep}'s session (resolved via\n * {@link AgentSessionHost.resolveByLabel}, the same lookup a `sessionRef`\n * reuse uses) a prompt with this gate's last report injected, wait for\n * its turn, then re-run the gate command. */\n onFail?: {\n reprompt: string\n with?: Record<string, unknown>\n }\n}\n\n/** One gate command invocation's raw result — before report resolution. */\nexport interface GateCommandResult {\n exitCode: number\n stdout: string\n stderr: string\n timedOut?: boolean\n}\n\n/** Host-injectable subprocess runner for {@link GateStep}. Undefined ⇒ the\n * runtime's own `node:child_process`-backed default. */\nexport type GateCommandRunner = (spec: {\n command: string\n args: readonly string[]\n cwd: string\n timeoutMs?: number\n /** The run's cancel signal — a cancelled run kills an in-flight gate\n * command's child process the same way it kills an agent step's session.\n * A host-injected runner should pass this through to its own subprocess\n * spawn (e.g. `child_process.execFile`'s `signal` option) so the process\n * is signalled, not merely orphaned. */\n signal?: AbortSignal\n}) => Promise<GateCommandResult>\n\n/** One `kind: \"gate\"` command attempt's outcome, reported as it happens\n * (every attempt, not just the last) — the `gate-report` lifecycle event. */\nexport interface GateReportEvent {\n stepId: string\n ok: boolean\n exitCode: number\n report: unknown\n attempt: number\n}\n\n/** What a declarative agent-step's `agent.ref` resolves to — the adapter to\n * spawn under plus any adapter options that pick which concrete agent runs\n * (e.g. mastra-agent's `agent` option, an emitted AGENT.md path). Built by\n * the host from its own app-install state; the compiler only consumes it. */\nexport interface AgentRefResolution {\n /** Adapter slug to spawn (e.g. \"mastra-agent\"). */\n adapter: string\n /** Adapter option id → value merged onto the compiled step's `options`. */\n options?: Record<string, boolean | number | string>\n /** AGENT.md's declared `model` — the compiled step's DEFAULT when the\n * step itself sets none (a step-level `model:` still wins). Forwarded\n * through the same `harness.model` channel a step-level `model` uses. */\n model?: string\n /** AGENT.md's declared `tools` (string ids only) — becomes the compiled\n * step's {@link AgentStep.agentTools}. */\n tools?: readonly string[]\n}\n\n/**\n * The element generics on `ToolStep` are erased to `any` so heterogeneous\n * steps (different contracts, different input/output/context types) coexist in\n * one `steps[]` array — per-step type safety is enforced where each step is\n * authored, not at the collection level. Same contravariant-function-position\n * constraint `@agentproto/driver`'s `implementations[]` works around (TS\n * issue #21534); tightening the union to `ToolStep<unknown, …>` rejects a\n * concrete `ToolStep<MarketSearchInput, …>` on the zod `ZodType<T>` variance.\n */\nexport type RunStep =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | ToolStep<any, any, any>\n | TransformStep\n | MapStep\n | PipelineStep\n | BranchStep\n | LoopStep\n | ParallelStep\n | ApprovalStep\n | SuspendStep\n | GroupStep\n | SubworkflowStep\n | AgentStep\n | GateStep\n | ArtifactStep\n\n/** One `outputsFiles.<key>` declaration carried onto a compiled\n * {@link RuntimeWorkflow} — the AIP-16 file contract, amended with\n * `required` (AIP-58 §4). `path` MAY use the `<runId>`/`<workflowId>`/\n * `<isoDate>` interpolation tokens AIP-16 names (`<toolId>` is not\n * resolvable at the workflow level and is left literal). */\nexport interface OutputsFileContract {\n path: string\n /** `true`: missing when the run's steps finish ⇒ `failed { code:\n * \"missing-artifact\" }` (AIP-58 §4/§10). Absent (the default) or `false`\n * ⇒ advisory only — a `console.warn`, the run still succeeds (mirrors\n * `StepRecord.hint`'s \"advisory, never load-bearing\" posture; matches the\n * AIP-58 V3 vector's own note: \"with required absent or false, the same\n * scenario would be a warning\"). */\n required?: boolean\n contentType?: string\n}\n\nexport interface RuntimeWorkflow {\n id: string\n description?: string\n steps: readonly RunStep[]\n /**\n * Cleanup steps that ALWAYS run once `steps` ends — succeeded, failed, or\n * cancelled (they run without the abort signal). They see the same\n * bindings (a step that never ran is simply absent). A failing `finally`\n * step fails an otherwise-successful run; after a failed or cancelled run\n * the original outcome wins and the cleanup error is only reported.\n */\n finally?: readonly RunStep[]\n /** Pick the run's final output (default: the last top-level step's output). */\n output?: Selector<unknown>\n /** AIP-16 `outputsFiles` (as amended by AIP-58 §4) — checked ONCE, after\n * every top-level step finishes successfully. See {@link OutputsFileContract}\n * and `run-workflow.ts`'s `checkOutputsFiles`. */\n outputsFiles?: Readonly<Record<string, OutputsFileContract>>\n}\n\n/** A human/host decision on one approval request. `who` records WHO decided\n * (\"human\", \"timeout\", \"cancelled\", …); `note` is optional free text. */\nexport interface ApprovalDecision {\n approved: boolean\n who: string\n note?: string\n}\n\nexport interface ApprovalRequest {\n stepId: string\n prompt: string\n approvers: readonly string[]\n artifacts?: readonly string[]\n /** The step's `timeoutMs` when set — the host may enforce it itself; the\n * runtime's default when the host doesn't is to wait forever. */\n timeoutMs?: number\n}\n\nexport interface ResumeRequest {\n stepId: string\n on: readonly string[]\n}\n\n/**\n * AIP-58 §3(a) explicit signal, recorded by the host when the step's own\n * session calls `run.requestInput` before its turn ends. Passed to\n * {@link RunWorkflowArgs.onInputRequired} to durably suspend the step.\n */\nexport interface InputRequiredRequest {\n stepId: string\n prompt: string\n schema?: Record<string, unknown>\n}\n\nexport interface AgentSessionHost {\n /** Spawn a new agent session and return its id. A `sandbox` ref asks the\n * host to run the session inside that sandbox (provider slug or inline\n * spec); hosts that can't MUST throw rather than silently spawn on the\n * host. */\n spawn(\n adapter: string,\n opts: {\n cwd?: string\n workspaceSlug?: string\n stepId?: string\n sandbox?: AgentSandboxRef\n /** Adapter option id → value for this spawn (see {@link AgentStep.options}). */\n options?: Record<string, boolean | number | string>\n /** Harness pinning for this spawn (see {@link AgentStep.harness}). */\n harness?: AgentHarness\n /** The agent manifest's declared tools (see {@link AgentStep.agentTools}). */\n agentTools?: readonly string[]\n /** Run-unique key of the spawning step when it runs inside a\n * `map`/`pipeline` item: `stepId[<index>]`, the same key the run's step\n * hooks report. Absent outside a fan-out (the key is then `stepId`). */\n stepKey?: string\n },\n ): Promise<string>\n /**\n * The run is done with a session it spawned: end it (if still live) and\n * archive it. Called once per spawned session — when its `map`/`pipeline`\n * item settles, else when the run itself ends (ok or error) — never\n * earlier, so a later step's `sessionRef` can still reuse it. The session's\n * id stays on the step's output. Best-effort: a throw is swallowed.\n */\n releaseSession?(sessionId: string): Promise<void>\n /** Send a prompt to an existing session and wait for its turn to end. */\n sendPromptAndWait(sessionId: string, prompt: string): Promise<void>\n /** Look up a session by the step id that spawned it (for sessionRef reuse). */\n resolveByLabel(stepId: string): string | undefined\n /** Handle an awaiting-input policy for a session. */\n onAwaitingInput?(sessionId: string, policy: AgentStep[\"policy\"]): Promise<void>\n /**\n * AIP-58 §3(a) explicit signal: consume (and clear) a pending\n * `run.requestInput` recorded for this session — checked by\n * {@link AgentStep} execution right after a turn ends, before the\n * outputSchema retry loop (and again inside it, after every reprompt).\n * `undefined` when no request is pending. Optional: a host that omits\n * this never suspends a step on this signal — the outcome rule's other\n * branches (missing-output / vacuous success) still apply.\n */\n takeInputRequest?(sessionId: string): { prompt: string; schema?: Record<string, unknown> } | undefined\n /** Return the session's final assistant message text (for outputSchema validation). */\n readFinalMessage?(sessionId: string): Promise<string>\n /** Current cumulative cost (USD) of a session, for run-level budgeting. */\n readCostUsd?(sessionId: string): Promise<number>\n /** Emit a harness-warning for a session — the pass-through channel behind\n * the AIP-15 \"never silently ignore\" `session:harness-warning` event (used\n * by the runtime for `harness.knowledge` empty matches, reason\n * `knowledge-empty`). Optional: hosts without an event bus omit it and\n * the runtime degrades to the run-record entry alone. */\n emitHarnessWarning?(input: {\n sessionId: string\n warnings: readonly string[]\n label?: string\n }): void\n}\n\n/** One journal entry: a cached step output plus the hash of the inputs that produced it. */\nexport interface StepCacheEntry {\n output: unknown\n resolvedInputHash: string\n /** Set only by a `kind: \"artifact\"` step (see {@link ArtifactStep}): the\n * absolute `artifactsDir` this entry's file was copied into when first\n * cached. A hit in a LATER run (a different `artifactsDir`, since AIP-58\n * §4 forbids two runs sharing a workspace) copies the file forward from\n * here into the new run's own `artifactsDir` instead of re-declaring it. */\n artifactsDirAtCache?: string\n /** Set only for a cacheable `tool`/`agent` step (see `hashResolvedInputs`/\n * `buildCacheEntry` in `run-workflow.ts`) whenever the host wires a run\n * workspace: the absolute `$run.workspace` / `_workflowFsRoot` path this\n * entry was cached under. A hit in a LATER run (a different workspace —\n * AIP-58 §4 forbids two runs sharing one) rewrites `output`'s path\n * strings from here onto the new run's own, and relocates\n * {@link workspaceFiles} the same way. */\n workspaceAtCache?: string\n /** Workspace-relative files/directories (under {@link workspaceAtCache})\n * this entry's `output` pointed at and that existed on disk when the\n * entry was written — copied forward into a later cache-hit run's own\n * workspace so a downstream step reading one of these paths finds the\n * bytes there too, not just in the original (by-then-gone) run's. */\n workspaceFiles?: readonly string[]\n}\n\n/** Opt-in journal for cacheable steps. Host-injected; file-backed in the runtime. */\nexport interface StepCache {\n /** Look up a step's journal entry by its namespaced key. */\n get(stepCacheKey: string): Promise<StepCacheEntry | undefined>\n /** Write/overwrite a step's journal entry. */\n set(stepCacheKey: string, entry: StepCacheEntry): Promise<void>\n}\n\n/** Extra context passed to `onStepStart`/`onStepComplete`. */\nexport interface StepHookInfo {\n /** The step's output was replayed from the {@link StepCache} journal —\n * it was not executed (no spawn, no tool dispatch) this run. */\n cached?: boolean\n}\n\n/** Why `onStepSkipped` fired. */\nexport interface StepSkippedInfo {\n /** `\"branch-not-taken\"`: the step sits in an untaken `branch` arm.\n * `\"circuit-open\"`: a `map`/`pipeline` item never started because the\n * fan-out's spawn circuit breaker opened\n * ({@link MapStep.maxConsecutiveSpawnFailures}). `\"run-cancelled\"`: a\n * `map`/`pipeline` item never started because the run was cancelled\n * (`RunWorkflowArgs.signal` aborted) while earlier items were still in\n * flight. */\n reason: \"branch-not-taken\" | \"circuit-open\" | \"run-cancelled\"\n /** Id of the authored step whose decision skipped the step — the `branch`\n * step, or (circuit-open/run-cancelled) the `map`/`pipeline` step. */\n branchId: string\n /** `\"circuit-open\"`: the first error of the spawn-failure streak that\n * tripped the breaker. `\"run-cancelled\"`: a fixed \"run cancelled\" message. */\n message?: string\n}\n\n/** What `onStepFailed` reports. */\nexport interface StepFailedInfo {\n /** `err.message` if the throw was an `Error`, else `String(err)`. */\n error: string\n}\n\nexport interface RunWorkflowArgs {\n workflow: RuntimeWorkflow\n input?: unknown\n signal?: AbortSignal\n /** Decide an {@link ApprovalStep}. Default: auto-approve. May return a bare\n * boolean (equivalent to `{approved, who: \"host\"}`) or a full\n * {@link ApprovalDecision} recording who decided. */\n approve?: (req: ApprovalRequest) => boolean | ApprovalDecision | Promise<boolean | ApprovalDecision>\n /** Supply a {@link SuspendStep}'s resume payload. Default: throw + suspend. */\n resume?: (req: ResumeRequest) => unknown | Promise<unknown>\n /**\n * AIP-58 §3(a)/§5 outcome rule: suspend an {@link AgentStep} that\n * signalled `run.requestInput` (see\n * {@link AgentSessionHost.takeInputRequest}), resolving with the resume\n * payload once an external event supplies one. The runtime sends that\n * payload (JSON) as the step's next prompt to the SAME session and\n * re-applies the outcome rule — the step may suspend again, fail\n * `missing-output`, or succeed. Default (undefined) ⇒\n * {@link AgentInputRequiredError} throws instead, the same\n * no-hook-supplied shape {@link WorkflowSuspendedError} uses for\n * {@link SuspendStep}.\n */\n onInputRequired?: (req: InputRequiredRequest) => unknown | Promise<unknown>\n /** Host-injected agent session runtime. Undefined ⇒ {@link AgentStep} throws. */\n agents?: AgentSessionHost\n /** Working directory for spawned agent sessions. */\n cwd?: string\n /** Workspace slug for spawned agent sessions. */\n workspaceSlug?: string\n /** AIP-58 §4 Run workspace — absolute path to this run's own scratch\n * directory (AIP-16's `_workflowFsRoot`), exposed to steps as\n * `$run.workspace` / `{{run.workspace}}`. Undefined ⇒ the `run` binding\n * and `kind: \"artifact\"` steps are unavailable. */\n workspace?: string\n /** AIP-58 §4 — absolute path to this run's `artifacts/` directory. Required\n * alongside `workspace` for a `kind: \"artifact\"` step (or a declared\n * `RuntimeWorkflow.outputsFiles`) to run. */\n artifactsDir?: string\n /** This run's id — used only to interpolate the `<runId>` token in a\n * declared `outputsFiles.<key>.path` (AIP-16). Purely informational\n * otherwise. */\n runId?: string\n /** Called once per {@link ArtifactEntry} recorded — by a `kind: \"artifact\"`\n * step, or by the end-of-run `outputsFiles` check — cache hit or fresh. */\n onArtifact?: (entry: ArtifactEntry) => void\n /** Run-level cost ceiling (USD). Once the summed cost of spawned sessions\n * reaches this, the next AgentStep spawn fails with `budget_exceeded`. */\n maxTotalCostUsd?: number\n /** Opt-in journal cache for cacheable steps. Undefined ⇒ caching disabled. */\n cache?: StepCache\n /** Namespacing label for this run's cache lookups (the workflow_start cacheKey).\n * Both `cache` and `cacheKey` must be set for any caching to happen. */\n cacheKey?: string\n /** Called when a step begins execution (before spawn/prompt). A cacheable\n * step replayed from the journal still fires this, with `info.cached`. */\n onStepStart?: (stepId: string, info?: StepHookInfo) => void\n /** Called when a step completes execution, with its output — `info.cached`\n * when the output was replayed from the journal instead of executed. */\n onStepComplete?: (stepId: string, output: unknown, info?: StepHookInfo) => void\n /** Called for every step in a `branch` arm that was NOT taken, once the\n * branch decides — the step will not run this time. Only statically-known\n * steps are reported (a `map`/`pipeline`/`subworkflow` step under the arm\n * reports its own id, not its body's); a step id that also sits in the\n * taken path is never reported. */\n onStepSkipped?: (stepId: string, info: StepSkippedInfo) => void\n /** Called when a step inside a tolerant (`onError: \"collect\"`) `map`/\n * `pipeline` item throws — the item is recorded as rejected and the run\n * goes on, so this is the only signal the failing step gets. `stepId` is\n * the innermost step that threw, indexed like `onStepStart`'s. A throw\n * that fails the run is NOT reported here (the run's own failure is). */\n onStepFailed?: (stepId: string, info: StepFailedInfo) => void\n /** Host-injectable subprocess runner for `kind: \"gate\"` steps. Undefined ⇒\n * the runtime's own `node:child_process`-backed default. */\n runGateCommand?: GateCommandRunner\n /** Called once per `kind: \"gate\"` command attempt (every attempt, not just\n * the last) — the `gate-report` lifecycle event. */\n onGateReport?: (ev: GateReportEvent) => void\n}\n\nexport interface WorkflowRunResult {\n output: unknown\n bindings: Bindings\n}\n","/**\n * NodeFsPort — a read-mostly `FsPort` over the host filesystem, rooted at an\n * AIP-10 corpus workspace. The local-FS twin of the adapter `corpus-cli`'s\n * knowledge preview uses, so `harness.knowledge` materialization resolves a\n * workspace with exactly the same port (and therefore the same hidden-segment\n * skipping and path confinement) the CLI does.\n */\n\nimport { mkdir, readFile, readdir, stat, writeFile, appendFile } from \"node:fs/promises\"\nimport type { Dirent } from \"node:fs\"\nimport { dirname, join } from \"node:path\"\nimport type { FsPort, FsLockHandle, FsStat } from \"@agentproto/corpus\"\n\nexport class NodeFsPort implements FsPort {\n private readonly root: string\n\n constructor(root: string) {\n this.root = root\n }\n\n private resolve(p: string): string {\n const normalized = p.replace(/^\\/+/, \"\")\n if (normalized.startsWith(\"..\")) {\n throw new Error(`NodeFsPort: path \"${p}\" escapes the workspace root \"${this.root}\"`)\n }\n return join(this.root, normalized)\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await stat(this.resolve(p))\n return true\n } catch {\n return false\n }\n }\n\n async readFile(p: string): Promise<string> {\n return readFile(this.resolve(p), \"utf8\")\n }\n\n async writeFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(dirname(target), { recursive: true })\n await writeFile(target, content, \"utf8\")\n }\n\n async appendFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(dirname(target), { recursive: true })\n await appendFile(target, content, \"utf8\")\n }\n\n async readdir(p: string): Promise<readonly string[]> {\n return readdir(this.resolve(p))\n }\n\n async walk(p: string): Promise<readonly string[]> {\n const out: string[] = []\n const visit = async (dir: string): Promise<void> => {\n let entries: Dirent[] = []\n try {\n entries = await readdir(dir, { withFileTypes: true })\n } catch {\n return\n }\n for (const ent of entries) {\n if (ent.name.startsWith(\".\")) continue\n const full = join(dir, ent.name)\n if (ent.isDirectory()) {\n await visit(full)\n } else if (ent.isFile()) {\n out.push(full)\n }\n }\n }\n await visit(this.resolve(p))\n const prefix = this.resolve(p)\n return out.map((f) => f.slice(prefix.length).replace(/^\\//, \"\"))\n }\n\n async stat(p: string): Promise<FsStat | null> {\n try {\n const s = await stat(this.resolve(p))\n return {\n kind: s.isDirectory() ? \"directory\" : \"file\",\n ...(s.isFile() ? { bytes: s.size } : {}),\n modifiedAt: s.mtime,\n }\n } catch {\n return null\n }\n }\n\n async lock(): Promise<FsLockHandle> {\n // Read-mostly port: knowledge materialization holds no cross-process\n // transactions, so the advisory lock is a no-op (the FsPort contract\n // explicitly allows a no-op for single-process topologies).\n return { release: async () => {} }\n }\n}\n","/**\n * `harness.knowledge` materialization (AIP-15 P2) — resolve each selector\n * against its AIP-10 corpus workspace with the same `resolveKnowledge` the\n * corpus CLI previews with, then write the matched raw entries (frontmatter +\n * body) into the step's cwd under `.knowledge/` BEFORE the step's session\n * runs. Idempotent: every run rewrites the same deterministic file set.\n */\n\nimport { mkdir, writeFile } from \"node:fs/promises\"\nimport { basename, isAbsolute, join } from \"node:path\"\n\nimport {\n filterEntriesByAllOf,\n isRefinedKind,\n resolveKnowledge,\n type RefinedKind,\n} from \"@agentproto/corpus\"\n\nimport { resolveRefString } from \"./ref-string.js\"\nimport type { Bindings } from \"./types.js\"\nimport type {\n HarnessKnowledgeSelector,\n KnowledgeAppliedRecord,\n} from \"./types.js\"\nimport { NodeFsPort } from \"./node-fs-port.js\"\n\nconst DEFAULT_MAX_ENTRIES = 50\n\nfunction resolveStringArray(\n stepId: string,\n index: number,\n field: string,\n values: readonly string[] | undefined,\n b: Bindings,\n): string[] | undefined {\n if (values === undefined) return undefined\n return values.map((v) =>\n resolveRefString(stepId, `harness.knowledge[${index}].${field}`, v, b),\n )\n}\n\n/**\n * Resolve every `$…`-bearing string of each `harness.knowledge[]` selector\n * (`workspace`, `anyOf[]`, `allOf[]`, `kinds[]`) against the run bindings,\n * producing selectors whose strings are run-resolved and stripped of the\n * loader's internal `deferred` flag. Selectors without refs pass through\n * unchanged (a copy). See {@link resolveRefString} for the ref rule.\n */\nexport function resolveKnowledgeSelectors(\n stepId: string,\n selectors: readonly HarnessKnowledgeSelector[],\n b: Bindings,\n): HarnessKnowledgeSelector[] {\n return selectors.map((sel, index) => {\n const deferred = sel.deferred === true\n const workspace = deferred\n ? resolveRefString(stepId, `harness.knowledge[${index}].workspace`, sel.workspace, b)\n : sel.workspace\n return {\n ...sel,\n deferred: undefined,\n workspace,\n ...(sel.anyOf !== undefined\n ? { anyOf: deferred ? resolveStringArray(stepId, index, \"anyOf\", sel.anyOf, b) : [...sel.anyOf] }\n : {}),\n ...(sel.allOf !== undefined\n ? { allOf: deferred ? resolveStringArray(stepId, index, \"allOf\", sel.allOf, b) : [...sel.allOf] }\n : {}),\n ...(sel.kinds !== undefined\n ? { kinds: deferred ? resolveStringArray(stepId, index, \"kinds\", sel.kinds, b) : [...sel.kinds] }\n : {}),\n }\n })\n}\n\n/** `../corpus-writer` → `corpus-writer`; `.` → the dir's own basename. */\nfunction workspaceDirName(workspace: string): string {\n const trimmed = workspace.replace(/\\/+$/, \"\")\n return basename(trimmed) || trimmed\n}\n\n/** Entries are written as `<slug>.md` — flatten anything path-like. */\nfunction safeSlug(slug: string): string {\n return slug.replace(/[^a-zA-Z0-9._-]+/g, \"-\")\n}\n\nexport interface MaterializedKnowledge {\n records: KnowledgeAppliedRecord[]\n /** Total entries written across all selectors — drives the prompt note. */\n written: number\n /** human-readable warnings for empty matches (`knowledge-empty`). */\n warnings: string[]\n}\n\n/**\n * Materialize every selector in `selectors` under `<stepCwd>/.knowledge/`.\n * Throws on a non-\"files\" `mode` or an unreadable workspace — the loader\n * rejects both earlier; this is the direct-TS-authoring path's backstop.\n */\nexport async function materializeKnowledge(\n stepId: string,\n selectors: readonly HarnessKnowledgeSelector[],\n stepCwd: string,\n): Promise<MaterializedKnowledge> {\n const knowledgeDir = join(stepCwd, \".knowledge\")\n const records: KnowledgeAppliedRecord[] = []\n const warnings: string[] = []\n const indexSections: string[] = []\n let written = 0\n\n for (const [i, sel] of selectors.entries()) {\n if (sel.mode !== undefined && sel.mode !== \"files\") {\n throw new Error(\n `step '${stepId}': harness.knowledge[${i}].mode must be \"files\" (v1 supports no other mode)`,\n )\n }\n const workspace = sel.workspace\n if (typeof workspace !== \"string\" || workspace.length === 0) {\n throw new Error(\n `step '${stepId}': harness.knowledge[${i}] needs a non-empty 'workspace'`,\n )\n }\n if (!isAbsolute(workspace)) {\n throw new Error(\n `step '${stepId}': harness.knowledge[${i}].workspace '${workspace}' must be absolute by run time — the loader resolves relative paths; did you bypass loadWorkflowHandle?`,\n )\n }\n\n const fs = new NodeFsPort(workspace)\n const rootStat = await fs.stat(\".\")\n if (rootStat === null || rootStat.kind !== \"directory\") {\n // A missing workspace after ref resolution is not a throw — the app's\n // gate decides (same seam as `knowledge-empty`); record the selector as\n // matching nothing and warn with the `knowledge-workspace-missing`\n // reason so hosts can distinguish it from an empty match.\n const warning = `knowledge-workspace-missing: harness.knowledge[${i}] (workspace '${workspace}') does not name an existing directory`\n warnings.push(warning)\n records.push({ workspace, matched: 0, written: 0 })\n continue\n }\n\n const kinds = (sel.kinds ?? []).filter((k): k is RefinedKind => isRefinedKind(k))\n const resolved = filterEntriesByAllOf(\n await resolveKnowledge({\n fs,\n query: {\n ...(sel.anyOf && sel.anyOf.length > 0 ? { tags: [...sel.anyOf] } : {}),\n ...(kinds.length > 0 ? { kinds } : {}),\n },\n }),\n sel.allOf,\n )\n\n // Deterministic order: slug ascending, then the cap.\n const sorted = [...resolved].sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0))\n const cap = sel.maxEntries ?? DEFAULT_MAX_ENTRIES\n const picked = sorted.slice(0, cap)\n\n const dirName = workspaceDirName(workspace)\n const lines: string[] = []\n for (const entry of picked) {\n const rel = join(dirName, `${safeSlug(entry.slug)}.md`)\n // Raw entry: frontmatter + body, exactly as it lives in the workspace.\n const raw = await fs.readFile(entry.path)\n await mkdir(join(knowledgeDir, dirName), { recursive: true })\n await writeFile(join(knowledgeDir, rel), raw, \"utf8\")\n lines.push(\n `- [${entry.title || entry.slug}](${rel.split(\"\\\\\").join(\"/\")}) — ${entry.kind}, ${entry.tags.join(\", \")}`,\n )\n }\n written += picked.length\n if (lines.length > 0) {\n indexSections.push(`## ${dirName}\\n\\n${lines.join(\"\\n\")}`)\n }\n\n records.push({ workspace, matched: resolved.length, written: picked.length })\n if (resolved.length === 0) {\n warnings.push(\n `knowledge-empty: harness.knowledge[${i}] (workspace '${workspace}') matched 0 entries`,\n )\n }\n }\n\n // Deterministic INDEX.md — selectors in declaration order, entries by slug.\n const index =\n \"# Knowledge index\\n\\n\" +\n (indexSections.length > 0 ? indexSections.join(\"\\n\\n\") : \"_No entries matched._\") +\n \"\\n\"\n await mkdir(knowledgeDir, { recursive: true })\n await writeFile(join(knowledgeDir, \"INDEX.md\"), index, \"utf8\")\n\n return { records, written, warnings }\n}\n","/**\n * The step-walker. Executes a {@link RuntimeWorkflow} top-to-bottom, threading\n * each step's output into a run-scoped binding bag, and dispatching `tool`\n * steps through `@agentproto/driver` `runTool` (resolve DRIVER → validate input\n * + context → execute body → validate output). Composite steps (`map` /\n * `branch` / `loop` / `parallel` / `approval` / `subworkflow`) recurse over the\n * same bindings; `suspend` defers to the host's resume hook.\n */\n\nimport { runTool } from \"@agentproto/driver\"\nimport { createHash } from \"node:crypto\"\nimport { execFile } from \"node:child_process\"\nimport { copyFile, cp, mkdir, readFile, stat, writeFile } from \"node:fs/promises\"\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\"\nimport { z } from \"zod\"\nimport { resolveRefString } from \"./ref-string.js\"\nimport type {\n AgentStep,\n ApprovalDecision,\n ArtifactEntry,\n ArtifactStep,\n Bindings,\n FanOutOutcome,\n GateCommandResult,\n GateStep,\n KnowledgeAppliedRecord,\n OutputSchemaLike,\n OutputsFileContract,\n RunStep,\n RunWorkflowArgs,\n RuntimeWorkflow,\n StepCacheEntry,\n StepFailedInfo,\n StepHookInfo,\n StepSkippedInfo,\n TolerantFanOutResult,\n WorkflowRunResult,\n} from \"./types.js\"\nimport { DEFAULT_MAX_CONSECUTIVE_SPAWN_FAILURES } from \"./types.js\"\nimport { materializeKnowledge, resolveKnowledgeSelectors } from \"./knowledge.js\"\n\n/** Thrown by a `suspend` step when no host `resume` hook is provided. */\nexport class WorkflowSuspendedError extends Error {\n constructor(\n readonly stepId: string,\n readonly on: readonly string[],\n ) {\n super(\n `workflow suspended at step '${stepId}' awaiting [${on.join(\", \")}] — ` +\n `no resume hook supplied`,\n )\n this.name = \"WorkflowSuspendedError\"\n }\n}\n\n/**\n * AIP-58 §3(a) — thrown when an {@link AgentStep}'s session signals\n * `run.requestInput` but no host `onInputRequired` hook is provided (the\n * same \"no resume hook supplied\" shape {@link WorkflowSuspendedError} uses\n * for {@link SuspendStep}). A host that wires `onInputRequired` never sees\n * this thrown — it durably suspends the step instead.\n */\nexport class AgentInputRequiredError extends Error {\n constructor(\n readonly stepId: string,\n readonly prompt: string,\n readonly schema?: Record<string, unknown>,\n ) {\n super(\n `step '${stepId}' requires input (\"${prompt}\") — no onInputRequired hook supplied`,\n )\n this.name = \"AgentInputRequiredError\"\n }\n}\n\n/**\n * AIP-58 §3 Outcome rule — thrown when an {@link AgentStep} declares an\n * `outputSchema` and its turn ends (after exhausting retries) without ever\n * producing output that validates against it, and no explicit\n * input-required signal (§3(a)/(b)) was observed either. `hint` is set when\n * the final message matches the \"trailing question mark\" heuristic — it is\n * ONLY a triage aid; it never changes the outcome (still `missing-output`).\n */\nexport class StepOutcomeError extends Error {\n constructor(\n readonly stepId: string,\n readonly code: \"missing-output\",\n message: string,\n readonly hint?: \"possible-input-request\",\n ) {\n super(message)\n this.name = \"StepOutcomeError\"\n }\n}\n\n/**\n * AIP-58 §4/§10 — thrown when a declared `outputsFiles.<key>` (`required`\n * absent or `true`) does not exist under the run workspace once every\n * top-level step has finished. `stepId` is the last top-level step that ran\n * (the manifest names no step for a workflow-level contract, so the last one\n * to finish is the best available attribution).\n */\nexport class MissingArtifactError extends Error {\n readonly code = \"missing-artifact\" as const\n constructor(\n readonly key: string,\n readonly stepId: string | undefined,\n ) {\n super(`outputsFiles.${key} was required but is missing from the run workspace`)\n this.name = \"MissingArtifactError\"\n }\n}\n\n/**\n * Thrown when an {@link AgentStep}'s session could not be spawned at all\n * (`AgentSessionHost.spawn` rejected) — distinct from a session that spawned\n * and then failed its turn. A tolerant fan-out counts these toward its spawn\n * circuit breaker ({@link MapStep.maxConsecutiveSpawnFailures}): a spawn that\n * fails for one item usually fails for every item (missing cwd, adapter\n * gone, process limits), so burning through the rest is pure noise.\n */\nexport class AgentSpawnError extends Error {\n constructor(\n readonly stepId: string,\n readonly cause: unknown,\n ) {\n super(`step '${stepId}': agent spawn failed — ${errorMessage(cause)}`)\n this.name = \"AgentSpawnError\"\n }\n}\n\n/**\n * Thrown instead of dispatching a step whose run was cancelled\n * (`ctx.signal.aborted`) — checked BEFORE any work for the step begins (see\n * {@link execStepBody}'s entry guard), so a cancel stops the run from\n * starting any further step, including a sibling within the SAME stage/\n * fan-out, not just a later one. Never journaled: it's thrown before a\n * cacheable step's `cache.set` call, so `workflow_retry` re-executes it.\n */\nexport class WorkflowCancelledError extends Error {\n constructor(readonly stepId: string) {\n super(`step '${stepId}': run cancelled — not started`)\n this.name = \"WorkflowCancelledError\"\n }\n}\n\ninterface RunState {\n readonly input: unknown\n readonly steps: Record<string, unknown>\n readonly maxTotalCostUsd?: number\n /** Last-known cost per session id; summed to get the run's total spend.\n * A Map (not a running delta) so a session reused across steps via\n * sessionRef is counted once, not double-counted. */\n readonly costBySession: Map<string, number>\n /** Journal keys ({@link cachedHitKey}) of steps whose output was replayed\n * from the cache this run and whose completion hasn't been reported yet —\n * consumed by {@link completeStep} to tag `onStepComplete` with\n * `{ cached: true }` (F35). */\n readonly cachedHits: Set<string>\n}\n\ninterface RunCtx {\n readonly state: RunState\n readonly approve?: RunWorkflowArgs[\"approve\"]\n readonly resume?: RunWorkflowArgs[\"resume\"]\n readonly onInputRequired?: RunWorkflowArgs[\"onInputRequired\"]\n readonly signal?: AbortSignal\n readonly agents?: RunWorkflowArgs[\"agents\"]\n readonly cwd?: string\n readonly workspaceSlug?: string\n /** AIP-58 §4 — see {@link RunWorkflowArgs.workspace}. */\n readonly workspace?: string\n /** AIP-58 §4 — see {@link RunWorkflowArgs.artifactsDir}. */\n readonly artifactsDir?: string\n readonly runId?: string\n readonly onArtifact?: RunWorkflowArgs[\"onArtifact\"]\n readonly cache?: RunWorkflowArgs[\"cache\"]\n readonly cacheKey?: RunWorkflowArgs[\"cacheKey\"]\n /** Set inside a `map`/`pipeline` fan-out body — the `[<index>]` path\n * (nested maps append their own `[<index>]`) appended to every cache\n * journal key computed under this ctx, so each item of a shared-id\n * body caches independently instead of overwriting one shared entry\n * (F33). Mirrors the id-suffixing {@link withIndexedHooks} already does\n * for `onStepStart`/`onStepComplete`. */\n readonly cacheKeySuffix?: string\n readonly onStepStart?: RunWorkflowArgs[\"onStepStart\"]\n readonly onStepComplete?: RunWorkflowArgs[\"onStepComplete\"]\n readonly onStepSkipped?: RunWorkflowArgs[\"onStepSkipped\"]\n readonly onStepFailed?: RunWorkflowArgs[\"onStepFailed\"]\n readonly runGateCommand?: RunWorkflowArgs[\"runGateCommand\"]\n readonly onGateReport?: RunWorkflowArgs[\"onGateReport\"]\n /** Sessions spawned in the current release scope (the run, or one\n * `map`/`pipeline` item) — released when that scope settles. */\n readonly spawned?: string[]\n /** F42 — on-disk artifact filenames already claimed this run, under\n * `artifactsDir` (one flat namespace, no subdirectories). One Set per\n * top-level run, shared by every nested `subworkflow` call (they write\n * into the SAME `artifactsDir` — see the `\"subworkflow\"` case in\n * `execStep`), so a parent's and a child's artifacts can't silently\n * collide either. See {@link reserveArtifactDestName}. */\n readonly usedArtifactNames?: Set<string>\n}\n\n/** Open a release scope for one fan-out item: sessions its steps spawn are\n * released as soon as the item settles, not held until the run ends. */\nfunction withReleaseScope(ctx: RunCtx): RunCtx {\n return { ...ctx, spawned: [] }\n}\n\n/** Release every session collected in `ctx`'s scope (see\n * `AgentSessionHost.releaseSession`). Never throws. */\nasync function releaseScope(ctx: RunCtx): Promise<void> {\n const release = ctx.agents?.releaseSession\n if (!release || !ctx.spawned || ctx.spawned.length === 0) return\n const ids = ctx.spawned.splice(0)\n const agents = ctx.agents\n await Promise.all(ids.map((id) => Promise.resolve().then(() => release.call(agents, id)).catch(() => undefined)))\n}\n\nfunction view(ctx: RunCtx, item?: unknown, index?: number): Bindings {\n return {\n input: ctx.state.input,\n steps: ctx.state.steps,\n item,\n index,\n ...(ctx.workspace !== undefined ? { run: { workspace: ctx.workspace } } : {}),\n }\n}\n\n/**\n * A `map`/`pipeline` fan-out body can't be enumerated at compile time (the\n * item list is only known at runtime — see `collectStaticSteps` in\n * `runtime/workflow-runner.ts`), so its per-item steps all share one static\n * compiled id (e.g. \"clean\"). Reporting every iteration under that same id\n * makes the host's step list unable to tell iterations apart (AIP-58 §5 /\n * F28). Wrapping `onStepStart`/`onStepComplete` for the duration of ONE\n * item's execution suffixes every step id it reports with `[<index>]`\n * (e.g. \"clean[0]\", \"clean[1]\") — the host discovers these dynamically,\n * same as any other step it didn't see at compile time.\n */\nfunction withIndexedHooks(ctx: RunCtx, index: number): RunCtx {\n const cacheKeySuffix = `${ctx.cacheKeySuffix ?? \"\"}[${index}]`\n if (!ctx.onStepStart && !ctx.onStepComplete && !ctx.onStepSkipped && !ctx.onStepFailed) {\n return { ...ctx, cacheKeySuffix }\n }\n return {\n ...ctx,\n cacheKeySuffix,\n onStepStart: ctx.onStepStart\n ? (id: string, info?: StepHookInfo) => ctx.onStepStart!(`${id}[${index}]`, info)\n : undefined,\n onStepComplete: ctx.onStepComplete\n ? (id: string, out: unknown, info?: StepHookInfo) => ctx.onStepComplete!(`${id}[${index}]`, out, info)\n : undefined,\n onStepSkipped: ctx.onStepSkipped\n ? (id: string, info: StepSkippedInfo) => ctx.onStepSkipped!(`${id}[${index}]`, info)\n : undefined,\n onStepFailed: ctx.onStepFailed\n ? (id: string, info: StepFailedInfo) => ctx.onStepFailed!(`${id}[${index}]`, info)\n : undefined,\n }\n}\n\n/**\n * The innermost step an in-flight error came from, as a reporter bound to\n * that step's own (indexed) hooks — set by the first {@link execStep} frame\n * the error unwinds through, so a tolerant fan-out that swallows the error\n * can still fail the step that actually threw (not its item's wrapper).\n */\nconst failureOrigin = new WeakMap<object, (info: StepFailedInfo) => void>()\n\n/** A tolerant fan-out item threw: report it via `onStepFailed` on the step\n * that threw (see {@link failureOrigin}), else on the item's body step. */\nfunction reportItemFailure(err: unknown, itemCtx: RunCtx, bodyId: string): void {\n const info = { error: errorMessage(err) }\n const origin = typeof err === \"object\" && err !== null ? failureOrigin.get(err) : undefined\n if (origin) {\n // Consume it: a host may reject every item with the SAME error object.\n failureOrigin.delete(err as object)\n origin(info)\n } else {\n itemCtx.onStepFailed?.(bodyId, info)\n }\n}\n\n/**\n * Spawn circuit breaker for one tolerant fan-out — see\n * {@link MapStep.maxConsecutiveSpawnFailures}. `settle` is fed every\n * item's outcome in completion order; `open` is the first error of the\n * streak that tripped it (undefined while closed). Once open it stays open.\n */\nfunction spawnBreaker(threshold: number): { settle: (err?: unknown) => void; readonly open: string | undefined } {\n let streak = 0\n let streakFirst: string | undefined\n let open: string | undefined\n return {\n settle(err?: unknown): void {\n if (open !== undefined) return\n if (!(err instanceof AgentSpawnError)) {\n streak = 0\n streakFirst = undefined\n return\n }\n if (streak === 0) streakFirst = err.message\n streak++\n if (threshold > 0 && streak >= threshold) open = streakFirst\n },\n get open() {\n return open\n },\n }\n}\n\n/** Report every item never started as `skipped` (each of its body's\n * statically-known steps, indexed like a started item's) — either because a\n * tripped spawn circuit breaker (`kind: \"circuit-open\"`) or the run being\n * cancelled (`kind: \"run-cancelled\"`) stopped the fan-out from starting any\n * more items. */\nfunction skipUnstartedItems(\n ctx: RunCtx,\n fanOutId: string,\n from: number,\n items: readonly unknown[],\n bodiesOf: (item: unknown, idx: number) => readonly RunStep[],\n kind: StepSkippedInfo[\"reason\"],\n reason: string,\n results: unknown[],\n): void {\n for (let idx = from; idx < items.length; idx++) {\n results[idx] = { status: \"skipped\", index: idx, item: items[idx], reason: `${kind}: ${reason}` }\n const itemCtx = withIndexedHooks(ctx, idx)\n if (!itemCtx.onStepSkipped) continue\n let bodies: readonly RunStep[]\n try {\n bodies = bodiesOf(items[idx], idx)\n } catch {\n // A body builder that needs a started item's state (a pipeline stage\n // reading its prevOutput) — the item's outcome above still records it.\n continue\n }\n for (const id of new Set(skippableStepIds(bodies))) {\n itemCtx.onStepSkipped(id, { reason: kind, branchId: fanOutId, message: reason })\n }\n }\n}\n\n/** The bound output of a tolerant fan-out. */\nfunction tolerantResult(results: unknown[], circuitOpen: string | undefined): TolerantFanOutResult {\n const outcomes = results as FanOutOutcome[]\n return {\n results: outcomes,\n succeeded: outcomes.filter((r) => r.status === \"fulfilled\").length,\n failed: outcomes.filter((r) => r.status === \"rejected\").length,\n skipped: outcomes.filter((r) => r.status === \"skipped\").length,\n ...(circuitOpen !== undefined ? { circuitOpen: { error: circuitOpen } } : {}),\n }\n}\n\n/** Resolve a value that is either a static string or a binding selector. */\nfunction resolveSel(sel: string | ((bindings: Bindings) => string), b: Bindings): string {\n return typeof sel === \"function\" ? sel(b) : sel\n}\n\n/** An AgentStep's `sessionRef` with `{{index}}` bound to the current fan-out\n * item (see `AgentStep.sessionRef`). Outside a fan-out it stays literal. */\nfunction resolveSessionRef(ref: string, b: Bindings): string {\n return b.index === undefined ? ref : ref.replace(/\\{\\{\\s*index\\s*\\}\\}/g, String(b.index))\n}\n\n/** Extract a JSON candidate from raw assistant text:\n * 1. last ```json fenced block if present, else\n * 2. last generic ``` fenced block if present, else\n * 3. the whole trimmed string. */\nfunction extractJsonCandidate(raw: string): string {\n const jsonFence = /```json\\s*([\\s\\S]*?)```/g\n const lastJson = lastMatch(jsonFence, raw)\n if (lastJson !== undefined) return lastJson\n\n const anyFence = /```\\s*([\\s\\S]*?)```/g\n const lastAny = lastMatch(anyFence, raw)\n if (lastAny !== undefined) return lastAny\n\n return raw.trim()\n}\n\nfunction lastMatch(re: RegExp, s: string): string | undefined {\n let m: RegExpExecArray | null\n let last: RegExpExecArray | null = null\n while ((m = re.exec(s)) !== null) last = m\n return last ? last[1]?.trim() : undefined\n}\n\nfunction spentUsd(state: RunState): number {\n let total = 0\n for (const c of state.costBySession.values()) total += c\n return total\n}\n\n/** Sentinel a resolved input/prompt's absolute run-workspace path is\n * replaced with before hashing (see {@link hashResolvedInputs}). */\nconst WORKSPACE_HASH_PLACEHOLDER = \"\\u0000$run.workspace\\u0000\"\n\n/** Deterministic content hash of a step's resolved inputs. `workspace` —\n * this run's `$run.workspace` / `_workflowFsRoot` absolute path, when the\n * host wires one — is replaced by a stable placeholder wherever it occurs\n * as a substring (including trailing subpaths, e.g.\n * `<workspace>/cleaned/out.txt`) before hashing. AIP-58 §4 gives every run\n * its OWN, disjoint workspace directory — a fresh absolute path each\n * time — so without this a step whose resolved input/prompt embeds\n * `$run.workspace` would hash differently on every run and never hit the\n * journal even though nothing about the step's actual work changed\n * (regression: AIP-58 P4 / #1467 broke #1421's cache this way). */\nfunction hashResolvedInputs(kind: string, resolved: unknown, workspace: string | undefined): string {\n const serialized = `${kind}\\u0000${JSON.stringify(resolved) ?? \"undefined\"}`\n const normalized = workspace ? serialized.split(workspace).join(WORKSPACE_HASH_PLACEHOLDER) : serialized\n return createHash(\"sha256\").update(normalized).digest(\"hex\")\n}\n\n/** `value`, recursively, with every string that is `from` (or `from` plus a\n * trailing subpath) rewritten to start with `to` instead. Used both to\n * normalize resolved inputs (`hashResolvedInputs` — via a literal split/join\n * rather than this walk, since inputs are hashed as one serialized blob)\n * and — here — to rewrite a cache hit's RECORDED OUTPUT so a path naming\n * the ORIGINAL run's workspace points at the CURRENT run's own instead\n * ({@link relocateCachedOutput}). Arrays/plain objects are copied; anything\n * else (numbers, booleans, class instances, `null`) passes through as-is. */\nfunction rewriteWorkspacePaths(value: unknown, from: string, to: string): unknown {\n if (typeof value === \"string\") return value.split(from).join(to)\n if (Array.isArray(value)) return value.map((v) => rewriteWorkspacePaths(v, from, to))\n if (value !== null && typeof value === \"object\" && value.constructor === Object) {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = rewriteWorkspacePaths(v, from, to)\n return out\n }\n return value\n}\n\n/** Every string in `value` (recursively) that names a path under `workspace`,\n * as a workspace-relative path — collected into `out`. A candidate only,\n * not yet checked against the filesystem (see {@link collectWorkspaceFiles}). */\nfunction collectWorkspaceCandidates(value: unknown, workspace: string, out: Set<string>): void {\n if (typeof value === \"string\") {\n if (value === workspace || value.startsWith(`${workspace}/`)) {\n const rel = relative(workspace, value)\n if (rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel)) out.add(rel)\n }\n return\n }\n if (Array.isArray(value)) {\n for (const v of value) collectWorkspaceCandidates(v, workspace, out)\n return\n }\n if (value !== null && typeof value === \"object\" && value.constructor === Object) {\n for (const v of Object.values(value as Record<string, unknown>)) collectWorkspaceCandidates(v, workspace, out)\n }\n}\n\n/** Every workspace-relative file/directory a cacheable step's output points\n * at — checked against the real filesystem (so a string that merely LOOKS\n * like a workspace path, but names nothing, isn't recorded as something a\n * later cache hit must relocate). Recorded on the journal entry\n * ({@link StepCacheEntry.workspaceFiles}) and copied forward by\n * {@link relocateCachedOutput} on a hit in a later run's own workspace. */\nasync function collectWorkspaceFiles(out: unknown, workspace: string): Promise<string[]> {\n const candidates = new Set<string>()\n collectWorkspaceCandidates(out, workspace, candidates)\n const files: string[] = []\n for (const rel of candidates) {\n try {\n await stat(join(workspace, rel))\n files.push(rel)\n } catch {\n // Not a real file/dir under the workspace — nothing to relocate.\n }\n }\n return files\n}\n\n/** Journal entry for a fresh (non-hit) cacheable `tool`/`agent` step —\n * records the workspace it ran under, and (best-effort) every file/dir its\n * output pointed at under that workspace, so a cache hit in a LATER run\n * (necessarily a different workspace — AIP-58 §4) can relocate them\n * (see {@link relocateCachedOutput}) instead of replaying an output that\n * names a path that only ever existed in this now-gone run. */\nasync function buildCacheEntry(ctx: RunCtx, out: unknown, hash: string): Promise<StepCacheEntry> {\n if (ctx.workspace === undefined) return { output: out, resolvedInputHash: hash }\n const workspaceFiles = await collectWorkspaceFiles(out, ctx.workspace)\n return {\n output: out,\n resolvedInputHash: hash,\n workspaceAtCache: ctx.workspace,\n ...(workspaceFiles.length > 0 ? { workspaceFiles } : {}),\n }\n}\n\n/** A `tool`/`agent` cache hit's recorded output, relocated onto the CURRENT\n * run: every file/dir the entry recorded under the ORIGINAL run's workspace\n * is copied into the matching path under this run's own (same relocation\n * spirit as `kind:\"artifact\"`'s cache hit — \"two runs MUST NEVER share a\n * workspace\", AIP-58 §4), then the recorded output's path strings are\n * rewritten to point there. Best-effort: a source the original run's\n * `scratch/` retention already swept is not this run's problem to recover\n * (same posture `kind:\"artifact\"`'s relocation takes). A no-op when the\n * entry predates this field, or this run has no workspace wired at all. */\nasync function relocateCachedOutput(ctx: RunCtx, entry: StepCacheEntry): Promise<unknown> {\n const from = entry.workspaceAtCache\n const to = ctx.workspace\n if (from === undefined || to === undefined || from === to) return entry.output\n for (const rel of entry.workspaceFiles ?? []) {\n const dest = join(to, rel)\n try {\n await mkdir(dirname(dest), { recursive: true })\n await cp(join(from, rel), dest, { recursive: true })\n } catch {\n // Best-effort — see doc above.\n }\n }\n return rewriteWorkspacePaths(entry.output, from, to)\n}\n\n/** Namespaced journal key for a step under a run's cacheKey. A step inside a\n * `map`/`pipeline` body shares its static compiled id (and kind) across\n * every item — `ctx.cacheKeySuffix` (the item's `[<index>]` path, set by\n * {@link withIndexedHooks}) disambiguates them so each item's cache entry\n * is independent instead of every item overwriting one shared key (F33). */\nfunction stepJournalKey(ctx: RunCtx, step: RunStep): string {\n return `${ctx.cacheKey}\\u0000${step.id}\\u0000${step.kind}${ctx.cacheKeySuffix ?? \"\"}`\n}\n\n/** True when this step should consult/populate the journal. */\nfunction isCacheEnabled(ctx: RunCtx, step: { cacheable?: boolean }): boolean {\n return step.cacheable === true && ctx.cache !== undefined && ctx.cacheKey !== undefined\n}\n\n/** Identity of one step execution under `ctx` for {@link RunState.cachedHits}\n * — the step id plus the map/pipeline item path, so concurrent items of a\n * shared-id body don't see each other's hits. */\nfunction cachedHitKey(ctx: RunCtx, stepId: string): string {\n return `${stepId}${ctx.cacheKeySuffix ?? \"\"}`\n}\n\n/** Report a step's completion — `{ cached: true }` when {@link execStep}\n * replayed it from the journal (F35: a cache hit still surfaces as a step). */\nfunction completeStep(ctx: RunCtx, stepId: string, out: unknown): void {\n const cached = ctx.state.cachedHits.delete(cachedHitKey(ctx, stepId))\n ctx.onStepComplete?.(stepId, out, cached ? { cached: true } : undefined)\n}\n\n/** Read the journal; on a hit return the output, else the key+hash to write on miss. */\nasync function readStepCache(\n ctx: RunCtx,\n step: RunStep,\n resolvedInputs: unknown,\n): Promise<{ hit: true; output: unknown } | { hit: false; key: string; hash: string }> {\n const key = stepJournalKey(ctx, step)\n const hash = hashResolvedInputs(step.kind, resolvedInputs, ctx.workspace)\n const entry = await ctx.cache!.get(key)\n if (entry !== undefined && entry.resolvedInputHash === hash) {\n return { hit: true, output: await relocateCachedOutput(ctx, entry) }\n }\n return { hit: false, key, hash }\n}\n\n/** `err.message` if `err` is an `Error`, else its string coercion. */\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** Formats the failure branch of {@link OutputSchemaLike.safeParse} — a real\n * zod `ZodError` satisfies this structurally (its `issues[]` carry `path`/\n * `message` plus extra fields TS ignores here), so this reads either a zod\n * schema's rejection or the ajv-backed JSON Schema adapter's. */\nfunction formatSchemaError(err: Extract<ReturnType<OutputSchemaLike[\"safeParse\"]>, { success: false }>[\"error\"]): string {\n return err.issues\n .map((i) => `${i.path.length > 0 ? i.path.join(\".\") + \": \" : \"\"}${i.message}`)\n .join(\", \")\n}\n\n/**\n * F27: render an agent step's `outputSchema` into a prompt-affordance note —\n * appended to BOTH the first prompt and every retry, so the model sees the\n * contract before it ever replies, not just after a rejected first attempt.\n * Prefers the exact schema: `compileOutputSchema`'s `jsonSchema` marker for a\n * WORKFLOW.md-authored step, else a live zod schema's own `z.toJSONSchema()`\n * (a TS-authored `buildAgentStep` caller commonly passes one directly — see\n * `OutputSchemaLike`'s doc). Degrades to a short field list when neither\n * conversion is possible (an exotic zod type, or a hand-built\n * `OutputSchemaLike` with no `jsonSchema` marker) — never throws, since a\n * step's prompt must never fail to build over an unrelated schema quirk.\n */\nfunction describeOutputSchemaForPrompt(schema: OutputSchemaLike): string | undefined {\n if (schema.jsonSchema !== undefined) {\n return `When done, reply with ONLY a JSON object matching this JSON Schema: ${JSON.stringify(schema.jsonSchema)}`\n }\n try {\n const jsonSchema = z.toJSONSchema(schema as unknown as z.ZodType)\n return `When done, reply with ONLY a JSON object matching this JSON Schema: ${JSON.stringify(jsonSchema)}`\n } catch {\n // Not a convertible zod schema — fall through to the short field list.\n }\n const shape = (schema as { shape?: unknown }).shape\n if (shape && typeof shape === \"object\") {\n const fields = Object.keys(shape)\n if (fields.length > 0) {\n return `When done, reply with ONLY a JSON object with these fields: ${fields.join(\", \")}`\n }\n }\n return undefined\n}\n\n/**\n * The statically-known steps under `steps` that a skipped `branch` arm\n * reports via `onStepSkipped`: leaf steps, plus `map`/`pipeline`/\n * `subworkflow` steps by their own id (their bodies aren't enumerable here or\n * don't report through this run's hooks). Structural wrappers (group,\n * parallel, branch, loop) are walked, never reported themselves.\n */\nfunction skippableStepIds(steps: readonly RunStep[], acc: string[] = []): string[] {\n for (const s of steps) {\n switch (s.kind) {\n case \"group\":\n skippableStepIds(s.steps, acc)\n break\n case \"parallel\":\n for (const br of s.branches) skippableStepIds(br.steps, acc)\n break\n case \"branch\":\n skippableStepIds(s.then, acc)\n if (s.otherwise) skippableStepIds(s.otherwise, acc)\n break\n case \"loop\":\n skippableStepIds(s.body, acc)\n break\n default:\n acc.push(s.id)\n }\n }\n return acc\n}\n\n/** Run an ordered list of steps, binding each output under its id; return last. */\nasync function runSequence(\n steps: readonly RunStep[],\n ctx: RunCtx,\n item: unknown,\n index: number | undefined,\n): Promise<unknown> {\n let last: unknown\n for (const s of steps) {\n const out = await execStep(s, ctx, item, index)\n ctx.state.steps[s.id] = out\n completeStep(ctx, s.id, out)\n last = out\n }\n return last\n}\n\n/**\n * Send a prompt and wait for the turn to end; if the session signals AIP-58\n * §3(a) (`run.requestInput`) before this returns, durably suspend via\n * `ctx.onInputRequired` — the promise only resolves once an external event\n * supplies the resume payload — then forward that payload (JSON) as the\n * step's NEXT prompt to the SAME session and repeat. So a step may suspend,\n * resume, and suspend again before this ever returns to its caller. No\n * signal observed ⇒ an ordinary one-shot send.\n */\nasync function sendPromptAndAwaitOutcome(\n ctx: RunCtx,\n step: AgentStep,\n sessionId: string,\n prompt: string,\n): Promise<void> {\n let next = prompt\n for (;;) {\n await ctx.agents!.sendPromptAndWait(sessionId, next)\n const req = ctx.agents!.takeInputRequest?.(sessionId)\n if (!req) return\n if (!ctx.onInputRequired) {\n throw new AgentInputRequiredError(step.id, req.prompt, req.schema)\n }\n const payload = await ctx.onInputRequired({ stepId: step.id, prompt: req.prompt, schema: req.schema })\n next = JSON.stringify(payload)\n }\n}\n\n/** Execute the full AgentStep body — spawn, prompt, policy, budget, outputSchema retry loop. */\nasync function execAgentStep(step: AgentStep, ctx: RunCtx, b: Bindings): Promise<unknown> {\n // Notify step start before any execution\n ctx.onStepStart?.(step.id)\n\n if (\n step.adapter &&\n ctx.state.maxTotalCostUsd !== undefined &&\n spentUsd(ctx.state) >= ctx.state.maxTotalCostUsd\n ) {\n throw new Error(\n `step '${step.id}': budget_exceeded — run spend $${spentUsd(ctx.state).toFixed(4)} >= cap $${ctx.state.maxTotalCostUsd}`,\n )\n }\n // Harness precedence: step `harness.cwd` (highest, among what this runtime\n // sees) beats the step's own `cwd` selector, which beats the run-level\n // `ctx.cwd` — see `AgentHarness`'s doc for the full chain (AGENT.md\n // frontmatter / app_run args / adapter default are resolved upstream of\n // this runtime, by the host's spawn implementation).\n // A relative step cwd resolves against the run cwd, never the daemon's own.\n const stepCwd = step.cwd ? resolveSel(step.cwd, b) : undefined\n const cwd =\n step.harness?.cwd ??\n (stepCwd !== undefined ? (ctx.cwd !== undefined ? resolve(ctx.cwd, stepCwd) : stepCwd) : ctx.cwd)\n // AIP-15 P2 `harness.knowledge`: materialize matched corpus entries into\n // the step cwd's `.knowledge/` BEFORE the spawn, and prepend the prompt\n // note pointing the session at the INDEX. An empty match is not an error —\n // it's recorded (`matched: 0`) and surfaced as a harness warning after the\n // spawn gives us a session to attribute it to.\n let knowledgeOut: KnowledgeAppliedRecord[] | undefined\n let knowledgeWarnings: readonly string[] = []\n if (step.harness?.knowledge && step.harness.knowledge.length > 0) {\n if (cwd === undefined) {\n throw new Error(\n `step '${step.id}': harness.knowledge requires a resolvable working directory (set step cwd, harness.cwd, or the run cwd)`,\n )\n }\n // Deferred selectors (loader-flagged `$…` refs) resolve per run against\n // the bindings; a relative resolved workspace joins to this run cwd.\n const knowledgeSelectors = resolveKnowledgeSelectors(step.id, step.harness.knowledge, b).map(\n (sel) => ({\n ...sel,\n workspace: isAbsolute(sel.workspace) ? sel.workspace : join(cwd, sel.workspace),\n }),\n )\n const materialized = await materializeKnowledge(step.id, knowledgeSelectors, cwd)\n knowledgeOut = materialized.records\n knowledgeWarnings = materialized.warnings\n if (materialized.written > 0) {\n const note =\n `Knowledge for this step is materialized under .knowledge/ ` +\n `(see .knowledge/INDEX.md, ${materialized.written} entries).`\n const inner = step.prompt\n step = { ...step, prompt: (b: Bindings) => `${note}\\n\\n${inner(b)}` }\n }\n }\n // Sandbox ref: a selector resolves per-run (undefined ⇒ host spawn); a\n // literal (slug string or inline spec object) passes through as-is.\n const sandbox =\n typeof step.sandbox === \"function\" ? step.sandbox(b) : step.sandbox\n // Step-level `model` (same semantics as `agent_start.model`): a selector\n // resolves per-run against the bindings. It is folded into the spawn's\n // harness slot — the channel both spawn paths already forward as the\n // session's model — but an explicit `harness.model` pinning (AIP-15 P2)\n // still wins: the block is the more specific pinning layer.\n const model = step.model !== undefined ? resolveSel(step.model, b) : undefined\n const harness =\n step.harness !== undefined || model !== undefined\n ? {\n ...(step.harness ?? {}),\n ...(model !== undefined && step.harness?.model === undefined ? { model } : {}),\n }\n : undefined\n let sessionId: string | undefined\n if (step.adapter) {\n // A cancelled run winds down (its `finally` still runs) — it must not\n // start new agent sessions on the way (a fan-out would otherwise keep\n // spawning reviewers after the cancel killed the running ones). The\n // entry guard in `execStepBody` already catches this for a step that\n // hadn't started at all; this second check covers a cancel landing\n // WHILE this step's own body is already running (knowledge\n // materialization, sandbox/model resolution, …), before it reaches spawn.\n if (ctx.signal?.aborted) throw new WorkflowCancelledError(step.id)\n try {\n sessionId = await ctx.agents!.spawn(resolveSel(step.adapter, b), {\n cwd,\n workspaceSlug: ctx.workspaceSlug,\n stepId: step.id,\n ...(sandbox !== undefined ? { sandbox } : {}),\n ...(step.options !== undefined ? { options: step.options } : {}),\n ...(harness !== undefined ? { harness } : {}),\n ...(step.agentTools !== undefined ? { agentTools: step.agentTools } : {}),\n ...(b.index !== undefined ? { stepKey: `${step.id}[${b.index}]` } : {}),\n })\n } catch (err) {\n throw new AgentSpawnError(step.id, err)\n }\n } else {\n sessionId = ctx.agents!.resolveByLabel(resolveSessionRef(step.sessionRef!, b))\n }\n if (!sessionId) throw new Error(`step '${step.id}': no session (adapter and sessionRef both unresolved)`)\n if (step.adapter) ctx.spawned?.push(sessionId)\n if (knowledgeWarnings.length > 0 && ctx.agents!.emitHarnessWarning) {\n ctx.agents!.emitHarnessWarning({\n sessionId,\n warnings: knowledgeWarnings,\n label: step.id,\n })\n }\n // `harness.tools` has no generic per-spawn allowlist mechanism reaching\n // this runtime today (see `AgentHarness.tools`'s doc) — record that\n // honestly on the run record rather than silently dropping the field.\n const harnessOut =\n harness !== undefined\n ? {\n ...harness,\n ...(harness.tools && harness.tools.length > 0\n ? { toolsApplied: false as const }\n : {}),\n }\n : undefined\n // AIP-15 P2 prompt affordance: only when the host actually exposes the\n // `run_request_input` tool (signalled by `takeInputRequest` existing) —\n // a host without it never suspends on this signal, so telling the model\n // to call a tool that doesn't exist would be actively misleading.\n const inputRequestAffordance = ctx.agents!.takeInputRequest\n ? \"\\n\\nIf you need information you don't have, call the run_request_input tool instead of asking in your reply.\"\n : \"\"\n // F27: an `outputSchema` step states its contract on the FIRST prompt, not\n // only on a rejected-reply retry — the model should never have to guess\n // the shape and then get corrected.\n const outputSchemaNote = step.outputSchema ? describeOutputSchemaForPrompt(step.outputSchema) : undefined\n const outputSchemaAffordance = outputSchemaNote ? `\\n\\n${outputSchemaNote}` : \"\"\n await sendPromptAndAwaitOutcome(ctx, step, sessionId, step.prompt(b) + inputRequestAffordance + outputSchemaAffordance)\n if (step.policy && ctx.agents!.onAwaitingInput) {\n await ctx.agents!.onAwaitingInput(sessionId, step.policy)\n }\n\n if (ctx.agents!.readCostUsd) {\n ctx.state.costBySession.set(sessionId, await ctx.agents!.readCostUsd(sessionId))\n }\n\n if (!step.outputSchema) {\n let text: string | undefined\n if (ctx.agents!.readFinalMessage) {\n try {\n text = await ctx.agents!.readFinalMessage(sessionId)\n } catch {\n // ignore\n }\n }\n return { sessionId, ...(text !== undefined ? { text } : {}), ...(harnessOut ? { harness: harnessOut } : {}), ...(knowledgeOut ? { knowledgeApplied: knowledgeOut } : {}) }\n }\n\n // Validate-and-retry loop\n if (!ctx.agents!.readFinalMessage) {\n throw new Error(`step '${step.id}': outputSchema requires a host with readFinalMessage`)\n }\n const maxRetries = step.maxRetries ?? 2\n let lastErr = \"\"\n let lastRaw = \"\"\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const raw = await ctx.agents!.readFinalMessage(sessionId)\n lastRaw = raw\n const candidate = extractJsonCandidate(raw)\n let value: unknown\n try {\n value = JSON.parse(candidate)\n } catch {\n lastErr = \"not valid JSON\"\n if (attempt < maxRetries) {\n await sendPromptAndAwaitOutcome(\n ctx,\n step,\n sessionId,\n `Your previous reply did not match the required schema: ${lastErr}. ` +\n `Reply again with ONLY a JSON object that matches. No prose, no code fence needed.` +\n outputSchemaAffordance,\n )\n }\n continue\n }\n const res = step.outputSchema.safeParse(value)\n if (res.success) return { sessionId, output: res.data, ...(harnessOut ? { harness: harnessOut } : {}), ...(knowledgeOut ? { knowledgeApplied: knowledgeOut } : {}) }\n lastErr = formatSchemaError(res.error)\n if (attempt < maxRetries) {\n await sendPromptAndAwaitOutcome(\n ctx,\n step,\n sessionId,\n `Your previous reply did not match the required schema: ${lastErr}. ` +\n `Reply again with ONLY a JSON object that matches. No prose, no code fence needed.` +\n outputSchemaAffordance,\n )\n }\n }\n // AIP-58 §3 Outcome rule: a turn ending without producing a validated\n // output is `missing-output`, regardless of how the final message reads.\n // A trailing \"?\" is ONLY a triage hint — it never upgrades this to\n // `suspended` (that requires one of the two explicit signals above).\n const hint = lastRaw.trim().endsWith(\"?\") ? (\"possible-input-request\" as const) : undefined\n throw new StepOutcomeError(\n step.id,\n \"missing-output\",\n `step '${step.id}': missing-output — final message never matched outputSchema (${lastErr})`,\n hint,\n )\n}\n\n/** Best-effort `JSON.parse` — `undefined` (never a throw) on blank/invalid text. */\nfunction tryParseJson(text: string): unknown {\n const trimmed = text.trim()\n if (!trimmed) return undefined\n try {\n return JSON.parse(trimmed)\n } catch {\n return undefined\n }\n}\n\n/**\n * The runtime's own subprocess runner for `kind: \"gate\"` steps, used when no\n * `runGateCommand` host hook is injected — a plain `node:child_process`\n * argv-vector invocation (no shell interpolation). Exit code 0 always\n * resolves (never rejects on a non-zero exit); a timeout resolves with\n * `timedOut: true` and whatever partial output was captured. `spec.signal`\n * (the run's cancel signal) is threaded straight into `execFile`'s own\n * `signal` option, which kills the child process — a cancelled run must not\n * leave a gate's subprocess running unsupervised any more than it leaves an\n * agent step's session running; {@link execGateStep} re-checks the signal\n * right after this resolves to turn the kill into a `WorkflowCancelledError`.\n */\nfunction defaultRunGateCommand(spec: {\n command: string\n args: readonly string[]\n cwd: string\n timeoutMs?: number\n signal?: AbortSignal\n}): Promise<GateCommandResult> {\n return new Promise((resolve) => {\n execFile(\n spec.command,\n [...spec.args],\n { cwd: spec.cwd, timeout: spec.timeoutMs, maxBuffer: 10 * 1024 * 1024, signal: spec.signal },\n (err, stdout, stderr) => {\n if (!err) {\n resolve({ exitCode: 0, stdout, stderr })\n return\n }\n const nodeErr = err as NodeJS.ErrnoException & { code?: number | string; killed?: boolean; signal?: string }\n const timedOut = nodeErr.killed === true && nodeErr.signal !== undefined && spec.timeoutMs !== undefined\n const exitCode = typeof nodeErr.code === \"number\" ? nodeErr.code : 1\n resolve({ exitCode, stdout, stderr, ...(timedOut ? { timedOut: true } : {}) })\n },\n )\n })\n}\n\n/** Resolve a gate's report: the command's stdout if it parses as JSON, else\n * the file at `reportPath` (relative to `cwd`), parsed as JSON. `undefined`\n * when neither yields parseable JSON — never a throw (a gate that emits no\n * structured report is still a valid pass/fail signal on its own). */\nasync function resolveGateReport(\n cmd: GateCommandResult,\n cwd: string,\n reportPath: string | undefined,\n): Promise<unknown> {\n const fromStdout = tryParseJson(cmd.stdout)\n if (fromStdout !== undefined) return fromStdout\n if (!reportPath) return undefined\n try {\n const abs = isAbsolute(reportPath) ? reportPath : join(cwd, reportPath)\n const raw = await readFile(abs, \"utf8\")\n return tryParseJson(raw)\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve a gate step's `cwd` against the run bindings. The same string-ref\n * rule as {@link resolveRefString} (leading `$input|$item|$steps.<id>|$index`\n * token + trailing literal text; `$$` escapes a literal `$`; an unresolvable\n * or malformed ref throws naming the step and the field). The RESOLVED cwd is\n * then made absolute: an absolute value stays as-is, a RELATIVE one (incl.\n * `.`) resolves against the run's own `ctx.cwd` — never the daemon process\n * cwd. No `cwd` (or a selector resolving to one) falls back to the run cwd.\n */\nfunction resolveGateCwd(step: GateStep, ctx: RunCtx, b: Bindings): string {\n const fallback = ctx.cwd ?? process.cwd()\n if (!step.cwd) return fallback\n const resolved = resolveRefString(step.id, \"cwd\", resolveSel(step.cwd, b), b, \"error\")\n return isAbsolute(resolved) ? resolved : resolve(fallback, resolved)\n}\n\n/** Execute the full GateStep body — run, parse report, retry-with-reprompt. */\nasync function execGateStep(step: GateStep, ctx: RunCtx, b: Bindings): Promise<unknown> {\n const cwd = resolveGateCwd(step, ctx, b)\n const args = (step.args ?? []).map((arg, index) =>\n resolveRefString(step.id, `args[${index}]`, resolveSel(arg, b), b, \"error\"),\n )\n const maxAttempts = Math.max(1, step.retry?.maxAttempts ?? 1)\n\n let last: { ok: boolean; exitCode: number; report: unknown } | undefined\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // A cancel landing between retry attempts must not reprompt a session\n // that cancel's releaseAll() may have already killed (which would\n // surface as a confusing \"session not found\" error instead of a clean\n // WorkflowCancelledError), nor wait out a retry backoff pointlessly.\n if (ctx.signal?.aborted) throw new WorkflowCancelledError(step.id)\n if (attempt > 1 && step.onFail?.reprompt) {\n if (!ctx.agents) {\n throw new Error(`step '${step.id}': on_fail.reprompt requires a host agents implementation`)\n }\n const targetSessionId = ctx.agents.resolveByLabel(step.onFail.reprompt)\n if (!targetSessionId) {\n throw new Error(\n `step '${step.id}': on_fail.reprompt targets unknown step '${step.onFail.reprompt}' — no session found`,\n )\n }\n const reportText = JSON.stringify(last?.report ?? null, null, 2)\n const extra = step.onFail.with ? `\\n\\nAdditional context:\\n${JSON.stringify(step.onFail.with, null, 2)}` : \"\"\n await ctx.agents.sendPromptAndWait(\n targetSessionId,\n `Gate '${step.id}' failed (exit code ${last?.exitCode}). Report:\\n${reportText}${extra}\\n\\n` +\n `Please address the findings above, then reply when done.`,\n )\n }\n\n if (attempt > 1 && step.retry?.initialMs) {\n const delayMs =\n step.retry.backoff === \"exponential\"\n ? step.retry.initialMs * 2 ** (attempt - 2)\n : step.retry.initialMs\n await new Promise((resolve) => setTimeout(resolve, delayMs))\n }\n\n const cmdResult = await (ctx.runGateCommand ?? defaultRunGateCommand)({\n command: step.command,\n args,\n cwd,\n timeoutMs: step.timeoutMs,\n signal: ctx.signal,\n })\n // The signal killed the subprocess mid-command (see\n // `defaultRunGateCommand`) — report the step as cancelled, not as\n // whatever exit code the kill happened to produce, so it's never\n // journaled as succeeded/failed and `workflow_retry` re-runs it.\n if (ctx.signal?.aborted) throw new WorkflowCancelledError(step.id)\n const report = await resolveGateReport(cmdResult, cwd, step.reportPath)\n const ok = cmdResult.exitCode === 0\n last = { ok, exitCode: cmdResult.exitCode, report }\n ctx.onGateReport?.({ stepId: step.id, ok, exitCode: cmdResult.exitCode, report, attempt })\n if (ok) break\n }\n\n if (!last!.ok) {\n const err = new Error(\n `step '${step.id}': gate failed after ${maxAttempts} attempt(s) — exit code ${last!.exitCode}`,\n ) as Error & { exitCode?: number; report?: unknown }\n err.exitCode = last!.exitCode\n err.report = last!.report\n throw err\n }\n return last\n}\n\n/** A cache hit still surfaces as a step (F35): fire `onStepStart` with\n * `{ cached: true }` and flag it so its completion is tagged too. */\nfunction cacheHit(ctx: RunCtx, step: RunStep, output: unknown): unknown {\n ctx.state.cachedHits.add(cachedHitKey(ctx, step.id))\n ctx.onStepStart?.(step.id, { cached: true })\n return output\n}\n\nasync function execStep(\n step: RunStep,\n ctx: RunCtx,\n item: unknown,\n index: number | undefined,\n): Promise<unknown> {\n try {\n return await execStepBody(step, ctx, item, index)\n } catch (err) {\n // Innermost frame wins: an outer (composite) frame sees it already set.\n if (typeof err === \"object\" && err !== null && !failureOrigin.has(err)) {\n failureOrigin.set(err, (info) => ctx.onStepFailed?.(step.id, info))\n }\n throw err\n }\n}\n\nasync function execStepBody(\n step: RunStep,\n ctx: RunCtx,\n item: unknown,\n index: number | undefined,\n): Promise<unknown> {\n const { state, signal } = ctx\n\n // A cancelled run must not dispatch ANY further step — a sibling still\n // queued in the same stage/fan-out included, not just a later stage (the\n // old contract, \"no new stages will be started\", left a same-stage\n // successor like a `map`'s next item or the step right after it free to\n // start). Checked before `onStepStart` fires, so a step that never ran\n // never reports as started. `runFinally` clears `signal` on its own ctx\n // (cleanup must survive a cancel), so this never blocks a `finally` step.\n if (signal?.aborted) throw new WorkflowCancelledError(step.id)\n\n const b = view(ctx, item, index)\n\n // Notify step start for non-agent steps (agent steps notify in\n // execAgentStep; a tool/artifact step notifies in its own case, once it\n // knows whether it's a cache hit).\n if (step.kind !== \"agent\" && step.kind !== \"tool\" && step.kind !== \"artifact\") {\n ctx.onStepStart?.(step.id)\n }\n\n switch (step.kind) {\n case \"tool\": {\n const input = step.input(b)\n const runIt = (): Promise<unknown> =>\n runTool({\n tool: step.tool,\n candidates: step.candidates,\n input,\n context: step.context ? step.context(b) : undefined,\n resolverContext: step.resolverContext,\n secrets: step.secrets,\n signal,\n })\n if (!isCacheEnabled(ctx, step)) {\n ctx.onStepStart?.(step.id)\n return runIt()\n }\n const c = await readStepCache(ctx, step, input)\n if (c.hit) return cacheHit(ctx, step, c.output)\n ctx.onStepStart?.(step.id)\n const out = await runIt()\n await ctx.cache!.set(c.key, await buildCacheEntry(ctx, out, c.hash))\n return out\n }\n\n case \"transform\":\n return step.compute(b)\n\n case \"map\": {\n const arr = [...step.over(b)]\n const parallelism = Math.max(1, step.parallelism ?? 1)\n const tolerant = step.onError === \"collect\"\n const results: unknown[] = new Array(arr.length)\n // Sliding window, not fixed batches: each of `parallelism` workers\n // pulls the next item as soon as its current one settles, so one slow\n // item never holds idle slots hostage. Same pool shape as `pipeline`.\n // Non-tolerant: after the first failure no NEW item starts (in-flight\n // ones finish), and the map rethrows that first error. Tolerant: a\n // failed item is reported on the step that threw, and the spawn\n // circuit breaker stops new items once spawning is systemically broken.\n let next = 0\n let failed = false\n const breaker = spawnBreaker(step.maxConsecutiveSpawnFailures ?? DEFAULT_MAX_CONSECUTIVE_SPAWN_FAILURES)\n const runItem = async (idx: number): Promise<void> => {\n const el = arr[idx]\n const inner = step.body(el, idx, view(ctx, el, idx))\n const wrapped = withReleaseScope(withIndexedHooks(ctx, idx))\n try {\n const out = await execStep(inner, wrapped, el, idx)\n completeStep(wrapped, inner.id, out)\n results[idx] = tolerant ? { status: \"fulfilled\", index: idx, value: out } : out\n breaker.settle()\n } catch (err) {\n if (!tolerant) {\n failed = true\n throw err\n }\n results[idx] = { status: \"rejected\", index: idx, item: el, error: errorMessage(err) }\n reportItemFailure(err, wrapped, inner.id)\n breaker.settle(err)\n } finally {\n await releaseScope(wrapped)\n }\n }\n const worker = async (): Promise<void> => {\n while (!failed && breaker.open === undefined && signal?.aborted !== true && next < arr.length) {\n const idx = next++\n await runItem(idx)\n }\n }\n await Promise.all(Array.from({ length: Math.min(parallelism, arr.length) }, () => worker()))\n // The run was cancelled while items remained unstarted: a non-tolerant\n // map must not report success over an incomplete `results` array — a\n // tolerant one instead marks the rest `skipped` (same shape a tripped\n // circuit breaker leaves), same as {@link skipUnstartedItems}'s other caller.\n if (signal?.aborted === true && next < arr.length) {\n if (!tolerant) throw new WorkflowCancelledError(step.id)\n skipUnstartedItems(ctx, step.id, next, arr, (el, idx) => [step.body(el, idx, view(ctx, el, idx))], \"run-cancelled\", \"run cancelled\", results)\n return tolerantResult(results, breaker.open)\n }\n if (!tolerant) return results\n if (breaker.open !== undefined) {\n skipUnstartedItems(ctx, step.id, next, arr, (el, idx) => [step.body(el, idx, view(ctx, el, idx))], \"circuit-open\", breaker.open, results)\n }\n return tolerantResult(results, breaker.open)\n }\n\n case \"pipeline\": {\n const items = [...step.over(b)]\n const tolerant = step.onError === \"collect\"\n if (items.length === 0) return tolerant ? tolerantResult([], undefined) : []\n const cap = Math.max(1, step.concurrency ?? items.length)\n const results: unknown[] = new Array(items.length)\n let next = 0\n const breaker = spawnBreaker(step.maxConsecutiveSpawnFailures ?? DEFAULT_MAX_CONSECUTIVE_SPAWN_FAILURES)\n const runItem = async (idx: number): Promise<void> => {\n let prev: unknown = undefined\n let stageId = step.id\n const wrapped = withReleaseScope(withIndexedHooks(ctx, idx))\n try {\n for (const stage of step.stages) {\n const inner = stage(items[idx], idx, prev, view(ctx, items[idx], idx))\n stageId = inner.id\n prev = await execStep(inner, wrapped, items[idx], idx)\n completeStep(wrapped, inner.id, prev)\n }\n results[idx] = tolerant ? { status: \"fulfilled\", index: idx, value: prev } : prev\n breaker.settle()\n } catch (err) {\n if (!tolerant) throw err\n results[idx] = { status: \"rejected\", index: idx, item: items[idx], error: errorMessage(err) }\n reportItemFailure(err, wrapped, stageId)\n breaker.settle(err)\n } finally {\n await releaseScope(wrapped)\n }\n }\n const worker = async (): Promise<void> => {\n while ((!tolerant || breaker.open === undefined) && signal?.aborted !== true && next < items.length) {\n const idx = next++\n await runItem(idx)\n }\n }\n await Promise.all(Array.from({ length: Math.min(cap, items.length) }, () => worker()))\n // See the `\"map\"` case's identical guard above.\n if (signal?.aborted === true && next < items.length) {\n if (!tolerant) throw new WorkflowCancelledError(step.id)\n skipUnstartedItems(\n ctx,\n step.id,\n next,\n items,\n (el, idx) => step.stages.map((stage) => stage(el, idx, undefined, view(ctx, el, idx))),\n \"run-cancelled\",\n \"run cancelled\",\n results,\n )\n return tolerantResult(results, breaker.open)\n }\n if (!tolerant) return results\n if (breaker.open !== undefined) {\n skipUnstartedItems(\n ctx,\n step.id,\n next,\n items,\n (el, idx) => step.stages.map((stage) => stage(el, idx, undefined, view(ctx, el, idx))),\n \"circuit-open\",\n breaker.open,\n results,\n )\n }\n return tolerantResult(results, breaker.open)\n }\n\n case \"branch\": {\n const taken = step.cond(b)\n const chosen = taken ? step.then : (step.otherwise ?? [])\n if (ctx.onStepSkipped) {\n // Report the untaken arm's steps as skipped (AIP-58 `step.skipped`)\n // — minus any id that also sits on the chosen path (arms sharing a\n // body, or a nested branch node that still has to decide).\n const onChosenPath = new Set(skippableStepIds(chosen))\n const untaken = taken ? (step.otherwise ?? []) : step.then\n for (const id of new Set(skippableStepIds(untaken))) {\n if (!onChosenPath.has(id)) ctx.onStepSkipped(id, { reason: \"branch-not-taken\", branchId: step.sourceId ?? step.id })\n }\n }\n return runSequence(chosen, ctx, item, index)\n }\n\n case \"loop\": {\n let iterations = 0\n let last: unknown\n while (\n iterations < step.maxIterations &&\n step.while(view(ctx, item, index))\n ) {\n last = await runSequence(step.body, ctx, item, index)\n iterations++\n }\n return last\n }\n\n case \"parallel\": {\n const outs = await Promise.all(\n step.branches.map((br) =>\n runSequence(br.steps, ctx, item, index).then((last) => ({\n id: br.id,\n last,\n })),\n ),\n )\n const record: Record<string, unknown> = {}\n for (const { id, last } of outs) record[id] = last\n return record\n }\n\n case \"approval\": {\n const prompt = step.prompt(b)\n const approvers = step.approvers ?? []\n const raw = ctx.approve\n ? await ctx.approve({\n stepId: step.id,\n prompt,\n approvers,\n ...(step.artifacts !== undefined ? { artifacts: step.artifacts } : {}),\n ...(step.timeoutMs !== undefined ? { timeoutMs: step.timeoutMs } : {}),\n })\n : true\n // A bare boolean is a host that doesn't record who decided — normalize\n // it to a full decision so downstream ledger/audit writes always have a\n // `who`.\n const decision: ApprovalDecision =\n typeof raw === \"boolean\" ? { approved: raw, who: \"host\" } : raw\n const approved = decision.approved\n const followups = approved\n ? (step.onApprove ?? [])\n : (step.onReject ?? [])\n await runSequence(followups, ctx, item, index)\n return { approved, who: decision.who, ...(decision.note !== undefined ? { note: decision.note } : {}) }\n }\n\n case \"suspend\": {\n if (!ctx.resume) throw new WorkflowSuspendedError(step.id, step.on)\n return ctx.resume({ stepId: step.id, on: step.on })\n }\n\n case \"group\":\n return runSequence(step.steps, ctx, item, index)\n\n case \"subworkflow\": {\n const childInput = step.input ? step.input(b) : state.input\n const child = await runWorkflowInner(step.workflow, childInput, {\n approve: ctx.approve,\n resume: ctx.resume,\n onInputRequired: ctx.onInputRequired,\n signal,\n agents: ctx.agents,\n cwd: ctx.cwd,\n workspaceSlug: ctx.workspaceSlug,\n workspace: ctx.workspace,\n artifactsDir: ctx.artifactsDir,\n runId: ctx.runId,\n onArtifact: ctx.onArtifact,\n cache: ctx.cache,\n cacheKey: ctx.cacheKey,\n runGateCommand: ctx.runGateCommand,\n onGateReport: ctx.onGateReport,\n spawned: ctx.spawned,\n usedArtifactNames: ctx.usedArtifactNames,\n })\n return child.output\n }\n\n case \"agent\": {\n if (!ctx.agents) throw new Error(`step '${step.id}': AgentStep requires a host agents implementation`)\n if (!isCacheEnabled(ctx, step)) return execAgentStep(step, ctx, b)\n const resolved = {\n prompt: step.prompt(b),\n adapter: step.adapter ? resolveSel(step.adapter, b) : undefined,\n model: step.model ? resolveSel(step.model, b) : undefined,\n sessionRef: step.sessionRef !== undefined ? resolveSessionRef(step.sessionRef, b) : undefined,\n }\n const c = await readStepCache(ctx, step, resolved)\n if (c.hit) return cacheHit(ctx, step, c.output) // cache hit ⇒ NO spawn, NO budget spend\n const out = await execAgentStep(step, ctx, b)\n await ctx.cache!.set(c.key, await buildCacheEntry(ctx, out, c.hash))\n return out\n }\n\n case \"gate\":\n return execGateStep(step, ctx, b)\n\n case \"artifact\":\n return execArtifactStep(step, ctx, b)\n }\n}\n\n/** Filesystem-safe filename — sanitizes either a bare artifact key (the\n * empty-basename fallback) or a declared file's basename. */\nfunction sanitizeArtifactFilename(name: string): string {\n const cleaned = name.replace(/[^a-zA-Z0-9._-]/g, \"_\")\n return cleaned.length > 0 ? cleaned : \"artifact\"\n}\n\n/**\n * F42 — an artifact's on-disk name under `artifactsDir` is the declared\n * source file's own basename (sanitized), not its key: `outputsFiles.pdf:\n * {path: transcript.pdf}` lands at `artifacts/transcript.pdf`, keeping the\n * extension, instead of P4's extension-less `artifacts/pdf`.\n *\n * Two keys whose source files share a basename (e.g. two different steps\n * each producing their own `report.json`) would otherwise silently\n * overwrite one another in the flat `artifactsDir` namespace — disambiguated\n * deterministically by prefixing a colliding name with its own sanitized\n * key (and a counter, in the practically-unreachable case that ALSO\n * collides), so the same workflow produces the same names run to run.\n * `usedNames` is one Set per top-level run, shared across subworkflows —\n * see `RunCtx.usedArtifactNames`.\n */\nfunction reserveArtifactDestName(rawPath: string, key: string, usedNames: Set<string>): string {\n const base = sanitizeArtifactFilename(basename(rawPath))\n let candidate = base\n if (usedNames.has(candidate)) {\n const keyPart = sanitizeArtifactFilename(key)\n candidate = `${keyPart}-${base}`\n for (let n = 2; usedNames.has(candidate); n++) {\n candidate = `${keyPart}-${n}-${base}`\n }\n }\n usedNames.add(candidate)\n return candidate\n}\n\n/** Read + hash the file at `rawPath` (resolved against `workspace`, which\n * MUST contain it) and copy it into `artifactsDir/<basename, disambiguated>`\n * (see {@link reserveArtifactDestName}). Shared by {@link execArtifactStep}'s\n * fresh path and {@link checkOutputsFiles}. */\nasync function copyIntoArtifacts(\n stepId: string,\n key: string,\n rawPath: string,\n workspace: string,\n artifactsDir: string,\n contentType: string | undefined,\n usedNames: Set<string>,\n): Promise<ArtifactEntry> {\n const abs = isAbsolute(rawPath) ? resolve(rawPath) : resolve(workspace, rawPath)\n const rel = relative(workspace, abs)\n if (rel.startsWith(\"..\") || isAbsolute(rel)) {\n throw new Error(`step '${stepId}': artifact path '${rawPath}' resolves outside the run workspace`)\n }\n const buf = await readFile(abs)\n const sha256 = createHash(\"sha256\").update(buf).digest(\"hex\")\n const destName = reserveArtifactDestName(rawPath, key, usedNames)\n await mkdir(artifactsDir, { recursive: true })\n await writeFile(join(artifactsDir, destName), buf)\n return {\n key,\n path: `artifacts/${destName}`,\n sha256,\n size: buf.length,\n stepId,\n ...(contentType !== undefined ? { contentType } : {}),\n }\n}\n\n/** `kind: \"artifact\"` — see {@link ArtifactStep}'s doc for the cache/relocate\n * mechanics. */\nasync function execArtifactStep(step: ArtifactStep, ctx: RunCtx, b: Bindings): Promise<ArtifactEntry> {\n if (ctx.workspace === undefined || ctx.artifactsDir === undefined) {\n throw new Error(`step '${step.id}': kind:\"artifact\" requires a run workspace (no workspace/artifactsDir wired)`)\n }\n const workspace = ctx.workspace\n const artifactsDir = ctx.artifactsDir\n const key = resolveSel(step.key, b)\n const rawPath = resolveSel(step.path, b)\n const contentType = step.contentType ? resolveSel(step.contentType, b) : undefined\n const resolvedInputs = { key, path: rawPath }\n const cacheOn = ctx.cache !== undefined && ctx.cacheKey !== undefined\n const journalKey = cacheOn ? stepJournalKey(ctx, step) : undefined\n const hash = cacheOn ? hashResolvedInputs(step.kind, resolvedInputs, ctx.workspace) : undefined\n\n if (cacheOn) {\n const entry = await ctx.cache!.get(journalKey!)\n if (entry !== undefined && entry.resolvedInputHash === hash) {\n const out = entry.output as ArtifactEntry\n // F42: reuse the EXACT name recorded at cache-write time — it may have\n // been collision-disambiguated (see `reserveArtifactDestName`), so\n // recomputing it fresh from `key` here could pick a different name\n // than what THIS run's other artifacts already claimed.\n const destName = out.path.slice(\"artifacts/\".length)\n ctx.usedArtifactNames?.add(destName)\n const destAbs = join(artifactsDir, destName)\n const srcAbs = join(entry.artifactsDirAtCache ?? artifactsDir, destName)\n if (srcAbs !== destAbs) {\n // AIP-58 §4 — \"two runs MUST NEVER share a workspace\": relocate the\n // bytes into THIS run's own artifactsDir rather than reading from\n // (or worse, pointing the run record at) the prior run's directory.\n await mkdir(dirname(destAbs), { recursive: true })\n try {\n await copyFile(srcAbs, destAbs)\n } catch {\n // Best-effort — the source may have been cleaned up by a host\n // retention policy (AIP-58 §4 permits discarding `scratch/`, but\n // `artifacts/` SHOULD be retained; a missing source here is a\n // deployment/retention issue, not something this run can fix).\n }\n }\n ctx.onArtifact?.(out)\n return cacheHit(ctx, step, out) as ArtifactEntry\n }\n }\n\n ctx.onStepStart?.(step.id)\n const out = await copyIntoArtifacts(step.id, key, rawPath, workspace, artifactsDir, contentType, ctx.usedArtifactNames!)\n if (cacheOn) {\n await ctx.cache!.set(journalKey!, { output: out, resolvedInputHash: hash!, artifactsDirAtCache: artifactsDir })\n }\n ctx.onArtifact?.(out)\n return out\n}\n\n/** Replace AIP-16's `<runId>`/`<workflowId>`/`<isoDate>` interpolation tokens\n * in a declared `outputsFiles.<key>.path`. `<toolId>` has no meaning at the\n * workflow level and is left literal. */\nfunction interpolateFileContractPath(path: string, workflowId: string, runId: string | undefined): string {\n return path\n .replace(/<runId>/g, runId ?? \"\")\n .replace(/<workflowId>/g, workflowId)\n .replace(/<isoDate>/g, new Date().toISOString().slice(0, 10))\n}\n\n/**\n * AIP-58 §4 / AIP-16 §Amendments — checked once every top-level step has\n * finished successfully. For each declared `outputsFiles.<key>`: present ⇒\n * copied into `artifactsDir` and reported via `onArtifact`, same as a\n * `kind:\"artifact\"` step (but never cache-aware — see the README's \"Cache/\n * replay interplay\" section for why that's a deliberate, documented limit —\n * route a step's file-shaped output through an explicit `kind:\"artifact\"`\n * step instead, if it needs to survive a cache hit in a later run);\n * absent + `required === true` ⇒ throws {@link MissingArtifactError}. Absent\n * OR `false` (the default — `required` is opt-in, matching AIP-16\n * `IO.schema.json`'s `fileContractEntry.required` doc and the V3 vector's own\n * note: \"with required absent or false, the same scenario would be a\n * warning\") ⇒ advisory only, a `console.warn`, the run still succeeds.\n */\nasync function checkOutputsFiles(\n outputsFiles: RuntimeWorkflow[\"outputsFiles\"],\n ctx: RunCtx,\n workflowId: string,\n lastStepId: string | undefined,\n): Promise<void> {\n if (!outputsFiles) return\n if (ctx.workspace === undefined || ctx.artifactsDir === undefined) return\n for (const [key, contract] of Object.entries(outputsFiles)) {\n const rawPath = interpolateFileContractPath(contract.path, workflowId, ctx.runId)\n const abs = isAbsolute(rawPath) ? rawPath : resolve(ctx.workspace, rawPath)\n let out: ArtifactEntry\n try {\n out = await copyIntoArtifacts(lastStepId ?? workflowId, key, abs, ctx.workspace, ctx.artifactsDir, contract.contentType, ctx.usedArtifactNames!)\n } catch {\n if (contract.required === true) {\n throw new MissingArtifactError(key, lastStepId)\n }\n console.warn(\n `[workflow-runtime] outputsFiles.${key} ('${contract.path}') is missing and not marked required — the run still succeeds (AIP-58 §4)`,\n )\n continue\n }\n ctx.onArtifact?.(out)\n }\n}\n\n/**\n * A workflow's `finally` steps ({@link RuntimeWorkflow.finally}): every one\n * runs, in order, without the run's abort signal (cleanup must survive a\n * cancel). After a failed body, a cleanup error is reported on its step and\n * swallowed so the original error wins; after a successful body the first\n * cleanup error is rethrown once every cleanup step has had its turn.\n */\nasync function runFinally(steps: readonly RunStep[], ctx: RunCtx, bodyFailed: boolean): Promise<void> {\n const cleanupCtx: RunCtx = { ...ctx, signal: undefined }\n let firstError: unknown\n for (const step of steps) {\n try {\n const out = await execStep(step, cleanupCtx, undefined, undefined)\n cleanupCtx.state.steps[step.id] = out\n completeStep(cleanupCtx, step.id, out)\n } catch (err) {\n cleanupCtx.onStepFailed?.(step.id, { error: errorMessage(err) })\n if (firstError === undefined) firstError = err\n }\n }\n if (!bodyFailed && firstError !== undefined) throw firstError\n}\n\nasync function runWorkflowInner(\n workflow: RuntimeWorkflow,\n input: unknown,\n hooks: Pick<RunCtx, \"approve\" | \"resume\" | \"onInputRequired\" | \"signal\" | \"agents\" | \"cwd\" | \"workspaceSlug\" | \"workspace\" | \"artifactsDir\" | \"runId\" | \"onArtifact\" | \"cache\" | \"cacheKey\" | \"onStepStart\" | \"onStepComplete\" | \"onStepSkipped\" | \"onStepFailed\" | \"runGateCommand\" | \"onGateReport\" | \"spawned\" | \"usedArtifactNames\">,\n maxTotalCostUsd?: number,\n): Promise<WorkflowRunResult> {\n const state: RunState = { input, steps: {}, costBySession: new Map(), maxTotalCostUsd, cachedHits: new Set() }\n // A subworkflow shares its parent's release scope (a parent step may\n // `sessionRef` a child's session); only the outermost run owns one — same\n // test (`hooks.spawned === undefined`) doubles as \"own a fresh\n // `usedArtifactNames`\", since a subworkflow always passes both down\n // together (see the `\"subworkflow\"` case above).\n const ownsScope = hooks.spawned === undefined\n const ctx: RunCtx = {\n state,\n ...hooks,\n ...(ownsScope ? { spawned: [], usedArtifactNames: new Set<string>() } : {}),\n }\n let lastId: string | undefined\n let bodyFailed = false\n try {\n for (const step of workflow.steps) {\n const out = await execStep(step, ctx, undefined, undefined)\n state.steps[step.id] = out\n completeStep(ctx, step.id, out)\n lastId = step.id\n }\n await checkOutputsFiles(workflow.outputsFiles, ctx, workflow.id, lastId)\n } catch (err) {\n bodyFailed = true\n throw err\n } finally {\n try {\n if (workflow.finally && workflow.finally.length > 0) await runFinally(workflow.finally, ctx, bodyFailed)\n } finally {\n if (ownsScope) await releaseScope(ctx)\n }\n }\n const bindings = view(ctx)\n const output = workflow.output\n ? workflow.output(bindings)\n : lastId !== undefined\n ? state.steps[lastId]\n : undefined\n return { output, bindings }\n}\n\nexport async function runWorkflow(\n args: RunWorkflowArgs,\n): Promise<WorkflowRunResult> {\n return runWorkflowInner(args.workflow, args.input, {\n approve: args.approve,\n resume: args.resume,\n onInputRequired: args.onInputRequired,\n signal: args.signal,\n agents: args.agents,\n cwd: args.cwd,\n workspaceSlug: args.workspaceSlug,\n workspace: args.workspace,\n artifactsDir: args.artifactsDir,\n runId: args.runId,\n onArtifact: args.onArtifact,\n cache: args.cache,\n cacheKey: args.cacheKey,\n onStepStart: args.onStepStart,\n onStepComplete: args.onStepComplete,\n onStepSkipped: args.onStepSkipped,\n onStepFailed: args.onStepFailed,\n runGateCommand: args.runGateCommand,\n onGateReport: args.onGateReport,\n }, args.maxTotalCostUsd)\n}\n","/**\n * compileWorkflowManifest — the connective step between an authored\n * `WORKFLOW.md` and a runnable workflow.\n *\n * AIP-15 ships every piece needed to run a declarative manifest except the\n * seam that joins them: `parseWorkflowManifest` (md + frontmatter → manifest)\n * and `workflowFromManifest` (manifest → `WorkflowHandle`) live in\n * `@agentproto/workflow`; `compileWorkflow` (handle → `RuntimeWorkflow`) lives\n * here. Without this chain an authored `WORKFLOW.md` parses and validates but\n * never reaches the executor. This joins the three so a manifest source string\n * compiles straight to a runnable workflow — no hand-built handle.\n *\n * Framework-pure: the caller owns reading the file off disk (this package does\n * no I/O), and passes the source string in. The tool registry + driver\n * candidates are injected via {@link CompileWorkflowOptions}, same as the\n * hand-built path.\n */\n\nimport {\n parseWorkflowManifest,\n workflowFromManifest,\n} from \"@agentproto/workflow/manifest\"\n\nimport { compileWorkflow } from \"./compile-workflow.js\"\nimport type { CompileWorkflowOptions } from \"./compile-workflow.js\"\nimport type { RuntimeWorkflow } from \"./types.js\"\n\n/**\n * Compile a `WORKFLOW.md` source string into a {@link RuntimeWorkflow} ready\n * for `runWorkflow`. Parses + validates the frontmatter against the AIP-15\n * schema, lifts it to a `WorkflowHandle`, then compiles its step graph against\n * the injected tool registry. Throws on invalid frontmatter (the parser's\n * diagnostic) or an unresolved tool / non-linear step (the compiler's).\n */\nexport function compileWorkflowManifest(\n source: string,\n opts: CompileWorkflowOptions,\n): RuntimeWorkflow {\n const manifest = parseWorkflowManifest(source)\n const handle = workflowFromManifest(manifest)\n return compileWorkflow(handle, opts)\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/build-agent-step.ts","../src/validate-input.ts","../src/compile-workflow.ts","../src/ref-string.ts","../src/types.ts","../src/node-fs-port.ts","../src/knowledge.ts","../src/run-workflow.ts","../src/load-workflow.ts"],"names":["f","join","mkdir","writeFile","isAbsolute","stat","dirname","b","resolve","readFile","basename","out"],"mappings":";;;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,CAAA,GAClB,MAAA;AACN,EAAA,OAAO,EAAE,QAAQ,QAAA,EAAS;AAC5B;AAEA,eAAsB,YACpB,IAAA,EAC4B;AAC5B,EAAA,OAAO,gBAAA,CAAiB,IAAA,CAAK,QAAA,EAAU,IAAA,CAAK,KAAA,EAAO;AAAA,IACjD,SAAS,IAAA,CAAK,OAAA;AAAA,IACd,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,iBAAiB,IAAA,CAAK,eAAA;AAAA,IACtB,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,KAAK,IAAA,CAAK,GAAA;AAAA,IACV,eAAe,IAAA,CAAK,aAAA;AAAA,IACpB,WAAW,IAAA,CAAK,SAAA;AAAA,IAChB,cAAc,IAAA,CAAK,YAAA;AAAA,IACnB,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,YAAY,IAAA,CAAK,UAAA;AAAA,IACjB,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,aAAa,IAAA,CAAK,WAAA;AAAA,IAClB,gBAAgB,IAAA,CAAK,cAAA;AAAA,IACrB,eAAe,IAAA,CAAK,aAAA;AAAA,IACpB,cAAc,IAAA,CAAK,YAAA;AAAA,IACnB,gBAAgB,IAAA,CAAK,cAAA;AAAA,IACrB,cAAc,IAAA,CAAK;AAAA,GACrB,EAAG,KAAK,eAAe,CAAA;AACzB;ACluDO,SAAS,uBAAA,CACd,QACA,IAAA,EACiB;AACjB,EAAA,MAAM,QAAA,GAAW,sBAAsB,MAAM,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAS,qBAAqB,QAAQ,CAAA;AAC5C,EAAA,OAAO,eAAA,CAAgB,QAAQ,IAAI,CAAA;AACrC","file":"index.mjs","sourcesContent":["/**\n * Shared `AgentStep` construction — the one place that applies AgentStep's\n * defaults (`policy` → `{ awaiting: \"fail\" }`, a literal `prompt` wrapped as\n * a `Selector`). Used by both `compileWorkflow`'s declarative `kind:\"agent\"`\n * step and `@agentproto/runtime`'s `translateStages` (the `workflow_start` /\n * `WorkflowRunner` path), so the two authoring surfaces stay byte-identical\n * instead of drifting apart.\n */\n\nimport type { AgentHarness, AgentSandboxRef, AgentStep, Bindings, Selector } from \"./types.js\"\n\nexport interface AgentStepFields {\n /** A literal prompt string, or a per-run selector (declarative manifest\n * steps resolve `$steps.*` refs into one before calling this). */\n prompt: string | Selector<string>\n adapter?: string\n /** See {@link AgentStep.cwd}. */\n cwd?: Selector<string>\n model?: Selector<string> | string\n sessionRef?: string\n sandbox?: AgentSandboxRef\n cacheable?: boolean\n policy?: AgentStep[\"policy\"]\n outputSchema?: AgentStep[\"outputSchema\"]\n maxRetries?: number\n options?: Record<string, boolean | number | string>\n harness?: AgentHarness\n agentTools?: readonly string[]\n}\n\n/** Build a runtime {@link AgentStep} from field values, applying the same\n * defaults everywhere: `policy` defaults to `{ awaiting: \"fail\" }`. */\nexport function buildAgentStep(id: string, fields: AgentStepFields): AgentStep {\n const prompt = fields.prompt\n return {\n kind: \"agent\",\n id,\n ...(fields.adapter !== undefined ? { adapter: fields.adapter } : {}),\n ...(fields.cwd !== undefined ? { cwd: fields.cwd } : {}),\n ...(fields.model !== undefined ? { model: fields.model } : {}),\n ...(fields.sessionRef !== undefined ? { sessionRef: fields.sessionRef } : {}),\n ...(fields.sandbox !== undefined ? { sandbox: fields.sandbox } : {}),\n ...(fields.cacheable ? { cacheable: true } : {}),\n ...(fields.options !== undefined ? { options: fields.options } : {}),\n prompt: typeof prompt === \"function\" ? prompt : ((_b: Bindings) => prompt),\n policy: fields.policy ?? { awaiting: \"fail\" as const },\n ...(fields.outputSchema !== undefined ? { outputSchema: fields.outputSchema } : {}),\n ...(fields.maxRetries !== undefined ? { maxRetries: fields.maxRetries } : {}),\n ...(fields.harness !== undefined ? { harness: fields.harness } : {}),\n ...(fields.agentTools !== undefined ? { agentTools: fields.agentTools } : {}),\n }\n}\n","/**\n * AIP-58 §3 Outcome rule — \"invalid or missing required input is checked\n * before any step runs\". AIP-16 declares a workflow's `inputs` block as\n * JSON Schema, but most existing WORKFLOW.md authors write a shorthand flat\n * map instead (`inputs: { url: { type, description, default } }` — see\n * `youtube-transcriber`'s `transcribe/WORKFLOW.md`). This module normalizes\n * that shorthand into real JSON Schema, then validates a run's input\n * against it with the same ajv machinery `@agentproto/tool` already uses for\n * TOOL contracts (`define-tool.ts`'s `validateJsonSchema`).\n */\n\nimport Ajv from \"ajv\"\nimport type { ErrorObject, ValidateFunction } from \"ajv\"\nimport addFormats from \"ajv-formats\"\n\n/** One shorthand-form input property, e.g. `{ type: \"string\", default: \"en\" }`. */\ninterface ShorthandInputSpec {\n type?: string\n description?: string\n default?: unknown\n /** Non-standard: shorthand-only marker promoted to the schema's top-level\n * `required[]` — see {@link normalizeWorkflowInputsSchema}. */\n required?: boolean\n [k: string]: unknown\n}\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v)\n\n/** True when `inputs` is already an AIP-16 canonical JSON Schema object\n * (`{ type: \"object\", properties: {...} }`) rather than the shorthand flat\n * map many existing manifests use. */\nfunction isJsonSchemaObject(inputs: Record<string, unknown>): boolean {\n return inputs[\"type\"] === \"object\" && isPlainObject(inputs[\"properties\"])\n}\n\n/**\n * Normalize a WORKFLOW.md `inputs` field to a JSON Schema object.\n *\n * Already-canonical JSON Schema (`{ type: \"object\", properties, required?\n * }`) passes through unchanged — its own `required[]`, if any, is honored\n * as-is (this is the shape AIP-58's V1 vector authors directly).\n *\n * The shorthand flat map (`{ <name>: { type, description?, default?,\n * required? } }`) is lifted: each key becomes a `properties` entry (minus\n * its shorthand-only `required` marker); a property gets added to the\n * schema's `required[]` ONLY when its shorthand spec sets `required: true`\n * AND declares no `default` — a `default` always makes a field optional to\n * omit, regardless of `required`. A shorthand property with no `required`\n * marker at all stays optional, so normalizing an existing manifest that\n * never used the marker (e.g. `youtube-transcriber`'s `transcribe/\n * WORKFLOW.md`) never newly fails validation for it.\n */\nexport function normalizeWorkflowInputsSchema(inputs: unknown): Record<string, unknown> {\n if (!isPlainObject(inputs)) return { type: \"object\", properties: {} }\n if (isJsonSchemaObject(inputs)) return inputs\n\n const properties: Record<string, unknown> = {}\n const required: string[] = []\n for (const [key, rawSpec] of Object.entries(inputs)) {\n const spec: ShorthandInputSpec = isPlainObject(rawSpec) ? rawSpec : {}\n const { required: isRequired, ...schemaFields } = spec\n properties[key] = schemaFields\n if (isRequired === true && spec[\"default\"] === undefined) required.push(key)\n }\n return {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n }\n}\n\n// Shared Ajv instance + per-schema validator cache — same pattern as\n// `@agentproto/tool`'s `define-tool.ts` (`_ajv` / `_validatorCache`), plus\n// `ajv-formats` so a manifest's `format: \"uri\"` (as AIP-58's V1 vector\n// declares) actually validates instead of Ajv's strict mode rejecting the\n// unrecognized format keyword outright.\nconst _ajv = addFormats(new Ajv({ allErrors: true }))\nconst _validatorCache = new WeakMap<object, ValidateFunction>()\n\nfunction compile(schema: Record<string, unknown>): ValidateFunction {\n let validate = _validatorCache.get(schema)\n if (!validate) {\n validate = _ajv.compile(schema)\n _validatorCache.set(schema, validate)\n }\n return validate\n}\n\nfunction fieldFor(err: ErrorObject): string {\n if (err.keyword === \"required\") {\n return String((err.params as { missingProperty?: string }).missingProperty ?? \"\")\n }\n return err.instancePath.replace(/^\\//, \"\") || \"(root)\"\n}\n\nexport type WorkflowInputValidation =\n | { valid: true; schema: Record<string, unknown> }\n | {\n valid: false\n schema: Record<string, unknown>\n /** AIP-58 §10 error code — this validator only ever produces one. */\n code: \"invalid-input\"\n /** Missing/invalid field names (deduped), for a caller that wants to\n * point at exactly what's wrong without re-parsing `message`. */\n fields: readonly string[]\n /** Human-readable message naming the missing/invalid fields. */\n message: string\n }\n\n/**\n * AIP-58 §9 `run.requestInput`/`run.resume`: `true` when `schema` is a\n * usable JSON Schema (ajv can compile it) — a plain object is necessary but\n * not sufficient (e.g. `{ type: \"not-a-type\" }` compiles-fails). Used to\n * reject a malformed `schema` argument before it's ever recorded as a\n * step's `StepRecord.suspend.schema`.\n */\nexport function isCompilableJsonSchema(schema: unknown): schema is Record<string, unknown> {\n if (!isPlainObject(schema)) return false\n try {\n compile(schema)\n return true\n } catch {\n return false\n }\n}\n\n/** One structural (zod-`ZodIssue`-shaped) validation failure — the common\n * currency between ajv's `ErrorObject[]` and zod's `ZodError.issues`, see\n * {@link OutputSchemaLikeIssue}. */\nexport interface SchemaValidationIssue {\n path: readonly (string | number)[]\n message: string\n}\n\nfunction toIssue(err: ErrorObject): SchemaValidationIssue {\n const path = err.instancePath.replace(/^\\//, \"\").split(\"/\").filter((seg) => seg.length > 0)\n if (err.keyword === \"required\") {\n const missing = (err.params as { missingProperty?: string }).missingProperty\n if (missing) path.push(missing)\n }\n return { path, message: err.message ?? \"invalid\" }\n}\n\n/**\n * Generic JSON Schema validation, used both by AIP-58 §3/§9 (validate a\n * `run.resume` payload against the suspended step's `StepRecord.suspend\n * .schema` BEFORE the resume transition happens — an invalid payload MUST\n * leave the run suspended, never transition it) and by `compileAgentStep`\n * (adapt a WORKFLOW.md-authored JSON Schema `outputSchema` into the\n * {@link OutputSchemaLike} shape `execAgentStep` consumes). `issues` mirrors\n * zod's `ZodError.issues` shape so both call sites format errors the same\n * way regardless of which schema language declared the contract.\n */\nexport function validateAgainstJsonSchema(\n schema: Record<string, unknown>,\n value: unknown,\n): { valid: true } | { valid: false; message: string; issues: readonly SchemaValidationIssue[] } {\n const validate = compile(schema)\n if (validate(value)) return { valid: true }\n const errors = validate.errors ?? []\n const issues = errors.map(toIssue)\n const detail = errors.map((e) => `${e.instancePath || \"/\"} ${e.message}`).join(\"; \")\n return { valid: false, message: `does not match schema: ${detail}`, issues }\n}\n\n/**\n * Validate a run's `input` against a WORKFLOW.md's declared `inputs`\n * (shorthand or canonical JSON Schema — see\n * {@link normalizeWorkflowInputsSchema}). The caller is responsible for\n * calling this BEFORE dispatching any step and BEFORE spawning any session\n * on an invalid result — this function only judges the input, it doesn't\n * gate execution itself.\n */\nexport function validateWorkflowInput(inputsField: unknown, input: unknown): WorkflowInputValidation {\n const schema = normalizeWorkflowInputsSchema(inputsField)\n const validate = compile(schema)\n if (validate(input ?? {})) return { valid: true, schema }\n\n const errors = validate.errors ?? []\n const fields = [...new Set(errors.map(fieldFor).filter((f) => f.length > 0))]\n const detail = errors.map((e) => `${e.instancePath || \"/\"} ${e.message}`).join(\"; \")\n return {\n valid: false,\n schema,\n code: \"invalid-input\",\n fields,\n message: `invalid input${fields.length > 0 ? ` (${fields.join(\", \")})` : \"\"}: ${detail}`,\n }\n}\n","/**\n * Compile a declarative AIP-15 `WorkflowHandle` into a runnable\n * {@link RuntimeWorkflow} for {@link runWorkflow}. This is the bridge that makes\n * an authored WORKFLOW.md actually execute.\n *\n * AIP-15 leaves the IO seam (`step.inputs`, `map.over`, `loop.while`) to a\n * meta-validator. This compiler pins a concrete, minimal **reference grammar**\n * for it — the convention a manifest author writes:\n *\n * - data refs: `$input` · `$input.a.b` · `$steps.<id>` · `$steps.<id>.a`\n * · `$item` · `$item.a` · `$index` (`$$` escapes a literal `$`)\n * - prompts: the above refs PLUS mustache-style `{{name}}` /\n * `{{a.b}}` interpolation, `{{#name}}…{{/name}}` conditional\n * and `{{^name}}…{{/name}}` inverted sections (see\n * {@link interpolateTemplate})\n * - `step.inputs`: a JSON object whose leaf strings may be refs (resolved\n * recursively); non-`$` strings are literals\n * - `map.over`: a ref to an array\n * - `loop.while` / approval prompt: `<ref> <op> <literal>` (`== != < <= > >=`)\n * or a bare ref (truthiness)\n *\n * Scope: the **linear / structured subset** of AIP-15 — steps run in document\n * order; `map`/`loop`/`parallel` nest their child step lists. Non-linear `next`\n * gotos are rejected with a clear diagnostic. `kind:\"branch\"` compiles in its\n * **forward-only** form: every `branches[].next`/`default`/`join` must name a\n * later sibling in the SAME step list (not backward, not into a nested map/\n * loop/parallel body). Arms are EXCLUSIVE by default — exactly one arm body\n * runs, then execution continues at the join (see `compileExclusiveBranch`);\n * `fallthrough: true` opts into the legacy \"target + everything after it\"\n * semantics (see `compileBranchChain`). Compiling a full goto graph\n * (backward jumps, cross-scope targets) is a separable follow-up; hand-author\n * a `loop` step for retry-style control flow instead.\n */\n\nimport type { WorkflowHandle } from \"@agentproto/workflow\"\nimport { assertKnownStepRefs } from \"@agentproto/workflow\"\nimport type { DriverHandle } from \"@agentproto/driver\"\nimport type { ToolHandle } from \"@agentproto/tool\"\nimport type { AgentRefResolution, AgentStep, Bindings, GateStep, OutputSchemaLike, RunStep, RuntimeWorkflow, Selector } from \"./types.js\"\nimport { buildAgentStep } from \"./build-agent-step.js\"\nimport { resolveRefString } from \"./ref-string.js\"\nimport { isCompilableJsonSchema, validateAgainstJsonSchema } from \"./validate-input.js\"\n\nexport interface CompileWorkflowOptions {\n /** TOOL contracts by id — each `tool` step resolves its handle here. */\n tools: ReadonlyMap<string, ToolHandle> | Record<string, ToolHandle>\n /** DRIVER candidates the resolver dispatches over for every tool step. */\n candidates: readonly DriverHandle[]\n /** Resolve a tool step's injected context (live capabilities) from bindings. */\n contextFor?: (toolId: string, bindings: Bindings) => unknown\n /** Sub-workflows by id, for `subworkflow` steps. */\n workflows?:\n | ReadonlyMap<string, WorkflowHandle>\n | Record<string, WorkflowHandle>\n /** App-scoped agent ids for a declarative `kind:\"agent\"` step's\n * `agent.ref` — e.g. `{ \"@app/reviewer\": { adapter: \"mastra-agent\",\n * options: { agent: \"<dir>/.agentproto/agents/reviewer/AGENT.md\" } } }`.\n * Built by the host from its own app-install state (see\n * `@agentproto/runtime`'s `resolveAgentRefsForWorkflow`). A step using\n * `agent.ref` with this unset, or naming a ref this map doesn't have,\n * fails compilation — never the runtime. */\n agentRefs?: ReadonlyMap<string, AgentRefResolution> | Record<string, AgentRefResolution>\n}\n\nexport class WorkflowCompileError extends Error {\n constructor(message: string) {\n super(`compileWorkflow: ${message}`)\n this.name = \"WorkflowCompileError\"\n }\n}\n\n// ── reference + predicate resolution (the AIP-16 IO seam) ────────────\n\nconst get = <T>(\n m: ReadonlyMap<string, T> | Record<string, T>,\n key: string,\n): T | undefined =>\n m instanceof Map ? m.get(key) : (m as Record<string, T>)[key]\n\nfunction dig(value: unknown, path: readonly string[]): unknown {\n let v = value\n for (const seg of path) {\n if (v == null) return undefined\n v = (v as Record<string, unknown>)[seg]\n }\n return v\n}\n\nconst REF_RE = /^\\$(input|item|steps|run)((?:\\.[^.]+)*)$/\n\n/**\n * The prefix form of the ref grammar: a ref token at the START of a string\n * that continues with a literal suffix (e.g. `$input.bookDir/knowledge` —\n * resolve `$input.bookDir`, append `/knowledge` verbatim). The token's path\n * segments stop at the first `.`, `$`, or `/` — so `$input.a$b/c` resolves\n * `$input.a` with rest `$b/c`. `$index` is recognized as a whole token too.\n */\nconst REF_PREFIX_RE = /^\\$(?:input|item|steps|run|index)((?:\\.[^.$/]+)*)/\n\n/** Resolve a single `$…` reference string against the run bindings. */\nexport function resolveRef(ref: string, b: Bindings): unknown {\n if (ref === \"$index\") return b.index\n const m = ref.match(REF_RE)\n if (!m) throw new WorkflowCompileError(`bad reference '${ref}'`)\n const segs = m[2] ? m[2].slice(1).split(\".\") : []\n switch (m[1]) {\n case \"input\":\n return dig(b.input, segs)\n case \"item\":\n return dig(b.item, segs)\n case \"steps\": {\n const [stepId, ...rest] = segs\n if (!stepId) throw new WorkflowCompileError(`'$steps' needs a step id`)\n return dig(b.steps[stepId], rest)\n }\n // AIP-58 §4 — `$run.workspace`, a convenience alias for the run\n // workspace path (see `Bindings.run`).\n case \"run\":\n return dig(b.run, segs)\n }\n}\n\n/** Resolve the leading ref token of a string (see {@link REF_PREFIX_RE}):\n * if `value` starts with a `$input`/`$item`/`$steps`/`$index` reference\n * token, resolve it against the bindings and return the resolved value plus\n * the literal remainder (`rest`). Throws exactly like {@link resolveRef} for\n * a matched-but-malformed token; returns `undefined` when the string does\n * not START with a ref token at all (caller decides pass-through vs error). */\nexport function resolveRefPrefixed(\n value: string,\n b: Bindings,\n): { resolved: unknown; rest: string } | undefined {\n const m = value.match(REF_PREFIX_RE)\n if (!m) return undefined\n const token = value.slice(0, m[0].length)\n return { resolved: resolveRef(token, b), rest: value.slice(m[0].length) }\n}\n\n// ── mustache-style prompt interpolation ──────────────────────────────\n\n/** A `{{…}}` tag name: dotted identifier path (`url`, `a.b.c`). */\nconst TAG_NAME = \"(?:[\\\\w$-]+)(?:\\\\.(?:[\\\\w$-]+))*\"\nconst TAG_RE = new RegExp(`\\\\{\\\\{(${TAG_NAME})\\\\}\\\\}`, \"g\")\n/** `{{#name}}inner{{/name}}` (conditional) or `{{^name}}inner{{/name}}` (inverted). */\nconst SECTION_RE = new RegExp(\n `\\\\{\\\\{([#^])(${TAG_NAME})\\\\}\\\\}([\\\\s\\\\S]*?)\\\\{\\\\{/\\\\2\\\\}\\\\}`,\n)\n\n/** Resolve a `{{…}}` tag name against the bindings — the same paths the\n * `$…` ref grammar reaches: `input.x`, `item.x`, `steps.<id>.x`, `index`,\n * and a bare name as shorthand for a top-level workflow input. */\nfunction resolveTagName(name: string, b: Bindings): unknown {\n const segs = name.split(\".\")\n const head = segs[0]!\n if (head === \"input\") return segs.length === 1 ? b.input : dig(b.input, segs.slice(1))\n if (head === \"item\") return segs.length === 1 ? b.item : dig(b.item, segs.slice(1))\n if (head === \"steps\" && segs.length > 1)\n return dig(b.steps[segs[1]!], segs.slice(2))\n if (head === \"index\" && segs.length === 1) return b.index\n if (head === \"run\") return segs.length === 1 ? b.run : dig(b.run, segs.slice(1))\n return dig(b.input, segs)\n}\n\n/** Stringify an interpolated value: strings verbatim, objects/arrays as\n * JSON, everything else (numbers, booleans) via `String()`, null as \"\" —\n * mustache convention. */\nfunction stringifyValue(v: unknown): string {\n if (v === null) return \"\"\n if (typeof v === \"string\") return v\n if (typeof v === \"object\") return JSON.stringify(v)\n return String(v)\n}\n\n/**\n * Interpolate mustache-style `{{…}}` templates against the run bindings.\n *\n * - `{{name}}` / `{{a.b}}` → the resolved value stringified; a MISSING\n * value leaves the placeholder as-is (never crashes, never renders\n * \"undefined\" into an agent prompt).\n * - `{{#name}}…{{/name}}` renders the inner text only when `name` is\n * truthy; `{{^name}}…{{/name}}` only when falsy. When a section tag\n * sits alone on its line (only whitespace around it), the whole line\n * collapses too — so a dropped section doesn't leave blank lines behind.\n * - Sections nest: inner text is interpolated recursively.\n */\nexport function interpolateTemplate(template: string, b: Bindings): string {\n let out = template\n for (;;) {\n const m = out.match(SECTION_RE)\n if (!m) break\n const kind = m[1]!\n const name = m[2]!\n const inner = m[3]!\n const value = resolveTagName(name, b)\n const truthy = kind === \"#\" ? Boolean(value) : !value\n const start = m.index!\n const end = start + m[0].length\n const before = out.slice(0, start)\n const after = out.slice(end)\n // Standalone-line detection: only whitespace between the tag and the\n // enclosing newlines on both sides.\n const lineStart = before.lastIndexOf(\"\\n\") + 1\n const nl = after.indexOf(\"\\n\")\n const standalone =\n before.slice(lineStart).trim() === \"\" &&\n (nl === -1 ? after : after.slice(0, nl)).trim() === \"\"\n let replacement: string\n if (!truthy) {\n replacement = \"\"\n } else {\n replacement = interpolateTemplate(inner, b)\n if (standalone) {\n // The newline that terminated the open-tag line and the whitespace +\n // newline that began the close-tag line belong to the tags, not the\n // rendered body.\n replacement = replacement.replace(/^\\n/, \"\").replace(/\\n[ \\t]*$/, \"\")\n }\n }\n // Only a standalone section swallows its own line's leading whitespace;\n // an inline one keeps everything before it on the line.\n out =\n (standalone ? before.slice(0, lineStart) : before) +\n replacement +\n (standalone\n ? (truthy ? (nl === -1 ? after : after.slice(nl)) : after.slice(nl + 1))\n : after)\n }\n return out.replace(TAG_RE, (whole, name: string) => {\n const v = resolveTagName(name, b)\n return v === undefined ? whole : stringifyValue(v)\n })\n}\n\n/**\n * Render an agent/approval step prompt for a run: `$…` refs first (a whole\n * string that starts with a ref token resolves exactly as before — a\n * ref-prefixed string resolves the token and interpolates the literal rest),\n * then mustache interpolation over the remainder / non-ref strings.\n */\nfunction renderPrompt(raw: string, b: Bindings): string {\n if (raw.startsWith(\"$$\")) return raw.slice(1)\n if (raw.startsWith(\"$\")) {\n const pref = resolveRefPrefixed(raw, b)\n if (pref) {\n const head =\n pref.rest === \"\" ? String(pref.resolved) : stringifyValue(pref.resolved)\n return head + interpolateTemplate(pref.rest, b)\n }\n }\n return interpolateTemplate(raw, b)\n}\n\n/** Recursively resolve a value node: refs in strings, into arrays/objects. */\nexport function resolveValue(node: unknown, b: Bindings): unknown {\n if (typeof node === \"string\") {\n if (node.startsWith(\"$$\")) return node.slice(1) // $$ → literal $\n if (node.startsWith(\"$\")) return resolveRef(node, b)\n return node\n }\n if (Array.isArray(node)) return node.map((n) => resolveValue(n, b))\n if (node && typeof node === \"object\") {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(node as Record<string, unknown>))\n out[k] = resolveValue(v, b)\n return out\n }\n return node\n}\n\n/** Like {@link resolveRef} but reports whether the referenced path actually\n * exists in the bindings — a strict subworkflow projection uses this to turn\n * a silently-`undefined` reference into a named error instead. */\nfunction refPathExists(ref: string, b: Bindings): boolean {\n const m = ref.match(REF_RE)\n if (!m) return false\n const segs = m[2] ? m[2].slice(1).split(\".\") : []\n let v: unknown\n if (m[1] === \"steps\") {\n const [stepId, ...rest] = segs\n if (!stepId || !(stepId in b.steps)) return false\n v = b.steps[stepId]\n segs.length = 0\n segs.push(...rest)\n } else {\n v = m[1] === \"input\" ? b.input : m[1] === \"run\" ? b.run : b.item\n }\n for (const seg of segs) {\n if (v === null || typeof v !== \"object\") return false\n const o = v as Record<string, unknown>\n if (!(seg in o)) return false\n v = o[seg]\n }\n return true\n}\n\n/** Strict variant of {@link resolveValue} for a subworkflow step's input\n * projection: an exact `$…` reference that resolves to `undefined` AND names\n * a path that doesn't exist in the bindings is a hard error naming the step\n * and key — never a silent `undefined` handed to the child. */\nexport function resolveValueStrict(node: unknown, b: Bindings, label: string): unknown {\n if (typeof node === \"string\") {\n if (node.startsWith(\"$$\")) return node.slice(1) // $$ → literal $\n if (node.startsWith(\"$\")) {\n const v = resolveRef(node, b)\n if (v === undefined && !refPathExists(node, b)) {\n throw new WorkflowCompileError(\n `${label}: reference '${node}' resolves to nothing — the referenced field does not exist`,\n )\n }\n return v\n }\n return node\n }\n if (Array.isArray(node)) return node.map((n) => resolveValueStrict(n, b, label))\n if (node && typeof node === \"object\") {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(node as Record<string, unknown>))\n out[k] = resolveValueStrict(v, b, label)\n return out\n }\n return node\n}\n\nconst COMPARATORS: Record<string, (a: number, b: number) => boolean> = {\n \"<\": (a, c) => a < c,\n \"<=\": (a, c) => a <= c,\n \">\": (a, c) => a > c,\n \">=\": (a, c) => a >= c,\n}\n\nfunction literal(token: string, b: Bindings): unknown {\n if (token.startsWith(\"$\")) return resolveRef(token, b)\n if (token === \"true\") return true\n if (token === \"false\") return false\n if (token === \"null\") return null\n if (/^-?\\d+(\\.\\d+)?$/.test(token)) return Number(token)\n return token.replace(/^['\"]|['\"]$/g, \"\")\n}\n\n/** Evaluate a `while`/`when` predicate string against the bindings. */\nexport function evalPredicate(expr: string, b: Bindings): boolean {\n const m = expr.match(/^(.+?)\\s*(==|!=|<=|>=|<|>)\\s*(.+)$/)\n if (!m) return Boolean(literal(expr.trim(), b)) // bare ref → truthiness\n const left = literal(m[1]!.trim(), b)\n const right = literal(m[3]!.trim(), b)\n switch (m[2]) {\n case \"==\":\n return left === right\n case \"!=\":\n return left !== right\n default: {\n const cmp = COMPARATORS[m[2]!]!\n return cmp(Number(left), Number(right))\n }\n }\n}\n\n// ── step compilation ─────────────────────────────────────────────────\n\n/** AIP step ids may be paths/refs; the runtime key is the last segment. */\nfunction normalizeToolId(ref: string): string {\n let s = ref.trim()\n if (s.endsWith(\"/TOOL.md\")) s = s.slice(0, -\"/TOOL.md\".length)\n const slash = s.lastIndexOf(\"/\")\n return slash === -1 ? s : s.slice(slash + 1)\n}\n\n// AIP step frontmatter leaves IO fields as opaque `{}`; read them dynamically.\nconst f = <T>(step: object, key: string): T =>\n (step as Record<string, unknown>)[key] as T\n\n/** Validate an optional `timeout_ms` field: the JSON schema guards\n * WORKFLOW.md-authored manifests, but a programmatic `defineWorkflow` (or\n * entry.mjs handle) step bypasses that schema entirely — a bad value\n * (`timeout_ms: \"five\"`, `timeout_ms: 0`) must fail HERE, at compile time,\n * not silently reach the runtime dispatcher. */\nfunction assertStepTimeoutMs(id: string, kind: string, value: unknown): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 1) {\n throw new WorkflowCompileError(\n `${kind} step '${id}' has an invalid 'timeout_ms' (${JSON.stringify(value)}) — must be a number >= 1`,\n )\n }\n return value\n}\n\nfunction assertLinear(steps: readonly { id: string; kind: string; next?: string }[]): void {\n steps.forEach((s, i) => {\n const next = (s as { next?: string }).next\n const followingId = steps[i + 1]?.id\n if (next && next !== followingId) {\n throw new WorkflowCompileError(\n `step '${s.id}' has a non-linear next='${next}' — the structured-subset ` +\n `compiler only runs steps in document order. Hand-author a BranchStep ` +\n `or nest structurally.`,\n )\n }\n })\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction collectStepIds(steps: any[], ids: Set<string> = new Set()): Set<string> {\n for (const s of steps) {\n if (typeof s?.id === \"string\") ids.add(s.id)\n if (Array.isArray(s?.steps)) collectStepIds(s.steps, ids)\n if (Array.isArray(s?.branches)) {\n for (const br of s.branches) {\n if (Array.isArray(br?.steps)) collectStepIds(br.steps, ids)\n }\n }\n }\n return ids\n}\n\n/** Per-compile context: the public options plus the full set of step ids\n * declared anywhere in THIS workflow (recomputed fresh for each nested\n * `subworkflow` child, which has its own id namespace). */\ninterface Ctx {\n opts: CompileWorkflowOptions\n knownStepIds: ReadonlySet<string>\n}\n\nexport function compileWorkflow(\n handle: WorkflowHandle,\n opts: CompileWorkflowOptions,\n): RuntimeWorkflow {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const steps = handle.steps as unknown as any[]\n if (handle.start && handle.start !== steps[0]?.id) {\n throw new WorkflowCompileError(\n `start='${handle.start}' is not the first step — structured-subset runs in order`,\n )\n }\n const ctx: Ctx = { opts, knownStepIds: collectStepIds(steps) }\n // `result` is the optional output value-expression (AIP-15): map it through\n // the same ref grammar as a step's inputs. Absent ⇒ no output selector, so\n // runWorkflow falls back to the final step's result.\n const result = (handle as { result?: unknown }).result\n const output =\n result !== undefined ? (b: Bindings) => resolveValue(result, b) : undefined\n // `finally`: entry-authored cleanup steps that always run (see\n // `RuntimeWorkflow.finally`). They may read any main step's output.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const finallySteps = (handle as { finally?: any[] }).finally\n const finallyCtx: Ctx = finallySteps?.length\n ? { opts, knownStepIds: new Set([...ctx.knownStepIds, ...collectStepIds(finallySteps)]) }\n : ctx\n // AIP-58 §4 — `outputsFiles` (AIP-16, amended with `required`) survives\n // unchanged onto the compiled RuntimeWorkflow; `checkOutputsFiles`\n // (run-workflow.ts) reads it once every top-level step has finished.\n const outputsFiles = (\n handle as { outputsFiles?: Record<string, { path: string; required?: boolean; contentType?: string }> }\n ).outputsFiles\n return {\n id: handle.id,\n description: handle.description,\n steps: compileSiblingsToSteps(steps, ctx),\n ...(finallySteps?.length ? { finally: compileSiblingsToSteps(finallySteps, finallyCtx) } : {}),\n ...(output ? { output } : {}),\n ...(outputsFiles ? { outputsFiles } : {}),\n }\n}\n\n/**\n * Compile a sibling step list in document order. A `kind:\"branch\"` step\n * owns the siblings that form its arm bodies: an exclusive branch (the\n * default — see {@link compileExclusiveBranch}) compiles to one runtime node\n * and the walk resumes at its join point; a legacy `fallthrough: true`\n * branch swallows every sibling after it (see {@link compileBranchChain}),\n * so the walk stops there.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileSiblingsToSteps(steps: any[], ctx: Ctx): RunStep[] {\n assertLinear(steps)\n const out: RunStep[] = []\n for (let i = 0; i < steps.length; i++) {\n const s = steps[i]\n if (s.kind === \"branch\") {\n if (s.fallthrough === true) {\n out.push(compileBranchChain(steps, i, ctx))\n return out\n }\n const { node, joinIdx } = compileExclusiveBranch(steps, i, ctx)\n out.push(node)\n i = joinIdx - 1\n continue\n }\n out.push(compileStep(s, ctx))\n }\n return out\n}\n\nfunction compileStepList(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n steps: any[],\n id: string,\n ctx: Ctx,\n): RunStep {\n const compiled = compileSiblingsToSteps(steps, ctx)\n if (compiled.length === 1) return compiled[0]!\n return { kind: \"group\", id, steps: compiled }\n}\n\n/** Resolve a branch `next`/`default`/`join` id to its index in `steps`,\n * which MUST be a later sibling of the branch at index `i`. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction resolveBranchTarget(steps: any[], i: number, targetId: string, label: string): number {\n const idx = steps.findIndex((s) => s.id === targetId)\n if (idx === -1 || idx <= i) {\n throw new WorkflowCompileError(\n `branch '${steps[i].id}' ${label} targets '${targetId}', which is not a sibling later in this ` +\n `step list — the forward-only branch compiler only supports jumping to a later sibling in the ` +\n `SAME list (not backward, and not into a nested map/loop/parallel body). Hand-author a 'loop' ` +\n `step for retry-style control flow instead.`,\n )\n }\n return idx\n}\n\n/**\n * Compile an exclusive `kind:\"branch\"` step (index `i` in `steps`) — the\n * default branch semantics. Every arm target (`branches[].next`, `default`)\n * MUST be a later sibling in this SAME list. Sorted by position, the targets\n * partition the siblings after the branch into arm BODIES:\n *\n * - an arm's body is its target sibling up to (not including) the next\n * arm's target — or, for the last arm, up to the JOIN;\n * - the join is the explicit `join:` sibling id if declared, else the\n * sibling right after the last arm's target (so without `join:` the\n * last arm's body is exactly its target step);\n * - with no `default`, a no-match runs the siblings between the branch\n * and the first arm target (the implicit default body — empty when the\n * first target is the very next sibling). An explicit `default` makes\n * those siblings unreachable, which fails compilation.\n *\n * Exactly one arm body runs (first truthy `when`, else the default body);\n * the caller resumes the walk at the join, so every sibling from the join on\n * runs once, whichever arm was taken. Arms sharing a target share a body.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileExclusiveBranch(steps: any[], i: number, ctx: Ctx): { node: RunStep; joinIdx: number } {\n const branchStep = steps[i]\n const branches = f<{ when: string; next: string }[]>(branchStep, \"branches\")\n const defaultTarget = f<string | undefined>(branchStep, \"default\")\n const joinTarget = f<string | undefined>(branchStep, \"join\")\n\n const armIdx = branches.map((br, k) => resolveBranchTarget(steps, i, br.next, `branches[${k}].next`))\n const defaultIdx =\n defaultTarget !== undefined ? resolveBranchTarget(steps, i, defaultTarget, \"default\") : undefined\n const starts = [...new Set([...armIdx, ...(defaultIdx !== undefined ? [defaultIdx] : [])])].sort(\n (a, b) => a - b,\n )\n const lastStart = starts[starts.length - 1]!\n const joinIdx =\n joinTarget !== undefined ? resolveBranchTarget(steps, i, joinTarget, \"join\") : lastStart + 1\n if (joinIdx <= lastStart) {\n throw new WorkflowCompileError(\n `branch '${branchStep.id}' join '${joinTarget}' must come after every arm target — ` +\n `'${steps[lastStart].id}' is an arm target at or after it`,\n )\n }\n if (defaultIdx !== undefined && starts[0]! > i + 1) {\n throw new WorkflowCompileError(\n `branch '${branchStep.id}': step '${steps[i + 1].id}' sits between the branch and its first arm ` +\n `target and belongs to no arm — with an explicit 'default' it can never run. Move it after the ` +\n `join, or make it an arm target.`,\n )\n }\n\n // One compiled body per distinct start index, so arms sharing a target\n // share the exact same RunStep objects.\n const bodies = new Map<number, RunStep[]>()\n const bodyAt = (start: number): RunStep[] => {\n let body = bodies.get(start)\n if (!body) {\n const pos = starts.indexOf(start)\n const end = pos + 1 < starts.length ? starts[pos + 1]! : joinIdx\n body = compileSiblingsToSteps(steps.slice(start, end), ctx)\n bodies.set(start, body)\n }\n return body\n }\n\n let otherwise: RunStep[] =\n defaultIdx !== undefined\n ? bodyAt(defaultIdx)\n : compileSiblingsToSteps(steps.slice(i + 1, starts[0]), ctx)\n for (let k = branches.length - 1; k >= 0; k--) {\n const condExpr = branches[k]!.when\n otherwise = [\n {\n kind: \"branch\",\n id: k === 0 ? branchStep.id : `${branchStep.id}__branch${k}`,\n ...(k === 0 ? {} : { sourceId: branchStep.id }),\n cond: (b: Bindings) => evalPredicate(condExpr, b),\n then: bodyAt(armIdx[k]!),\n ...(otherwise.length > 0 ? { otherwise } : {}),\n },\n ]\n }\n return { node: otherwise[0]!, joinIdx }\n}\n\n/**\n * Compile a legacy `fallthrough: true` `kind:\"branch\"` step (index `i` in\n * `steps`) into a nested runtime {@link BranchStep} chain: `branches[]`\n * evaluate in order, the first truthy `when` jumps to its `next` sibling and\n * falls through in document order from there (running every later arm's\n * steps too); no match jumps to `default` (or falls through to `i + 1`).\n * Every target MUST be a later sibling in this SAME list.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileBranchChain(steps: any[], i: number, ctx: Ctx): RunStep {\n const branchStep = steps[i]\n const branches = f<{ when: string; next: string }[]>(branchStep, \"branches\")\n const defaultTarget = f<string | undefined>(branchStep, \"default\")\n if (f<string | undefined>(branchStep, \"join\") !== undefined) {\n throw new WorkflowCompileError(\n `branch '${branchStep.id}' declares both 'fallthrough: true' and 'join' — a fall-through ` +\n `branch runs every later sibling, so it has no join point`,\n )\n }\n const resolveTarget = (targetId: string, label: string): number =>\n resolveBranchTarget(steps, i, targetId, label)\n\n const defaultIdx = defaultTarget !== undefined ? resolveTarget(defaultTarget, \"default\") : i + 1\n let otherwise: RunStep[] = compileSiblingsToSteps(steps.slice(defaultIdx), ctx)\n\n for (let k = branches.length - 1; k >= 0; k--) {\n const br = branches[k]!\n const targetIdx = resolveTarget(br.next, `branches[${k}].next`)\n const thenSteps = compileSiblingsToSteps(steps.slice(targetIdx), ctx)\n const condExpr = br.when\n const nodeId = k === 0 ? branchStep.id : `${branchStep.id}__branch${k}`\n otherwise = [\n {\n kind: \"branch\",\n id: nodeId,\n ...(k === 0 ? {} : { sourceId: branchStep.id }),\n cond: (b: Bindings) => evalPredicate(condExpr, b),\n then: thenSteps,\n ...(otherwise.length > 0 ? { otherwise } : {}),\n },\n ]\n }\n return otherwise[0]!\n}\n\n/** `true` when `value` already satisfies {@link OutputSchemaLike} — e.g. a\n * zod `ZodType` a TS-authored step (`buildAgentStep` callers, `entry.mjs`)\n * passed directly. A function-valued `safeParse` member is sufficient,\n * since that's the only member `execAgentStep` ever calls. */\nfunction hasSafeParse(value: unknown): value is OutputSchemaLike {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === \"function\"\n )\n}\n\n/**\n * Adapt a WORKFLOW.md-authored `outputSchema` — plain JSON Schema, the only\n * shape YAML frontmatter can express — into the {@link OutputSchemaLike}\n * `execAgentStep` calls `.safeParse` on, backed by the same ajv instance\n * `validate-input.ts` already uses for run-input validation. Without this\n * adapter, a manifest-declared `outputSchema` reaches `execAgentStep` as a\n * bare object with no `safeParse` method at all, and the AIP-58 §3\n * missing-output check throws instead of validating. An uncompilable\n * schema fails HERE, at compile time, never at the runtime spawn.\n */\nfunction compileOutputSchema(schema: unknown, stepId: string): OutputSchemaLike {\n if (!isCompilableJsonSchema(schema)) {\n throw new WorkflowCompileError(\n `agent step '${stepId}' has an invalid 'outputSchema' — not a compilable JSON Schema`,\n )\n }\n return {\n safeParse: (value: unknown) => {\n const result = validateAgainstJsonSchema(schema, value)\n return result.valid\n ? { success: true as const, data: value }\n : { success: false as const, error: { issues: result.issues } }\n },\n // F27: lets `describeOutputSchemaForPrompt` (run-workflow.ts) render the\n // EXACT WORKFLOW.md-authored schema into the agent's prompt.\n jsonSchema: schema,\n }\n}\n\n/**\n * Compile a declarative `kind:\"agent\"` manifest step — `{ agent: { ref },\n * prompt, adapter?, sessionRef?, sandbox?, cacheable?, policy?, outputSchema?,\n * maxRetries? }` — into a real {@link AgentStep}. `prompt` runs through the\n * same `$input`/`$steps.<id>` ref grammar as a `tool` step's `inputs`.\n * `agent.ref` resolves via `opts.agentRefs` — unresolvable (no map, or an id\n * the map doesn't have) fails HERE, at compile time, never at the runtime\n * spawn.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileAgentStep(step: any, id: string, ctx: Ctx): AgentStep {\n const opts = ctx.opts\n const prompt = f<string>(step, \"prompt\")\n if (typeof prompt !== \"string\" || prompt.length === 0) {\n throw new WorkflowCompileError(`agent step '${id}' needs a non-empty 'prompt'`)\n }\n\n let adapter: string | undefined = typeof step.adapter === \"string\" ? step.adapter : undefined\n let options: Record<string, boolean | number | string> | undefined =\n step.options !== undefined ? step.options : undefined\n let model: unknown = step.model\n let agentTools: readonly string[] | undefined\n\n const agentRef: unknown = step.agent?.ref\n if (agentRef !== undefined) {\n if (typeof agentRef !== \"string\" || agentRef.trim().length === 0) {\n throw new WorkflowCompileError(`agent step '${id}' has an empty 'agent.ref'`)\n }\n const resolved = opts.agentRefs ? get(opts.agentRefs, agentRef) : undefined\n if (!resolved) {\n const available = opts.agentRefs\n ? opts.agentRefs instanceof Map\n ? [...opts.agentRefs.keys()]\n : Object.keys(opts.agentRefs)\n : []\n throw new WorkflowCompileError(\n `agent step '${id}' references unknown agent ref '${agentRef}'` +\n (available.length > 0\n ? ` — available refs: ${available.join(\", \")}`\n : \" — no agent refs are configured for this compile (not running in an app context?)\"),\n )\n }\n // An explicit step-level declaration is the author's override; the\n // agent-ref resolution only supplies the DEFAULT.\n if (adapter === undefined) adapter = resolved.adapter\n if (model === undefined) model = resolved.model\n // `resolved.options` is shaped for `resolved.adapter` specifically (e.g.\n // mastra-agent's `agent` option) — only apply it when the step ends up\n // spawning THAT adapter. A step-level `adapter:` override to a\n // DIFFERENT adapter must not inherit an option id the new adapter's own\n // manifest never declared (the spawn rejects it loudly — see F26's\n // `resolveAgentRefsForWorkflow` doc).\n if (options === undefined && adapter === resolved.adapter) options = resolved.options\n // The agent's declared tools travel with it whatever adapter runs it —\n // they scope the host's tool gateway, not an adapter option.\n agentTools = resolved.tools\n }\n\n // AIP-58 §3 Outcome rule: a step declaring NEITHER an output schema NOR a\n // required artifact (artifacts are P4, not checked here) has a vacuous\n // contract — its turn ending is unconditional success, and this runtime\n // can never detect a missing output for it. Warn once per step at compile\n // time (never at runtime, and never a thrown error — existing manifests\n // that never declared one keep working exactly as before).\n let outputSchema: OutputSchemaLike | undefined\n if (step.outputSchema === undefined) {\n console.warn(\n `[workflow-runtime] agent step '${id}' declares no output contract; AIP-58 cannot detect a missing output`,\n )\n } else if (hasSafeParse(step.outputSchema)) {\n // A TS-authored step (or an `entry.mjs` handle) passed a zod schema (or\n // anything else already `safeParse`-shaped) directly — use it as-is.\n outputSchema = step.outputSchema\n } else {\n // WORKFLOW.md YAML frontmatter can only express plain JSON Schema —\n // adapt it so `execAgentStep`'s `.safeParse` call works the same way\n // it does for a TS-authored zod schema.\n outputSchema = compileOutputSchema(step.outputSchema, id)\n }\n\n // `cwd`: a selector function (entry handles) passes through; a string\n // resolves through the same `$input`/`$steps.<id>` ref grammar as a gate\n // step's cwd (a literal path passes through unchanged).\n const rawCwd: unknown = step.cwd\n const cwd: Selector<string> | undefined =\n typeof rawCwd === \"function\"\n ? (rawCwd as Selector<string>)\n : typeof rawCwd === \"string\"\n ? (b: Bindings) => resolveRefString(id, \"cwd\", rawCwd, b, \"error\")\n : undefined\n\n return buildAgentStep(id, {\n prompt: (b: Bindings) => renderPrompt(prompt, b),\n ...(adapter !== undefined ? { adapter } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n ...(step.sessionRef !== undefined ? { sessionRef: step.sessionRef } : {}),\n ...(model !== undefined ? { model: model as Selector<string> | string } : {}),\n ...(step.sandbox !== undefined ? { sandbox: step.sandbox } : {}),\n ...(step.cacheable ? { cacheable: true } : {}),\n ...(options !== undefined ? { options } : {}),\n policy: step.policy,\n ...(outputSchema !== undefined ? { outputSchema } : {}),\n ...(step.maxRetries !== undefined ? { maxRetries: step.maxRetries } : {}),\n ...(step.harness !== undefined ? { harness: step.harness } : {}),\n ...(agentTools !== undefined ? { agentTools } : {}),\n })\n}\n\n/**\n * Compile a declarative `kind:\"gate\"` manifest step — `{ command, args?,\n * cwd?, report?, timeout_ms?, retry?, on_fail? }` — into a real\n * {@link GateStep}. `command` is re-validated here (compile time) even\n * though `@agentproto/workflow`'s `defineWorkflow` already rejects an\n * empty one at LOAD time — an ENTRY-based handle that hand-builds a gate\n * step in TS bypasses that manifest-only check.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileGateStep(step: any, id: string): GateStep {\n const command = f<string>(step, \"command\")\n if (typeof command !== \"string\" || command.trim().length === 0) {\n throw new WorkflowCompileError(`gate step '${id}' needs a non-empty 'command'`)\n }\n const args = f<string[] | undefined>(step, \"args\")\n const cwd = f<string | undefined>(step, \"cwd\")\n const reportPath = f<string | undefined>(step, \"report\")\n const timeoutMs = assertStepTimeoutMs(id, \"gate\", step.timeout_ms)\n const retry = f<\n { max_attempts: number; backoff: \"fixed\" | \"exponential\"; initial_ms?: number } | undefined\n >(step, \"retry\")\n const onFail = f<{ reprompt: string; with?: Record<string, unknown> } | undefined>(\n step,\n \"on_fail\",\n )\n return {\n kind: \"gate\",\n id,\n command,\n ...(args !== undefined ? { args } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n ...(reportPath !== undefined ? { reportPath } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n ...(retry !== undefined\n ? {\n retry: {\n maxAttempts: retry.max_attempts,\n backoff: retry.backoff,\n ...(retry.initial_ms !== undefined ? { initialMs: retry.initial_ms } : {}),\n },\n }\n : {}),\n ...(onFail !== undefined\n ? { onFail: { reprompt: onFail.reprompt, ...(onFail.with !== undefined ? { with: onFail.with } : {}) } }\n : {}),\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction compileStep(step: any, ctx: Ctx): RunStep {\n const opts = ctx.opts\n const id: string = step.id\n switch (step.kind) {\n case \"tool\": {\n const ref = typeof step.tool === \"string\" ? step.tool : step.tool.entry\n const toolId = normalizeToolId(ref)\n const tool = get(opts.tools, toolId)\n if (!tool)\n throw new WorkflowCompileError(`no tool registered for '${toolId}'`)\n const inputs = f<unknown>(step, \"inputs\") ?? {}\n assertKnownStepRefs(inputs, ctx.knownStepIds, `tool step '${id}' inputs`, {\n makeError: (message) => new WorkflowCompileError(message),\n })\n const timeoutMs = assertStepTimeoutMs(id, \"tool\", step.timeout_ms)\n return {\n kind: \"tool\",\n id,\n tool,\n candidates: opts.candidates,\n input: (b) => resolveValue(inputs, b),\n context: opts.contextFor\n ? (b) => opts.contextFor!(toolId, b)\n : undefined,\n ...(step.cacheable ? { cacheable: true } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n }\n }\n\n case \"map\": {\n const over = f<string>(step, \"over\")\n const inner = compileStepList(f(step, \"steps\"), `${id}__body`, ctx)\n const onError = f<\"throw\" | \"collect\" | undefined>(step, \"onError\")\n const maxConsecutiveSpawnFailures = f<number | undefined>(step, \"maxConsecutiveSpawnFailures\")\n return {\n kind: \"map\",\n id,\n parallelism: f<number | undefined>(step, \"parallelism\"),\n over: (b) => resolveRef(over, b) as readonly unknown[],\n body: () => inner,\n ...(onError !== undefined ? { onError } : {}),\n ...(maxConsecutiveSpawnFailures !== undefined ? { maxConsecutiveSpawnFailures } : {}),\n }\n }\n\n case \"loop\": {\n const whileExpr = f<string>(step, \"while\")\n return {\n kind: \"loop\",\n id,\n maxIterations: f<number>(step, \"max_iterations\"),\n while: (b) => evalPredicate(whileExpr, b),\n body: [compileStepList(f(step, \"steps\"), `${id}__body`, ctx)],\n }\n }\n\n case \"parallel\": {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const branches = f<any[]>(step, \"branches\")\n return {\n kind: \"parallel\",\n id,\n branches: branches.map((br) => ({\n id: br.id,\n steps: [compileStepList(br.steps, `${id}__${br.id}`, ctx)],\n })),\n }\n }\n\n case \"approval\": {\n const prompt = f<string>(step, \"prompt\")\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const approvers = (f<any[]>(step, \"approvers\") ?? []).map(\n (a) => a.role ?? a.userId ?? String(a),\n )\n const artifacts = f<string[]>(step, \"artifacts\")\n const timeoutMs = f<number>(step, \"timeout_ms\")\n return {\n kind: \"approval\",\n id,\n approvers,\n ...(artifacts !== undefined ? { artifacts } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n prompt: (b) => renderPrompt(prompt, b),\n }\n }\n\n case \"suspend\": {\n const resume = f<{ on: string[]; timeout_ms?: number }>(step, \"resume\")\n return { kind: \"suspend\", id, on: resume.on, timeoutMs: resume.timeout_ms }\n }\n\n case \"subworkflow\": {\n const wfId = f<string>(step, \"workflow\")\n const child = opts.workflows ? get(opts.workflows, wfId) : undefined\n if (!child)\n throw new WorkflowCompileError(\n `subworkflow '${wfId}' not found — pass it in opts.workflows`,\n )\n const compiledChild = compileWorkflow(child, opts)\n // `inputs` is an optional projection into the child's `$input` — the\n // same ref grammar as a `tool` step's `inputs` (refs resolved against\n // THIS (parent) workflow's bindings). Absent ⇒ today's behavior: the\n // child runs with the parent's own workflow input, unchanged.\n const inputs = f<unknown>(step, \"inputs\")\n if (inputs === undefined) {\n return { kind: \"subworkflow\", id, workflow: compiledChild }\n }\n assertKnownStepRefs(inputs, ctx.knownStepIds, `subworkflow step '${id}' inputs`, {\n makeError: (message) => new WorkflowCompileError(message),\n })\n const entries = Object.entries(inputs as Record<string, unknown>)\n return {\n kind: \"subworkflow\",\n id,\n workflow: compiledChild,\n // Each top-level key resolves strictly: a missing referenced field\n // throws at run time naming this step + key (no silent `undefined`).\n input: (b) => {\n const out: Record<string, unknown> = {}\n for (const [k, v] of entries)\n out[k] = resolveValueStrict(v, b, `subworkflow step '${id}' input key '${k}'`)\n return out\n },\n }\n }\n\n case \"agent\": {\n // Two shapes reach here under the same `kind:\"agent\"`: an ENTRY-based\n // handle's already-built runtime AgentStep (function-valued `prompt`\n // selector — nothing declarative left to resolve, pass through\n // unchanged), or a purely-declarative manifest step (`prompt` is a\n // plain string) that this compiler must turn into a real AgentStep,\n // the same way `translateStages` does for `workflow_start`.\n if (typeof step.prompt === \"function\") {\n const passthrough: RunStep = step\n return passthrough\n }\n return compileAgentStep(step, id, ctx)\n }\n\n case \"gate\":\n return compileGateStep(step, id)\n\n case \"artifact\": {\n // Entry-based handles may pass an already-built ArtifactStep straight\n // through (function-valued key/path); a declarative WORKFLOW.md step\n // gives plain strings — `path` resolves through the same `$…`\n // ref-string grammar a gate step's `cwd` uses (a literal path passes\n // through unchanged).\n if (typeof step.key === \"function\" || typeof step.path === \"function\") {\n const passthrough: RunStep = step\n return passthrough\n }\n const key = f<string>(step, \"key\")\n const rawPath = f<string>(step, \"path\")\n if (typeof key !== \"string\" || key.trim().length === 0) {\n throw new WorkflowCompileError(`artifact step '${id}' needs a non-empty 'key'`)\n }\n if (typeof rawPath !== \"string\" || rawPath.trim().length === 0) {\n throw new WorkflowCompileError(`artifact step '${id}' needs a non-empty 'path'`)\n }\n const contentType = f<string | undefined>(step, \"contentType\")\n return {\n kind: \"artifact\",\n id,\n key,\n path: (b: Bindings) => resolveRefString(id, \"path\", rawPath, b, \"error\"),\n ...(contentType !== undefined ? { contentType } : {}),\n }\n }\n\n case \"transform\": {\n // Not a declarative manifest kind — no string expression language for\n // `compute` — so it only reaches the compiler from an ENTRY-based\n // handle, already built as a runtime TransformStep (function-valued\n // `compute`). Passes through unchanged: this is what lets an entry.mjs\n // step shape/serialize an earlier tool step's output (e.g.\n // `JSON.stringify` a prior `$steps.<id>` value) for a later tool step\n // to consume as a plain string input, something the `$steps.*` ref\n // grammar alone can't do. `step` is `any`, so no cast is needed.\n const passthrough: RunStep = step\n return passthrough\n }\n\n case \"branch\":\n // Unreachable through the normal entry points: `compileSiblingsToSteps`\n // intercepts every `branch` step (a branch owns its arm-body siblings,\n // so it can only be compiled with the whole sibling list in view). A\n // direct call would be an internal invariant violation, not a\n // manifest problem.\n throw new WorkflowCompileError(\n `internal: branch step '${id}' reached compileStep directly — branch ` +\n `steps must be compiled via the sibling-list walker`,\n )\n\n default:\n throw new WorkflowCompileError(\n `unsupported step kind '${step.kind}' (step '${id}')`,\n )\n }\n}\n","/**\n * The shared string-ref resolver (AIP-16 ref grammar): ONE implementation for\n * every field that accepts \"a string that may START with a `$…` run-time\n * reference plus trailing literal text\" — `harness.knowledge[]` selector\n * strings, a `kind:\"gate\"` step's `args[]`, and its `cwd`.\n */\n\nimport { resolveRefPrefixed } from \"./compile-workflow.js\"\nimport type { Bindings } from \"./types.js\"\n\n/**\n * Resolve one string against the run bindings. Rule: refs are only\n * recognized at the START of the string. The leading reference token — the\n * shared AIP-16 prefix grammar in {@link resolveRefPrefixed} (it stops at\n * the first `/`, e.g. `$input.bookDir` in `$input.bookDir/knowledge`) — is\n * resolved against the bindings and `String()`-ed; the remainder of the\n * string is appended verbatim. A string that is exactly a ref resolves to\n * that value's string form. `$$` escapes to a literal `$`. A string without\n * a leading ref passes through untouched — unless `onUnmatched` is\n * `\"error\"` and the string starts with a `$` that does not open a known ref\n * token, in which case it throws (the gate `args`/`cwd` behavior: a literal\n * `$foo` handed to a subprocess is always a footgun, never intended). An\n * unresolvable or malformed ref throws naming the step and `field`\n * (e.g. `harness.knowledge[0].workspace`, `args[2]`, `cwd`).\n */\nexport function resolveRefString(\n stepId: string,\n field: string,\n value: string,\n b: Bindings,\n onUnmatched: \"passthrough\" | \"error\" = \"passthrough\",\n): string {\n if (value.startsWith(\"$$\")) return value.slice(1)\n let hit: ReturnType<typeof resolveRefPrefixed>\n try {\n hit = resolveRefPrefixed(value, b)\n } catch (err) {\n throw new Error(\n `step '${stepId}': ${field} '${value}' is not a valid reference — ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n if (!hit) {\n if (onUnmatched === \"error\" && value.startsWith(\"$\")) {\n throw new Error(\n `step '${stepId}': ${field} '${value}' is not a valid reference — a leading '$' must open a $input/$item/$steps.<id>/$index reference ('$$' escapes a literal '$')`,\n )\n }\n return value\n }\n const token = value.slice(0, value.length - hit.rest.length)\n if (hit.resolved === undefined) {\n throw new Error(\n `step '${stepId}': ${field} '${token}' resolves to nothing — the referenced field does not exist`,\n )\n }\n return String(hit.resolved) + hit.rest\n}\n","/**\n * Typed step algebra for AIP-15 WORKFLOW execution.\n *\n * The AIP-15 manifest leaves the IO-threading (`step.inputs`, `map.over`,\n * `branch.when`, `loop.while`) to a meta-validator — it never pins an\n * expression language. Rather than invent a stringly DSL, this runtime\n * expresses the AIP-16 IO seam as **typed selectors**: each step reads the\n * run-scoped {@link Bindings} (workflow input + every prior step's output, plus\n * the current item inside a `map`) through a plain `(bindings) => value`\n * function. Authoring stays in TypeScript; compiling a declarative manifest's\n * reference strings onto these selectors is a separable follow-up.\n */\n\nimport type { DriverHandle, ResolverContext } from \"@agentproto/driver\"\nimport type { ToolContext, ToolHandle } from \"@agentproto/tool\"\n\n/** The run-scoped data every selector reads from. */\nexport interface Bindings {\n /** The workflow's invocation input. */\n readonly input: unknown\n /** Each completed top-level step's output, keyed by step id. */\n readonly steps: Readonly<Record<string, unknown>>\n /** Present inside a `map` body — the element being processed. */\n readonly item?: unknown\n /** Present inside a `map` body — the element's index. */\n readonly index?: number\n /** AIP-58 §4 Run workspace — present when the host wires\n * {@link RunWorkflowArgs.workspace}. `$run.workspace` / `{{run.workspace}}`\n * is a convenience alias for the same absolute path AIP-16 injects as\n * `$input._workflowFsRoot` — steps may use either. */\n readonly run?: { readonly workspace: string }\n}\n\n/** The AIP-16 IO seam: read a value out of the run bindings. */\nexport type Selector<T> = (bindings: Bindings) => T\n\n/** Run a TOOL contract through the resolver; its output binds under `id`. */\nexport interface ToolStep<\n TInput = unknown,\n TOutput = unknown,\n TContext extends ToolContext = ToolContext,\n> {\n kind: \"tool\"\n id: string\n tool: ToolHandle<TInput, TOutput, TContext>\n candidates: readonly DriverHandle[]\n /** Derive the tool input from the run bindings. */\n input: Selector<TInput>\n /** Derive the injected per-call context (live capabilities) from bindings. */\n context?: Selector<TContext>\n resolverContext?: ResolverContext\n secrets?: Record<string, string>\n /** Cache this step's output under the run's cacheKey; only its `input` is hashed\n * (not `context`/secrets). Default false. */\n cacheable?: boolean\n /** Hard wall-clock cap for this step's dispatch (driver resolve + execute),\n * in ms. Bounds a driver that never settles its own promise (e.g. a `kind:\n * cli` subprocess whose stdio pipe is held open by an orphaned grandchild\n * process — F45) rather than relying on the driver to self-timeout.\n * Default {@link DEFAULT_STEP_TIMEOUT_MS} when unset. */\n timeoutMs?: number\n}\n\n/** A pure in-run computation (combine / filter / shape) — no tool dispatch. */\nexport interface TransformStep {\n kind: \"transform\"\n id: string\n compute: Selector<unknown>\n}\n\n/**\n * One item's outcome inside a `map`/`pipeline` run with `onError: \"collect\"`.\n * Mirrors `Promise.allSettled`'s fulfilled/rejected split so a caller can tell\n * a legitimate `undefined` body output apart from a failure at that index.\n */\nexport type FanOutOutcome<T = unknown> =\n | { readonly status: \"fulfilled\"; readonly index: number; readonly value: T }\n | {\n readonly status: \"rejected\"\n readonly index: number\n readonly item: unknown\n /** `err.message` if the throw was an `Error`, else `String(err)`. */\n readonly error: string\n }\n | {\n /** Never started: either the fan-out's spawn circuit breaker opened\n * first (see {@link MapStep.maxConsecutiveSpawnFailures}), or the run\n * was cancelled while earlier items were still in flight. */\n readonly status: \"skipped\"\n readonly index: number\n readonly item: unknown\n /** `circuit-open: <first error of the failure streak>`, or\n * `run-cancelled: run cancelled`. */\n readonly reason: string\n }\n\n/**\n * The bound output of a `map`/`pipeline` step run with `onError: \"collect\"`:\n * every item's outcome, plus the counts a caller needs to answer \"how many\n * failed and why\" without re-scanning `results`.\n */\nexport interface TolerantFanOutResult<T = unknown> {\n readonly results: readonly FanOutOutcome<T>[]\n readonly succeeded: number\n readonly failed: number\n /** Items never started because the spawn circuit breaker opened. */\n readonly skipped: number\n /** Set when the breaker opened: the first error of the spawn-failure\n * streak that tripped it. */\n readonly circuitOpen?: { readonly error: string }\n}\n\n/** Default for {@link MapStep.maxConsecutiveSpawnFailures} /\n * {@link PipelineStep.maxConsecutiveSpawnFailures}. */\nexport const DEFAULT_MAX_CONSECUTIVE_SPAWN_FAILURES = 3\n\n/** Default for {@link ToolStep.timeoutMs} / {@link GateStep.timeoutMs} when\n * the step declares none — 10 minutes. Bounds an otherwise-unbounded `tool`\n * or `gate` step dispatch (F45). */\nexport const DEFAULT_STEP_TIMEOUT_MS = 10 * 60 * 1000\n\n/**\n * Run a sub-step once per element of an array, optionally with bounded\n * concurrency. The element + index are exposed to the body via `bindings.item`\n * / `bindings.index`; the collected outputs bind under this step's id.\n */\nexport interface MapStep {\n kind: \"map\"\n id: string\n over: Selector<readonly unknown[]>\n /** Max concurrent bodies (default 1 = sequential). */\n parallelism?: number\n body: (item: unknown, index: number, bindings: Bindings) => RunStep\n /**\n * `\"throw\"` (default): the first item to throw aborts the whole map — the\n * step's output is a bare array, one entry per item, same as before this\n * field existed. `\"collect\"`: every item runs to completion; the step's\n * output becomes a {@link TolerantFanOutResult} instead of a bare array, so\n * a failure is visible to the caller rather than aborting or getting\n * silently dropped.\n */\n onError?: \"throw\" | \"collect\"\n /**\n * `\"collect\"` only: once this many items IN A ROW fail because an agent\n * step's session could not be spawned ({@link AgentSpawnError}), stop\n * starting new items — the failure is systemic, not per-item. In-flight\n * items finish; every item not yet started is reported skipped\n * (`circuit-open: <first error>`) and the map returns normally. A settled\n * item that isn't a spawn failure resets the streak. Default\n * {@link DEFAULT_MAX_CONSECUTIVE_SPAWN_FAILURES}; `0` disables the breaker.\n * (`\"throw\"` already stops at the first failure of any kind.)\n */\n maxConsecutiveSpawnFailures?: number\n}\n\n/**\n * Run N items through K sequential stage bodies with NO cross-item barrier:\n * each item flows through the stages as its own chain, independent of siblings.\n * Only `concurrency` (max item-chains in flight) is shared. The per-item final\n * output binds under this step's id, ordered by the item's index.\n */\nexport interface PipelineStep {\n kind: \"pipeline\"\n id: string\n over: Selector<readonly unknown[]>\n /** Max concurrent item-chains (default: all items at once). */\n concurrency?: number\n /** Ordered stage bodies; each item flows through them in order. `prevOutput`\n * is the previous stage's output for THIS item (undefined for stage 0). */\n stages: readonly ((\n item: unknown,\n index: number,\n prevOutput: unknown,\n bindings: Bindings,\n ) => RunStep)[]\n /** Same semantics as {@link MapStep.onError}: `\"throw\"` (default) aborts\n * the whole pipeline on the first item whose chain throws at any stage;\n * `\"collect\"` runs every item's chain to completion and binds a\n * {@link TolerantFanOutResult} instead of a bare array. */\n onError?: \"throw\" | \"collect\"\n /** Same semantics as {@link MapStep.maxConsecutiveSpawnFailures}. */\n maxConsecutiveSpawnFailures?: number\n}\n\n/** Run one of two branches based on a predicate over the bindings. */\nexport interface BranchStep {\n kind: \"branch\"\n id: string\n cond: Selector<boolean>\n then: readonly RunStep[]\n otherwise?: readonly RunStep[]\n /** The authored step this node was compiled from, when it differs from\n * `id` — a multi-arm manifest `kind: branch` compiles to a chain of\n * nodes (`<id>`, `<id>__branch1`, …); skip reports name `<id>`. */\n sourceId?: string\n}\n\n/** Repeat a body while a predicate holds, up to a hard iteration ceiling. */\nexport interface LoopStep {\n kind: \"loop\"\n id: string\n while: Selector<boolean>\n maxIterations: number\n body: readonly RunStep[]\n}\n\n/** Run several independent branches concurrently; outputs bind by branch id. */\nexport interface ParallelStep {\n kind: \"parallel\"\n id: string\n branches: readonly { id: string; steps: readonly RunStep[] }[]\n}\n\n/**\n * AIP-7 human-in-the-loop gate. The host's injected `approve` callback decides;\n * the chosen `onApprove` / `onReject` sub-steps then run. Default (no callback)\n * auto-approves. The step's own output is `{ approved }`.\n */\nexport interface ApprovalStep {\n kind: \"approval\"\n id: string\n prompt: Selector<string>\n approvers?: readonly string[]\n /** Artifacts attached to the approval request (e.g. paths to review). */\n artifacts?: readonly string[]\n /** Give up waiting after this long — the step resolves as REJECTED with\n * `who: \"timeout\"` (the host decides; the runtime enforces it). */\n timeoutMs?: number\n onApprove?: readonly RunStep[]\n onReject?: readonly RunStep[]\n}\n\n/**\n * Pause until an external event resumes the run. The host's injected `resume`\n * callback supplies the resume payload (bound under this step's id). With no\n * callback the run throws {@link WorkflowSuspendedError} — the durable-suspend\n * path a host persists and re-enters later.\n */\nexport interface SuspendStep {\n kind: \"suspend\"\n id: string\n on: readonly string[]\n timeoutMs?: number\n}\n\n/** Run an ordered list of steps as one unit; its output is the last step's. */\nexport interface GroupStep {\n kind: \"group\"\n id: string\n steps: readonly RunStep[]\n}\n\n/** Run a nested workflow with its own isolated bindings; its output binds here. */\nexport interface SubworkflowStep {\n kind: \"subworkflow\"\n id: string\n workflow: RuntimeWorkflow\n /** Input for the child (default: the parent's workflow input). */\n input?: Selector<unknown>\n}\n\n/**\n * Harness pinning for an {@link AgentStep}'s spawn (AIP-15 P2) — mirrors\n * `@agentproto/workflow`'s manifest `Harness` block, compiled onto the\n * runtime step. Precedence when a field is also set elsewhere: this block\n * (highest) > the resolved AGENT.md's own frontmatter > `app_run` caller\n * args > the adapter's own default (lowest).\n */\nexport interface AgentHarness {\n /** Model id override for this spawn. */\n model?: string\n /** Reasoning-effort override for this spawn (adapter-defined vocabulary). */\n effort?: string\n /** Spawn-time role — governs the child's tool-policy disposition. */\n role?: string\n /** Per-spawn tool allowlist. Applied where the resolved adapter supports a\n * generic per-spawn allowlist mechanism; where it doesn't, the host MUST\n * record `toolsApplied: false` on the step's output and emit a warning\n * rather than silently ignoring the field. */\n tools?: readonly string[]\n /** Skill ids auto-mounted into the spawn. */\n skills?: readonly string[]\n /** Working directory override for this step's spawn — takes precedence\n * over {@link AgentStep.cwd} and the run-level `ctx.cwd`. */\n cwd?: string\n /** sha256 (hex) of the `harness.promptFile` this step's prompt was read\n * from, computed by `@agentproto/workflow-loader` at load time. Absent\n * when the step's prompt was authored inline. */\n promptSha?: string\n /** AIP-10 corpus knowledge materialized into the step's cwd (under\n * `.knowledge/`) before the session runs. See\n * {@link HarnessKnowledgeSelector}. */\n knowledge?: readonly HarnessKnowledgeSelector[]\n}\n\n/**\n * One AIP-10 corpus workspace attachment on an {@link AgentStep}'s\n * `harness.knowledge[]` — mirrors `@agentproto/workflow`'s manifest\n * `KnowledgeSelector`, with the `workspace` path already resolved to an\n * absolute path by `@agentproto/workflow-loader` (or authored absolute).\n */\nexport interface HarnessKnowledgeSelector {\n /** Absolute path to an AIP-10 corpus workspace root. */\n workspace: string\n /** Tags with OR semantics (maps to `resolveKnowledge`'s `query.tags`). */\n anyOf?: readonly string[]\n /** Tags that must ALL be present (post-filter after `anyOf`). */\n allOf?: readonly string[]\n /** Refined-kind filter. */\n kinds?: readonly string[]\n /** Cap on materialized entries after slug-ascending sort. Default 50. */\n maxEntries?: number\n /** Materialization mode — v1 supports only `\"files\"`. */\n mode?: \"files\"\n /** Internal — set by `@agentproto/workflow-loader` when a selector string\n * carries `$…` run-time references that must be resolved against the run\n * bindings before materialization. Not user-authored; the loader rejects\n * an authored `deferred`, and resolution strips the flag. */\n deferred?: boolean\n}\n\n/** Per-selector materialization record on an agent step's run output. */\nexport interface KnowledgeAppliedRecord {\n /** The (absolute) corpus workspace root the selector resolved against. */\n workspace: string\n /** Entries matching the selector after allOf + kind filtering. */\n matched: number\n /** Entries actually written (≤ matched, after the `maxEntries` cap). */\n written: number\n}\n\n/**\n * Where an {@link AgentStep}'s session runs when not on the host: a sandbox\n * provider slug (e.g. `\"local\"`, `\"e2b\"`) or an inline AIP-36 SandboxSpec-like\n * object (`{ provider, config, env?, … }`). This runtime stays structural —\n * the injected {@link AgentSessionHost} interprets the value (the daemon host\n * forwards it to the same sandbox boot path `agent_start.sandbox` uses).\n */\nexport type AgentSandboxRef = string | { provider: string; [k: string]: unknown }\n\n/**\n * The minimal structural contract {@link AgentStep.outputSchema} must\n * satisfy — exactly the `safeParse` shape `execAgentStep` consumes (never\n * `.parse`, `._def`, or any other zod-specific member). A real zod\n * `ZodType` satisfies this automatically (structural typing — zod's own\n * `SafeParseReturnType` is a superset of this shape), so a TS-authored step\n * can still pass a zod schema directly. `compileAgentStep` additionally\n * builds one of these from a WORKFLOW.md-authored JSON Schema object (ajv\n * `validateAgainstJsonSchema`-backed) for the declarative manifest path,\n * where `outputSchema` is plain JSON Schema, not a zod instance.\n */\nexport interface OutputSchemaLike {\n safeParse(value: unknown):\n | { success: true; data: unknown }\n | { success: false; error: { issues: readonly { path: readonly PropertyKey[]; message: string }[] } }\n /** Set by `compileAgentStep`'s declarative (WORKFLOW.md) path to the raw\n * JSON Schema object it wrapped — lets F27's prompt-affordance render the\n * EXACT schema text instead of re-deriving it from the `safeParse`\n * closure. Absent on a TS-authored zod schema (rendered via\n * `z.toJSONSchema` instead — see `describeOutputSchemaForPrompt`). */\n jsonSchema?: unknown\n}\n\n/**\n * Spawn or reuse an agent session and send it a prompt, waiting for the\n * turn to complete. The host injects an {@link AgentSessionHost} — this\n * runtime has no knowledge of concrete session registries or event buses.\n */\nexport interface AgentStep {\n kind: \"agent\"\n id: string\n /** Adapter slug to spawn a NEW session. Omit to reuse via sessionRef. */\n adapter?: Selector<string> | string\n /** Reuse an earlier AgentStep's spawned session, by that step's id. Inside\n * a `map`/`pipeline` body, a `{{index}}` placeholder resolves to the\n * current item index — `\"review[{{index}}]\"` names the session THIS item's\n * `review` step spawned (the host indexes every fan-out spawn under its\n * `stepKey`, `<stepId>[<index>]`), where a bare `\"review\"` would resolve to\n * whichever item spawned last. */\n sessionRef?: string\n /** Model id override for this spawn — same semantics as `agent_start.model`\n * (a literal string or a per-run selector resolving to one; `undefined` ⇒\n * unchanged behaviour, the adapter keeps its default). Forwarded to the\n * spawn through the harness slot; an explicit `harness.model` pinning\n * (AIP-15 P2) still wins. Only meaningful with `adapter`; ignored on a\n * `sessionRef` reuse. */\n model?: Selector<string> | string\n /** Working directory for this spawn. Omit to fall back to the run-level `ctx.cwd`. */\n cwd?: Selector<string>\n /** Run this step's session inside a sandbox instead of on the host — a\n * provider slug or inline spec (see {@link AgentSandboxRef}), or a selector\n * resolving to one (`undefined` ⇒ host spawn, same as omitting the field).\n * Only meaningful when `adapter` is set (a `sessionRef` reuse inherits the\n * referenced session's placement). Hosts without sandbox support MUST fail\n * the spawn loudly rather than silently running on the host. */\n sandbox?: Selector<AgentSandboxRef | undefined> | AgentSandboxRef\n /** Prompt to send. */\n prompt: Selector<string>\n policy?:\n | { awaiting: \"auto-allow\"; prompt: string }\n | { awaiting: \"escalate\"; webhookUrl?: string; timeoutMs?: number }\n | { awaiting: \"fail\" }\n /** Validate the session's final message against this schema; re-prompt on\n * mismatch. A zod `ZodType` (TS-authored steps) or anything else\n * satisfying {@link OutputSchemaLike} (a WORKFLOW.md-authored JSON\n * Schema object compiles into one of these — see `compileAgentStep`). */\n outputSchema?: OutputSchemaLike\n /** Re-prompt-and-retry attempts on schema mismatch before failing. Default 2. */\n maxRetries?: number\n /** Cache this step's output under the run's cacheKey; the resolved prompt +\n * adapter + model + sessionRef are hashed. Default false — most agent steps have\n * side effects. */\n cacheable?: boolean\n /** Manifest-declared adapter option id → value, forwarded to a NEW spawn's\n * `startSession({ options })` — e.g. mastra-agent's `agent` option, set by\n * {@link CompileWorkflowOptions.agentRefs} resolution when this step's\n * declarative `agent.ref` names an app-scoped agent. Only meaningful with\n * `adapter`; ignored on a `sessionRef` reuse. */\n options?: Record<string, boolean | number | string>\n /** Harness pinning for this step's spawn. See {@link AgentHarness}. */\n harness?: AgentHarness\n /** The resolved agent manifest's declared `tools` (AGENT.md `tools:`), set\n * by {@link CompileWorkflowOptions.agentRefs} resolution. Forwarded to the\n * host's `spawn` so it can mount its own tool gateway scoped to this list\n * (names the gateway doesn't serve — harness-native tools — match\n * nothing). Unset ⇒ the agent declared no tools list. Only meaningful\n * with `adapter`; ignored on a `sessionRef` reuse. */\n agentTools?: readonly string[]\n}\n\n/**\n * AIP-58 §4 Run workspace — declare a file under the run workspace\n * (`$run.workspace` / `_workflowFsRoot`) as a run artifact: hashed, sized,\n * and copied into the host's `artifactsDir` (`<runsRoot>/<runId>/artifacts/`).\n * Bound output (and the value passed to {@link RunWorkflowArgs.onArtifact})\n * is the resulting {@link ArtifactEntry}.\n *\n * Cache-aware when the run has `cache`/`cacheKey` wired (independent of any\n * `cacheable` flag — there is none on this step; declaring the same key/path\n * again under the same cacheKey is always cheap to re-verify): a hit COPIES\n * the previously-cached file forward from its original `artifactsDir` into\n * THIS run's own — never shares a directory across runs (AIP-58 §4 \"two runs\n * MUST NEVER share a workspace\") — so a step declaring an artifact from a\n * cache-hit-replayed upstream step still works. See `run-workflow.ts`'s\n * `case \"artifact\"` for the exact mechanics.\n */\nexport interface ArtifactStep {\n kind: \"artifact\"\n id: string\n /** Artifact key — identifies this artifact for `workflow_artifact_get`/\n * `workflow_publish`. Its on-disk filename under `artifactsDir` is\n * `path`'s own basename (sanitized), not the key — see {@link\n * ArtifactEntry.path} — unless another key's file shares the same\n * basename, in which case the key disambiguates it (F42). */\n key: Selector<string> | string\n /** Path to the source file. Relative to `$run.workspace`; MUST resolve\n * inside it (an absolute path or a `..`-escaping relative one throws). */\n path: Selector<string> | string\n contentType?: Selector<string> | string\n}\n\n/**\n * AIP-58 §4/§1 `ArtifactEntry` — one run-scoped copy of a declared output\n * file. `path` is `\"artifacts/<basename>\"` (F42: the declared source file's\n * OWN basename, sanitized — e.g. `outputsFiles.pdf: {path: transcript.pdf}`\n * ⇒ `artifacts/transcript.pdf` — keeping the extension, unlike the bare key),\n * relative to the RUN WORKSPACE ROOT (`<runsRoot>/<runId>/`, the parent of\n * `$run.workspace` itself) — never the original in-workspace location the\n * file was read from. Two keys whose files share a basename get the SECOND\n * one's name prefixed with its own sanitized key instead (deterministic,\n * never a silent overwrite) — always read `path` back rather than assuming\n * `artifacts/<key>` or `artifacts/<basename(path)>`.\n */\nexport interface ArtifactEntry {\n key: string\n path: string\n sha256: string\n size: number\n stepId: string\n contentType?: string\n}\n\n/**\n * `kind: \"gate\"` — run a shell command through the host's subprocess runner\n * as a deterministic pass/fail check (AIP-15 P3 / AIP-17). Exit code 0 is a\n * pass; any other code is a failure. Bound output is `{ ok, exitCode, report\n * }`; `report` is the process' stdout (if it parses as JSON) or the file at\n * `reportPath` (relative to `cwd`), parsed as JSON.\n */\nexport interface GateStep {\n kind: \"gate\"\n id: string\n command: string\n /** Command arguments. Each element (selector or string) resolves per-run\n * against the bindings: a LEADING `$input|$item|$steps.<id>|$index` token\n * (AIP-16 prefix grammar) resolves and any trailing text is appended\n * verbatim (`\"$input.bookDir/knowledge\"` → `\"<resolved>/knowledge\"`); a\n * string that is exactly a ref resolves to that value's string form;\n * `$$…` stays a literal `$`; a ref that resolves to nothing (or a `$…`\n * string that opens no known ref token) throws naming the step and the\n * arg index. */\n args?: readonly (Selector<string> | string)[]\n /** Working directory. Selector form resolves per-run. A string may carry\n * the same leading-`$…` ref rule as `args` (leading token + trailing\n * text, `$$` escape, unresolvable ref throws). The RESOLVED cwd is made\n * absolute: absolute stays absolute; relative (incl. `.`) resolves\n * against the run's own `ctx.cwd` — never the daemon process cwd.\n * Omit for the run's `ctx.cwd`. */\n cwd?: Selector<string> | string\n /** Path (relative to `cwd`), of a JSON report file, consulted when stdout\n * doesn't itself parse as JSON. */\n reportPath?: string\n /** Hard wall-clock cap for a single command invocation, in ms. Default\n * {@link DEFAULT_STEP_TIMEOUT_MS} when unset — a gate's subprocess is\n * never left to run unbounded (F45). */\n timeoutMs?: number\n /** Re-run on a failing exit code, up to `maxAttempts` (default 1 = no\n * retry — a single attempt, fail immediately on a non-zero exit). */\n retry?: {\n maxAttempts: number\n backoff: \"fixed\" | \"exponential\"\n initialMs?: number\n }\n /** Re-prompt-and-rerun on a failing attempt, BEFORE each retry after the\n * first: send the named prior {@link AgentStep}'s session (resolved via\n * {@link AgentSessionHost.resolveByLabel}, the same lookup a `sessionRef`\n * reuse uses) a prompt with this gate's last report injected, wait for\n * its turn, then re-run the gate command. */\n onFail?: {\n reprompt: string\n with?: Record<string, unknown>\n }\n}\n\n/** One gate command invocation's raw result — before report resolution. */\nexport interface GateCommandResult {\n exitCode: number\n stdout: string\n stderr: string\n timedOut?: boolean\n}\n\n/** Host-injectable subprocess runner for {@link GateStep}. Undefined ⇒ the\n * runtime's own `node:child_process`-backed default. */\nexport type GateCommandRunner = (spec: {\n command: string\n args: readonly string[]\n cwd: string\n timeoutMs?: number\n /** The run's cancel signal — a cancelled run kills an in-flight gate\n * command's child process the same way it kills an agent step's session.\n * A host-injected runner should pass this through to its own subprocess\n * spawn (e.g. `child_process.execFile`'s `signal` option) so the process\n * is signalled, not merely orphaned. */\n signal?: AbortSignal\n}) => Promise<GateCommandResult>\n\n/** One `kind: \"gate\"` command attempt's outcome, reported as it happens\n * (every attempt, not just the last) — the `gate-report` lifecycle event. */\nexport interface GateReportEvent {\n stepId: string\n ok: boolean\n exitCode: number\n report: unknown\n attempt: number\n}\n\n/** What a declarative agent-step's `agent.ref` resolves to — the adapter to\n * spawn under plus any adapter options that pick which concrete agent runs\n * (e.g. mastra-agent's `agent` option, an emitted AGENT.md path). Built by\n * the host from its own app-install state; the compiler only consumes it. */\nexport interface AgentRefResolution {\n /** Adapter slug to spawn (e.g. \"mastra-agent\"). */\n adapter: string\n /** Adapter option id → value merged onto the compiled step's `options`. */\n options?: Record<string, boolean | number | string>\n /** AGENT.md's declared `model` — the compiled step's DEFAULT when the\n * step itself sets none (a step-level `model:` still wins). Forwarded\n * through the same `harness.model` channel a step-level `model` uses. */\n model?: string\n /** AGENT.md's declared `tools` (string ids only) — becomes the compiled\n * step's {@link AgentStep.agentTools}. */\n tools?: readonly string[]\n}\n\n/**\n * The element generics on `ToolStep` are erased to `any` so heterogeneous\n * steps (different contracts, different input/output/context types) coexist in\n * one `steps[]` array — per-step type safety is enforced where each step is\n * authored, not at the collection level. Same contravariant-function-position\n * constraint `@agentproto/driver`'s `implementations[]` works around (TS\n * issue #21534); tightening the union to `ToolStep<unknown, …>` rejects a\n * concrete `ToolStep<MarketSearchInput, …>` on the zod `ZodType<T>` variance.\n */\nexport type RunStep =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | ToolStep<any, any, any>\n | TransformStep\n | MapStep\n | PipelineStep\n | BranchStep\n | LoopStep\n | ParallelStep\n | ApprovalStep\n | SuspendStep\n | GroupStep\n | SubworkflowStep\n | AgentStep\n | GateStep\n | ArtifactStep\n\n/** One `outputsFiles.<key>` declaration carried onto a compiled\n * {@link RuntimeWorkflow} — the AIP-16 file contract, amended with\n * `required` (AIP-58 §4). `path` MAY use the `<runId>`/`<workflowId>`/\n * `<isoDate>` interpolation tokens AIP-16 names (`<toolId>` is not\n * resolvable at the workflow level and is left literal). */\nexport interface OutputsFileContract {\n path: string\n /** `true`: missing when the run's steps finish ⇒ `failed { code:\n * \"missing-artifact\" }` (AIP-58 §4/§10). Absent (the default) or `false`\n * ⇒ advisory only — a `console.warn`, the run still succeeds (mirrors\n * `StepRecord.hint`'s \"advisory, never load-bearing\" posture; matches the\n * AIP-58 V3 vector's own note: \"with required absent or false, the same\n * scenario would be a warning\"). */\n required?: boolean\n contentType?: string\n}\n\nexport interface RuntimeWorkflow {\n id: string\n description?: string\n steps: readonly RunStep[]\n /**\n * Cleanup steps that ALWAYS run once `steps` ends — succeeded, failed, or\n * cancelled (they run without the abort signal). They see the same\n * bindings (a step that never ran is simply absent). A failing `finally`\n * step fails an otherwise-successful run; after a failed or cancelled run\n * the original outcome wins and the cleanup error is only reported.\n */\n finally?: readonly RunStep[]\n /** Pick the run's final output (default: the last top-level step's output). */\n output?: Selector<unknown>\n /** AIP-16 `outputsFiles` (as amended by AIP-58 §4) — checked ONCE, after\n * every top-level step finishes successfully. See {@link OutputsFileContract}\n * and `run-workflow.ts`'s `checkOutputsFiles`. */\n outputsFiles?: Readonly<Record<string, OutputsFileContract>>\n}\n\n/** A human/host decision on one approval request. `who` records WHO decided\n * (\"human\", \"timeout\", \"cancelled\", …); `note` is optional free text. */\nexport interface ApprovalDecision {\n approved: boolean\n who: string\n note?: string\n}\n\nexport interface ApprovalRequest {\n stepId: string\n prompt: string\n approvers: readonly string[]\n artifacts?: readonly string[]\n /** The step's `timeoutMs` when set — the host may enforce it itself; the\n * runtime's default when the host doesn't is to wait forever. */\n timeoutMs?: number\n}\n\nexport interface ResumeRequest {\n stepId: string\n on: readonly string[]\n}\n\n/**\n * AIP-58 §3(a) explicit signal, recorded by the host when the step's own\n * session calls `run.requestInput` before its turn ends. Passed to\n * {@link RunWorkflowArgs.onInputRequired} to durably suspend the step.\n */\nexport interface InputRequiredRequest {\n stepId: string\n prompt: string\n schema?: Record<string, unknown>\n}\n\nexport interface AgentSessionHost {\n /** Spawn a new agent session and return its id. A `sandbox` ref asks the\n * host to run the session inside that sandbox (provider slug or inline\n * spec); hosts that can't MUST throw rather than silently spawn on the\n * host. */\n spawn(\n adapter: string,\n opts: {\n cwd?: string\n workspaceSlug?: string\n stepId?: string\n sandbox?: AgentSandboxRef\n /** Adapter option id → value for this spawn (see {@link AgentStep.options}). */\n options?: Record<string, boolean | number | string>\n /** Harness pinning for this spawn (see {@link AgentStep.harness}). */\n harness?: AgentHarness\n /** The agent manifest's declared tools (see {@link AgentStep.agentTools}). */\n agentTools?: readonly string[]\n /** Run-unique key of the spawning step when it runs inside a\n * `map`/`pipeline` item: `stepId[<index>]`, the same key the run's step\n * hooks report. Absent outside a fan-out (the key is then `stepId`). */\n stepKey?: string\n },\n ): Promise<string>\n /**\n * The run is done with a session it spawned: end it (if still live) and\n * archive it. Called once per spawned session — when its `map`/`pipeline`\n * item settles, else when the run itself ends (ok or error) — never\n * earlier, so a later step's `sessionRef` can still reuse it. The session's\n * id stays on the step's output. Best-effort: a throw is swallowed.\n */\n releaseSession?(sessionId: string): Promise<void>\n /** Send a prompt to an existing session and wait for its turn to end. */\n sendPromptAndWait(sessionId: string, prompt: string): Promise<void>\n /** Look up a session by the step id that spawned it (for sessionRef reuse). */\n resolveByLabel(stepId: string): string | undefined\n /** Handle an awaiting-input policy for a session. */\n onAwaitingInput?(sessionId: string, policy: AgentStep[\"policy\"]): Promise<void>\n /**\n * AIP-58 §3(a) explicit signal: consume (and clear) a pending\n * `run.requestInput` recorded for this session — checked by\n * {@link AgentStep} execution right after a turn ends, before the\n * outputSchema retry loop (and again inside it, after every reprompt).\n * `undefined` when no request is pending. Optional: a host that omits\n * this never suspends a step on this signal — the outcome rule's other\n * branches (missing-output / vacuous success) still apply.\n */\n takeInputRequest?(sessionId: string): { prompt: string; schema?: Record<string, unknown> } | undefined\n /** Return the session's final assistant message text (for outputSchema validation). */\n readFinalMessage?(sessionId: string): Promise<string>\n /** Current cumulative cost (USD) of a session, for run-level budgeting. */\n readCostUsd?(sessionId: string): Promise<number>\n /** Emit a harness-warning for a session — the pass-through channel behind\n * the AIP-15 \"never silently ignore\" `session:harness-warning` event (used\n * by the runtime for `harness.knowledge` empty matches, reason\n * `knowledge-empty`). Optional: hosts without an event bus omit it and\n * the runtime degrades to the run-record entry alone. */\n emitHarnessWarning?(input: {\n sessionId: string\n warnings: readonly string[]\n label?: string\n }): void\n}\n\n/** One journal entry: a cached step output plus the hash of the inputs that produced it. */\nexport interface StepCacheEntry {\n output: unknown\n resolvedInputHash: string\n /** Set only by a `kind: \"artifact\"` step (see {@link ArtifactStep}): the\n * absolute `artifactsDir` this entry's file was copied into when first\n * cached. A hit in a LATER run (a different `artifactsDir`, since AIP-58\n * §4 forbids two runs sharing a workspace) copies the file forward from\n * here into the new run's own `artifactsDir` instead of re-declaring it. */\n artifactsDirAtCache?: string\n /** Set only for a cacheable `tool`/`agent` step (see `hashResolvedInputs`/\n * `buildCacheEntry` in `run-workflow.ts`) whenever the host wires a run\n * workspace: the absolute `$run.workspace` / `_workflowFsRoot` path this\n * entry was cached under. A hit in a LATER run (a different workspace —\n * AIP-58 §4 forbids two runs sharing one) rewrites `output`'s path\n * strings from here onto the new run's own, and relocates\n * {@link workspaceFiles} the same way. */\n workspaceAtCache?: string\n /** Workspace-relative files/directories (under {@link workspaceAtCache})\n * this entry's `output` pointed at and that existed on disk when the\n * entry was written — copied forward into a later cache-hit run's own\n * workspace so a downstream step reading one of these paths finds the\n * bytes there too, not just in the original (by-then-gone) run's. */\n workspaceFiles?: readonly string[]\n}\n\n/** Opt-in journal for cacheable steps. Host-injected; file-backed in the runtime. */\nexport interface StepCache {\n /** Look up a step's journal entry by its namespaced key. */\n get(stepCacheKey: string): Promise<StepCacheEntry | undefined>\n /** Write/overwrite a step's journal entry. */\n set(stepCacheKey: string, entry: StepCacheEntry): Promise<void>\n}\n\n/** Extra context passed to `onStepStart`/`onStepComplete`. */\nexport interface StepHookInfo {\n /** The step's output was replayed from the {@link StepCache} journal —\n * it was not executed (no spawn, no tool dispatch) this run. */\n cached?: boolean\n}\n\n/** Why `onStepSkipped` fired. */\nexport interface StepSkippedInfo {\n /** `\"branch-not-taken\"`: the step sits in an untaken `branch` arm.\n * `\"circuit-open\"`: a `map`/`pipeline` item never started because the\n * fan-out's spawn circuit breaker opened\n * ({@link MapStep.maxConsecutiveSpawnFailures}). `\"run-cancelled\"`: a\n * `map`/`pipeline` item never started because the run was cancelled\n * (`RunWorkflowArgs.signal` aborted) while earlier items were still in\n * flight. */\n reason: \"branch-not-taken\" | \"circuit-open\" | \"run-cancelled\"\n /** Id of the authored step whose decision skipped the step — the `branch`\n * step, or (circuit-open/run-cancelled) the `map`/`pipeline` step. */\n branchId: string\n /** `\"circuit-open\"`: the first error of the spawn-failure streak that\n * tripped the breaker. `\"run-cancelled\"`: a fixed \"run cancelled\" message. */\n message?: string\n}\n\n/** What `onStepFailed` reports. */\nexport interface StepFailedInfo {\n /** `err.message` if the throw was an `Error`, else `String(err)`. */\n error: string\n}\n\nexport interface RunWorkflowArgs {\n workflow: RuntimeWorkflow\n input?: unknown\n signal?: AbortSignal\n /** Decide an {@link ApprovalStep}. Default: auto-approve. May return a bare\n * boolean (equivalent to `{approved, who: \"host\"}`) or a full\n * {@link ApprovalDecision} recording who decided. */\n approve?: (req: ApprovalRequest) => boolean | ApprovalDecision | Promise<boolean | ApprovalDecision>\n /** Supply a {@link SuspendStep}'s resume payload. Default: throw + suspend. */\n resume?: (req: ResumeRequest) => unknown | Promise<unknown>\n /**\n * AIP-58 §3(a)/§5 outcome rule: suspend an {@link AgentStep} that\n * signalled `run.requestInput` (see\n * {@link AgentSessionHost.takeInputRequest}), resolving with the resume\n * payload once an external event supplies one. The runtime sends that\n * payload (JSON) as the step's next prompt to the SAME session and\n * re-applies the outcome rule — the step may suspend again, fail\n * `missing-output`, or succeed. Default (undefined) ⇒\n * {@link AgentInputRequiredError} throws instead, the same\n * no-hook-supplied shape {@link WorkflowSuspendedError} uses for\n * {@link SuspendStep}.\n */\n onInputRequired?: (req: InputRequiredRequest) => unknown | Promise<unknown>\n /** Host-injected agent session runtime. Undefined ⇒ {@link AgentStep} throws. */\n agents?: AgentSessionHost\n /** Working directory for spawned agent sessions. */\n cwd?: string\n /** Workspace slug for spawned agent sessions. */\n workspaceSlug?: string\n /** AIP-58 §4 Run workspace — absolute path to this run's own scratch\n * directory (AIP-16's `_workflowFsRoot`), exposed to steps as\n * `$run.workspace` / `{{run.workspace}}`. Undefined ⇒ the `run` binding\n * and `kind: \"artifact\"` steps are unavailable. */\n workspace?: string\n /** AIP-58 §4 — absolute path to this run's `artifacts/` directory. Required\n * alongside `workspace` for a `kind: \"artifact\"` step (or a declared\n * `RuntimeWorkflow.outputsFiles`) to run. */\n artifactsDir?: string\n /** This run's id — used only to interpolate the `<runId>` token in a\n * declared `outputsFiles.<key>.path` (AIP-16). Purely informational\n * otherwise. */\n runId?: string\n /** Called once per {@link ArtifactEntry} recorded — by a `kind: \"artifact\"`\n * step, or by the end-of-run `outputsFiles` check — cache hit or fresh. */\n onArtifact?: (entry: ArtifactEntry) => void\n /** Run-level cost ceiling (USD). Once the summed cost of spawned sessions\n * reaches this, the next AgentStep spawn fails with `budget_exceeded`. */\n maxTotalCostUsd?: number\n /** Opt-in journal cache for cacheable steps. Undefined ⇒ caching disabled. */\n cache?: StepCache\n /** Namespacing label for this run's cache lookups (the workflow_start cacheKey).\n * Both `cache` and `cacheKey` must be set for any caching to happen. */\n cacheKey?: string\n /** Called when a step begins execution (before spawn/prompt). A cacheable\n * step replayed from the journal still fires this, with `info.cached`. */\n onStepStart?: (stepId: string, info?: StepHookInfo) => void\n /** Called when a step completes execution, with its output — `info.cached`\n * when the output was replayed from the journal instead of executed. */\n onStepComplete?: (stepId: string, output: unknown, info?: StepHookInfo) => void\n /** Called for every step in a `branch` arm that was NOT taken, once the\n * branch decides — the step will not run this time. Only statically-known\n * steps are reported (a `map`/`pipeline`/`subworkflow` step under the arm\n * reports its own id, not its body's); a step id that also sits in the\n * taken path is never reported. */\n onStepSkipped?: (stepId: string, info: StepSkippedInfo) => void\n /** Called when a step inside a tolerant (`onError: \"collect\"`) `map`/\n * `pipeline` item throws — the item is recorded as rejected and the run\n * goes on, so this is the only signal the failing step gets. `stepId` is\n * the innermost step that threw, indexed like `onStepStart`'s. A throw\n * that fails the run is NOT reported here (the run's own failure is). */\n onStepFailed?: (stepId: string, info: StepFailedInfo) => void\n /** Host-injectable subprocess runner for `kind: \"gate\"` steps. Undefined ⇒\n * the runtime's own `node:child_process`-backed default. */\n runGateCommand?: GateCommandRunner\n /** Called once per `kind: \"gate\"` command attempt (every attempt, not just\n * the last) — the `gate-report` lifecycle event. */\n onGateReport?: (ev: GateReportEvent) => void\n}\n\nexport interface WorkflowRunResult {\n output: unknown\n bindings: Bindings\n}\n","/**\n * NodeFsPort — a read-mostly `FsPort` over the host filesystem, rooted at an\n * AIP-10 corpus workspace. The local-FS twin of the adapter `corpus-cli`'s\n * knowledge preview uses, so `harness.knowledge` materialization resolves a\n * workspace with exactly the same port (and therefore the same hidden-segment\n * skipping and path confinement) the CLI does.\n */\n\nimport { mkdir, readFile, readdir, stat, writeFile, appendFile } from \"node:fs/promises\"\nimport type { Dirent } from \"node:fs\"\nimport { dirname, join } from \"node:path\"\nimport type { FsPort, FsLockHandle, FsStat } from \"@agentproto/corpus\"\n\nexport class NodeFsPort implements FsPort {\n private readonly root: string\n\n constructor(root: string) {\n this.root = root\n }\n\n private resolve(p: string): string {\n const normalized = p.replace(/^\\/+/, \"\")\n if (normalized.startsWith(\"..\")) {\n throw new Error(`NodeFsPort: path \"${p}\" escapes the workspace root \"${this.root}\"`)\n }\n return join(this.root, normalized)\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await stat(this.resolve(p))\n return true\n } catch {\n return false\n }\n }\n\n async readFile(p: string): Promise<string> {\n return readFile(this.resolve(p), \"utf8\")\n }\n\n async writeFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(dirname(target), { recursive: true })\n await writeFile(target, content, \"utf8\")\n }\n\n async appendFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(dirname(target), { recursive: true })\n await appendFile(target, content, \"utf8\")\n }\n\n async readdir(p: string): Promise<readonly string[]> {\n return readdir(this.resolve(p))\n }\n\n async walk(p: string): Promise<readonly string[]> {\n const out: string[] = []\n const visit = async (dir: string): Promise<void> => {\n let entries: Dirent[] = []\n try {\n entries = await readdir(dir, { withFileTypes: true })\n } catch {\n return\n }\n for (const ent of entries) {\n if (ent.name.startsWith(\".\")) continue\n const full = join(dir, ent.name)\n if (ent.isDirectory()) {\n await visit(full)\n } else if (ent.isFile()) {\n out.push(full)\n }\n }\n }\n await visit(this.resolve(p))\n const prefix = this.resolve(p)\n return out.map((f) => f.slice(prefix.length).replace(/^\\//, \"\"))\n }\n\n async stat(p: string): Promise<FsStat | null> {\n try {\n const s = await stat(this.resolve(p))\n return {\n kind: s.isDirectory() ? \"directory\" : \"file\",\n ...(s.isFile() ? { bytes: s.size } : {}),\n modifiedAt: s.mtime,\n }\n } catch {\n return null\n }\n }\n\n async lock(): Promise<FsLockHandle> {\n // Read-mostly port: knowledge materialization holds no cross-process\n // transactions, so the advisory lock is a no-op (the FsPort contract\n // explicitly allows a no-op for single-process topologies).\n return { release: async () => {} }\n }\n}\n","/**\n * `harness.knowledge` materialization (AIP-15 P2) — resolve each selector\n * against its AIP-10 corpus workspace with the same `resolveKnowledge` the\n * corpus CLI previews with, then write the matched raw entries (frontmatter +\n * body) into the step's cwd under `.knowledge/` BEFORE the step's session\n * runs. Idempotent: every run rewrites the same deterministic file set.\n */\n\nimport { mkdir, writeFile } from \"node:fs/promises\"\nimport { basename, isAbsolute, join } from \"node:path\"\n\nimport {\n filterEntriesByAllOf,\n isRefinedKind,\n resolveKnowledge,\n type RefinedKind,\n} from \"@agentproto/corpus\"\n\nimport { resolveRefString } from \"./ref-string.js\"\nimport type { Bindings } from \"./types.js\"\nimport type {\n HarnessKnowledgeSelector,\n KnowledgeAppliedRecord,\n} from \"./types.js\"\nimport { NodeFsPort } from \"./node-fs-port.js\"\n\nconst DEFAULT_MAX_ENTRIES = 50\n\nfunction resolveStringArray(\n stepId: string,\n index: number,\n field: string,\n values: readonly string[] | undefined,\n b: Bindings,\n): string[] | undefined {\n if (values === undefined) return undefined\n return values.map((v) =>\n resolveRefString(stepId, `harness.knowledge[${index}].${field}`, v, b),\n )\n}\n\n/**\n * Resolve every `$…`-bearing string of each `harness.knowledge[]` selector\n * (`workspace`, `anyOf[]`, `allOf[]`, `kinds[]`) against the run bindings,\n * producing selectors whose strings are run-resolved and stripped of the\n * loader's internal `deferred` flag. Selectors without refs pass through\n * unchanged (a copy). See {@link resolveRefString} for the ref rule.\n */\nexport function resolveKnowledgeSelectors(\n stepId: string,\n selectors: readonly HarnessKnowledgeSelector[],\n b: Bindings,\n): HarnessKnowledgeSelector[] {\n return selectors.map((sel, index) => {\n const deferred = sel.deferred === true\n const workspace = deferred\n ? resolveRefString(stepId, `harness.knowledge[${index}].workspace`, sel.workspace, b)\n : sel.workspace\n return {\n ...sel,\n deferred: undefined,\n workspace,\n ...(sel.anyOf !== undefined\n ? { anyOf: deferred ? resolveStringArray(stepId, index, \"anyOf\", sel.anyOf, b) : [...sel.anyOf] }\n : {}),\n ...(sel.allOf !== undefined\n ? { allOf: deferred ? resolveStringArray(stepId, index, \"allOf\", sel.allOf, b) : [...sel.allOf] }\n : {}),\n ...(sel.kinds !== undefined\n ? { kinds: deferred ? resolveStringArray(stepId, index, \"kinds\", sel.kinds, b) : [...sel.kinds] }\n : {}),\n }\n })\n}\n\n/** `../corpus-writer` → `corpus-writer`; `.` → the dir's own basename. */\nfunction workspaceDirName(workspace: string): string {\n const trimmed = workspace.replace(/\\/+$/, \"\")\n return basename(trimmed) || trimmed\n}\n\n/** Entries are written as `<slug>.md` — flatten anything path-like. */\nfunction safeSlug(slug: string): string {\n return slug.replace(/[^a-zA-Z0-9._-]+/g, \"-\")\n}\n\nexport interface MaterializedKnowledge {\n records: KnowledgeAppliedRecord[]\n /** Total entries written across all selectors — drives the prompt note. */\n written: number\n /** human-readable warnings for empty matches (`knowledge-empty`). */\n warnings: string[]\n}\n\n/**\n * Materialize every selector in `selectors` under `<stepCwd>/.knowledge/`.\n * Throws on a non-\"files\" `mode` or an unreadable workspace — the loader\n * rejects both earlier; this is the direct-TS-authoring path's backstop.\n */\nexport async function materializeKnowledge(\n stepId: string,\n selectors: readonly HarnessKnowledgeSelector[],\n stepCwd: string,\n): Promise<MaterializedKnowledge> {\n const knowledgeDir = join(stepCwd, \".knowledge\")\n const records: KnowledgeAppliedRecord[] = []\n const warnings: string[] = []\n const indexSections: string[] = []\n let written = 0\n\n for (const [i, sel] of selectors.entries()) {\n if (sel.mode !== undefined && sel.mode !== \"files\") {\n throw new Error(\n `step '${stepId}': harness.knowledge[${i}].mode must be \"files\" (v1 supports no other mode)`,\n )\n }\n const workspace = sel.workspace\n if (typeof workspace !== \"string\" || workspace.length === 0) {\n throw new Error(\n `step '${stepId}': harness.knowledge[${i}] needs a non-empty 'workspace'`,\n )\n }\n if (!isAbsolute(workspace)) {\n throw new Error(\n `step '${stepId}': harness.knowledge[${i}].workspace '${workspace}' must be absolute by run time — the loader resolves relative paths; did you bypass loadWorkflowHandle?`,\n )\n }\n\n const fs = new NodeFsPort(workspace)\n const rootStat = await fs.stat(\".\")\n if (rootStat === null || rootStat.kind !== \"directory\") {\n // A missing workspace after ref resolution is not a throw — the app's\n // gate decides (same seam as `knowledge-empty`); record the selector as\n // matching nothing and warn with the `knowledge-workspace-missing`\n // reason so hosts can distinguish it from an empty match.\n const warning = `knowledge-workspace-missing: harness.knowledge[${i}] (workspace '${workspace}') does not name an existing directory`\n warnings.push(warning)\n records.push({ workspace, matched: 0, written: 0 })\n continue\n }\n\n const kinds = (sel.kinds ?? []).filter((k): k is RefinedKind => isRefinedKind(k))\n const resolved = filterEntriesByAllOf(\n await resolveKnowledge({\n fs,\n query: {\n ...(sel.anyOf && sel.anyOf.length > 0 ? { tags: [...sel.anyOf] } : {}),\n ...(kinds.length > 0 ? { kinds } : {}),\n },\n }),\n sel.allOf,\n )\n\n // Deterministic order: slug ascending, then the cap.\n const sorted = [...resolved].sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0))\n const cap = sel.maxEntries ?? DEFAULT_MAX_ENTRIES\n const picked = sorted.slice(0, cap)\n\n const dirName = workspaceDirName(workspace)\n const lines: string[] = []\n for (const entry of picked) {\n const rel = join(dirName, `${safeSlug(entry.slug)}.md`)\n // Raw entry: frontmatter + body, exactly as it lives in the workspace.\n const raw = await fs.readFile(entry.path)\n await mkdir(join(knowledgeDir, dirName), { recursive: true })\n await writeFile(join(knowledgeDir, rel), raw, \"utf8\")\n lines.push(\n `- [${entry.title || entry.slug}](${rel.split(\"\\\\\").join(\"/\")}) — ${entry.kind}, ${entry.tags.join(\", \")}`,\n )\n }\n written += picked.length\n if (lines.length > 0) {\n indexSections.push(`## ${dirName}\\n\\n${lines.join(\"\\n\")}`)\n }\n\n records.push({ workspace, matched: resolved.length, written: picked.length })\n if (resolved.length === 0) {\n warnings.push(\n `knowledge-empty: harness.knowledge[${i}] (workspace '${workspace}') matched 0 entries`,\n )\n }\n }\n\n // Deterministic INDEX.md — selectors in declaration order, entries by slug.\n const index =\n \"# Knowledge index\\n\\n\" +\n (indexSections.length > 0 ? indexSections.join(\"\\n\\n\") : \"_No entries matched._\") +\n \"\\n\"\n await mkdir(knowledgeDir, { recursive: true })\n await writeFile(join(knowledgeDir, \"INDEX.md\"), index, \"utf8\")\n\n return { records, written, warnings }\n}\n","/**\n * The step-walker. Executes a {@link RuntimeWorkflow} top-to-bottom, threading\n * each step's output into a run-scoped binding bag, and dispatching `tool`\n * steps through `@agentproto/driver` `runTool` (resolve DRIVER → validate input\n * + context → execute body → validate output). Composite steps (`map` /\n * `branch` / `loop` / `parallel` / `approval` / `subworkflow`) recurse over the\n * same bindings; `suspend` defers to the host's resume hook.\n */\n\nimport { runTool } from \"@agentproto/driver\"\nimport { createHash } from \"node:crypto\"\nimport { spawn } from \"node:child_process\"\nimport { copyFile, cp, mkdir, readFile, stat, writeFile } from \"node:fs/promises\"\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\"\nimport { z } from \"zod\"\nimport { resolveRefString } from \"./ref-string.js\"\nimport type {\n AgentStep,\n ApprovalDecision,\n ArtifactEntry,\n ArtifactStep,\n Bindings,\n FanOutOutcome,\n GateCommandResult,\n GateStep,\n KnowledgeAppliedRecord,\n OutputSchemaLike,\n OutputsFileContract,\n RunStep,\n RunWorkflowArgs,\n RuntimeWorkflow,\n StepCacheEntry,\n StepFailedInfo,\n StepHookInfo,\n StepSkippedInfo,\n TolerantFanOutResult,\n WorkflowRunResult,\n} from \"./types.js\"\nimport { DEFAULT_MAX_CONSECUTIVE_SPAWN_FAILURES, DEFAULT_STEP_TIMEOUT_MS } from \"./types.js\"\nimport { materializeKnowledge, resolveKnowledgeSelectors } from \"./knowledge.js\"\n\n/** Thrown by a `suspend` step when no host `resume` hook is provided. */\nexport class WorkflowSuspendedError extends Error {\n constructor(\n readonly stepId: string,\n readonly on: readonly string[],\n ) {\n super(\n `workflow suspended at step '${stepId}' awaiting [${on.join(\", \")}] — ` +\n `no resume hook supplied`,\n )\n this.name = \"WorkflowSuspendedError\"\n }\n}\n\n/**\n * AIP-58 §3(a) — thrown when an {@link AgentStep}'s session signals\n * `run.requestInput` but no host `onInputRequired` hook is provided (the\n * same \"no resume hook supplied\" shape {@link WorkflowSuspendedError} uses\n * for {@link SuspendStep}). A host that wires `onInputRequired` never sees\n * this thrown — it durably suspends the step instead.\n */\nexport class AgentInputRequiredError extends Error {\n constructor(\n readonly stepId: string,\n readonly prompt: string,\n readonly schema?: Record<string, unknown>,\n ) {\n super(\n `step '${stepId}' requires input (\"${prompt}\") — no onInputRequired hook supplied`,\n )\n this.name = \"AgentInputRequiredError\"\n }\n}\n\n/**\n * AIP-58 §3 Outcome rule — thrown when an {@link AgentStep} declares an\n * `outputSchema` and its turn ends (after exhausting retries) without ever\n * producing output that validates against it, and no explicit\n * input-required signal (§3(a)/(b)) was observed either. `hint` is set when\n * the final message matches the \"trailing question mark\" heuristic — it is\n * ONLY a triage aid; it never changes the outcome (still `missing-output`).\n */\nexport class StepOutcomeError extends Error {\n constructor(\n readonly stepId: string,\n readonly code: \"missing-output\",\n message: string,\n readonly hint?: \"possible-input-request\",\n ) {\n super(message)\n this.name = \"StepOutcomeError\"\n }\n}\n\n/**\n * AIP-58 §4/§10 — thrown when a declared `outputsFiles.<key>` (`required`\n * absent or `true`) does not exist under the run workspace once every\n * top-level step has finished. `stepId` is the last top-level step that ran\n * (the manifest names no step for a workflow-level contract, so the last one\n * to finish is the best available attribution).\n */\nexport class MissingArtifactError extends Error {\n readonly code = \"missing-artifact\" as const\n constructor(\n readonly key: string,\n readonly stepId: string | undefined,\n ) {\n super(`outputsFiles.${key} was required but is missing from the run workspace`)\n this.name = \"MissingArtifactError\"\n }\n}\n\n/**\n * Thrown when an {@link AgentStep}'s session could not be spawned at all\n * (`AgentSessionHost.spawn` rejected) — distinct from a session that spawned\n * and then failed its turn. A tolerant fan-out counts these toward its spawn\n * circuit breaker ({@link MapStep.maxConsecutiveSpawnFailures}): a spawn that\n * fails for one item usually fails for every item (missing cwd, adapter\n * gone, process limits), so burning through the rest is pure noise.\n */\nexport class AgentSpawnError extends Error {\n constructor(\n readonly stepId: string,\n readonly cause: unknown,\n ) {\n super(`step '${stepId}': agent spawn failed — ${errorMessage(cause)}`)\n this.name = \"AgentSpawnError\"\n }\n}\n\n/**\n * Thrown instead of dispatching a step whose run was cancelled\n * (`ctx.signal.aborted`) — checked BEFORE any work for the step begins (see\n * {@link execStepBody}'s entry guard), so a cancel stops the run from\n * starting any further step, including a sibling within the SAME stage/\n * fan-out, not just a later one. Never journaled: it's thrown before a\n * cacheable step's `cache.set` call, so `workflow_retry` re-executes it.\n */\nexport class WorkflowCancelledError extends Error {\n constructor(readonly stepId: string) {\n super(`step '${stepId}': run cancelled — not started`)\n this.name = \"WorkflowCancelledError\"\n }\n}\n\ninterface RunState {\n readonly input: unknown\n readonly steps: Record<string, unknown>\n readonly maxTotalCostUsd?: number\n /** Last-known cost per session id; summed to get the run's total spend.\n * A Map (not a running delta) so a session reused across steps via\n * sessionRef is counted once, not double-counted. */\n readonly costBySession: Map<string, number>\n /** Journal keys ({@link cachedHitKey}) of steps whose output was replayed\n * from the cache this run and whose completion hasn't been reported yet —\n * consumed by {@link completeStep} to tag `onStepComplete` with\n * `{ cached: true }` (F35). */\n readonly cachedHits: Set<string>\n}\n\ninterface RunCtx {\n readonly state: RunState\n readonly approve?: RunWorkflowArgs[\"approve\"]\n readonly resume?: RunWorkflowArgs[\"resume\"]\n readonly onInputRequired?: RunWorkflowArgs[\"onInputRequired\"]\n readonly signal?: AbortSignal\n readonly agents?: RunWorkflowArgs[\"agents\"]\n readonly cwd?: string\n readonly workspaceSlug?: string\n /** AIP-58 §4 — see {@link RunWorkflowArgs.workspace}. */\n readonly workspace?: string\n /** AIP-58 §4 — see {@link RunWorkflowArgs.artifactsDir}. */\n readonly artifactsDir?: string\n readonly runId?: string\n readonly onArtifact?: RunWorkflowArgs[\"onArtifact\"]\n readonly cache?: RunWorkflowArgs[\"cache\"]\n readonly cacheKey?: RunWorkflowArgs[\"cacheKey\"]\n /** Set inside a `map`/`pipeline` fan-out body — the `[<index>]` path\n * (nested maps append their own `[<index>]`) appended to every cache\n * journal key computed under this ctx, so each item of a shared-id\n * body caches independently instead of overwriting one shared entry\n * (F33). Mirrors the id-suffixing {@link withIndexedHooks} already does\n * for `onStepStart`/`onStepComplete`. */\n readonly cacheKeySuffix?: string\n readonly onStepStart?: RunWorkflowArgs[\"onStepStart\"]\n readonly onStepComplete?: RunWorkflowArgs[\"onStepComplete\"]\n readonly onStepSkipped?: RunWorkflowArgs[\"onStepSkipped\"]\n readonly onStepFailed?: RunWorkflowArgs[\"onStepFailed\"]\n readonly runGateCommand?: RunWorkflowArgs[\"runGateCommand\"]\n readonly onGateReport?: RunWorkflowArgs[\"onGateReport\"]\n /** Sessions spawned in the current release scope (the run, or one\n * `map`/`pipeline` item) — released when that scope settles. */\n readonly spawned?: string[]\n /** F42 — on-disk artifact filenames already claimed this run, under\n * `artifactsDir` (one flat namespace, no subdirectories). One Set per\n * top-level run, shared by every nested `subworkflow` call (they write\n * into the SAME `artifactsDir` — see the `\"subworkflow\"` case in\n * `execStep`), so a parent's and a child's artifacts can't silently\n * collide either. See {@link reserveArtifactDestName}. */\n readonly usedArtifactNames?: Set<string>\n}\n\n/** Open a release scope for one fan-out item: sessions its steps spawn are\n * released as soon as the item settles, not held until the run ends. */\nfunction withReleaseScope(ctx: RunCtx): RunCtx {\n return { ...ctx, spawned: [] }\n}\n\n/** Release every session collected in `ctx`'s scope (see\n * `AgentSessionHost.releaseSession`). Never throws. */\nasync function releaseScope(ctx: RunCtx): Promise<void> {\n const release = ctx.agents?.releaseSession\n if (!release || !ctx.spawned || ctx.spawned.length === 0) return\n const ids = ctx.spawned.splice(0)\n const agents = ctx.agents\n await Promise.all(ids.map((id) => Promise.resolve().then(() => release.call(agents, id)).catch(() => undefined)))\n}\n\nfunction view(ctx: RunCtx, item?: unknown, index?: number): Bindings {\n return {\n input: ctx.state.input,\n steps: ctx.state.steps,\n item,\n index,\n ...(ctx.workspace !== undefined ? { run: { workspace: ctx.workspace } } : {}),\n }\n}\n\n/**\n * A `map`/`pipeline` fan-out body can't be enumerated at compile time (the\n * item list is only known at runtime — see `collectStaticSteps` in\n * `runtime/workflow-runner.ts`), so its per-item steps all share one static\n * compiled id (e.g. \"clean\"). Reporting every iteration under that same id\n * makes the host's step list unable to tell iterations apart (AIP-58 §5 /\n * F28). Wrapping `onStepStart`/`onStepComplete` for the duration of ONE\n * item's execution suffixes every step id it reports with `[<index>]`\n * (e.g. \"clean[0]\", \"clean[1]\") — the host discovers these dynamically,\n * same as any other step it didn't see at compile time.\n */\nfunction withIndexedHooks(ctx: RunCtx, index: number): RunCtx {\n const cacheKeySuffix = `${ctx.cacheKeySuffix ?? \"\"}[${index}]`\n if (!ctx.onStepStart && !ctx.onStepComplete && !ctx.onStepSkipped && !ctx.onStepFailed) {\n return { ...ctx, cacheKeySuffix }\n }\n return {\n ...ctx,\n cacheKeySuffix,\n onStepStart: ctx.onStepStart\n ? (id: string, info?: StepHookInfo) => ctx.onStepStart!(`${id}[${index}]`, info)\n : undefined,\n onStepComplete: ctx.onStepComplete\n ? (id: string, out: unknown, info?: StepHookInfo) => ctx.onStepComplete!(`${id}[${index}]`, out, info)\n : undefined,\n onStepSkipped: ctx.onStepSkipped\n ? (id: string, info: StepSkippedInfo) => ctx.onStepSkipped!(`${id}[${index}]`, info)\n : undefined,\n onStepFailed: ctx.onStepFailed\n ? (id: string, info: StepFailedInfo) => ctx.onStepFailed!(`${id}[${index}]`, info)\n : undefined,\n }\n}\n\n/**\n * The innermost step an in-flight error came from, as a reporter bound to\n * that step's own (indexed) hooks — set by the first {@link execStep} frame\n * the error unwinds through, so a tolerant fan-out that swallows the error\n * can still fail the step that actually threw (not its item's wrapper).\n */\nconst failureOrigin = new WeakMap<object, (info: StepFailedInfo) => void>()\n\n/** A tolerant fan-out item threw: report it via `onStepFailed` on the step\n * that threw (see {@link failureOrigin}), else on the item's body step. */\nfunction reportItemFailure(err: unknown, itemCtx: RunCtx, bodyId: string): void {\n const info = { error: errorMessage(err) }\n const origin = typeof err === \"object\" && err !== null ? failureOrigin.get(err) : undefined\n if (origin) {\n // Consume it: a host may reject every item with the SAME error object.\n failureOrigin.delete(err as object)\n origin(info)\n } else {\n itemCtx.onStepFailed?.(bodyId, info)\n }\n}\n\n/**\n * Spawn circuit breaker for one tolerant fan-out — see\n * {@link MapStep.maxConsecutiveSpawnFailures}. `settle` is fed every\n * item's outcome in completion order; `open` is the first error of the\n * streak that tripped it (undefined while closed). Once open it stays open.\n */\nfunction spawnBreaker(threshold: number): { settle: (err?: unknown) => void; readonly open: string | undefined } {\n let streak = 0\n let streakFirst: string | undefined\n let open: string | undefined\n return {\n settle(err?: unknown): void {\n if (open !== undefined) return\n if (!(err instanceof AgentSpawnError)) {\n streak = 0\n streakFirst = undefined\n return\n }\n if (streak === 0) streakFirst = err.message\n streak++\n if (threshold > 0 && streak >= threshold) open = streakFirst\n },\n get open() {\n return open\n },\n }\n}\n\n/** Report every item never started as `skipped` (each of its body's\n * statically-known steps, indexed like a started item's) — either because a\n * tripped spawn circuit breaker (`kind: \"circuit-open\"`) or the run being\n * cancelled (`kind: \"run-cancelled\"`) stopped the fan-out from starting any\n * more items. */\nfunction skipUnstartedItems(\n ctx: RunCtx,\n fanOutId: string,\n from: number,\n items: readonly unknown[],\n bodiesOf: (item: unknown, idx: number) => readonly RunStep[],\n kind: StepSkippedInfo[\"reason\"],\n reason: string,\n results: unknown[],\n): void {\n for (let idx = from; idx < items.length; idx++) {\n results[idx] = { status: \"skipped\", index: idx, item: items[idx], reason: `${kind}: ${reason}` }\n const itemCtx = withIndexedHooks(ctx, idx)\n if (!itemCtx.onStepSkipped) continue\n let bodies: readonly RunStep[]\n try {\n bodies = bodiesOf(items[idx], idx)\n } catch {\n // A body builder that needs a started item's state (a pipeline stage\n // reading its prevOutput) — the item's outcome above still records it.\n continue\n }\n for (const id of new Set(skippableStepIds(bodies))) {\n itemCtx.onStepSkipped(id, { reason: kind, branchId: fanOutId, message: reason })\n }\n }\n}\n\n/** The bound output of a tolerant fan-out. */\nfunction tolerantResult(results: unknown[], circuitOpen: string | undefined): TolerantFanOutResult {\n const outcomes = results as FanOutOutcome[]\n return {\n results: outcomes,\n succeeded: outcomes.filter((r) => r.status === \"fulfilled\").length,\n failed: outcomes.filter((r) => r.status === \"rejected\").length,\n skipped: outcomes.filter((r) => r.status === \"skipped\").length,\n ...(circuitOpen !== undefined ? { circuitOpen: { error: circuitOpen } } : {}),\n }\n}\n\n/** Resolve a value that is either a static string or a binding selector. */\nfunction resolveSel(sel: string | ((bindings: Bindings) => string), b: Bindings): string {\n return typeof sel === \"function\" ? sel(b) : sel\n}\n\n/** An AgentStep's `sessionRef` with `{{index}}` bound to the current fan-out\n * item (see `AgentStep.sessionRef`). Outside a fan-out it stays literal. */\nfunction resolveSessionRef(ref: string, b: Bindings): string {\n return b.index === undefined ? ref : ref.replace(/\\{\\{\\s*index\\s*\\}\\}/g, String(b.index))\n}\n\n/** Extract a JSON candidate from raw assistant text:\n * 1. last ```json fenced block if present, else\n * 2. last generic ``` fenced block if present, else\n * 3. the whole trimmed string. */\nfunction extractJsonCandidate(raw: string): string {\n const jsonFence = /```json\\s*([\\s\\S]*?)```/g\n const lastJson = lastMatch(jsonFence, raw)\n if (lastJson !== undefined) return lastJson\n\n const anyFence = /```\\s*([\\s\\S]*?)```/g\n const lastAny = lastMatch(anyFence, raw)\n if (lastAny !== undefined) return lastAny\n\n return raw.trim()\n}\n\nfunction lastMatch(re: RegExp, s: string): string | undefined {\n let m: RegExpExecArray | null\n let last: RegExpExecArray | null = null\n while ((m = re.exec(s)) !== null) last = m\n return last ? last[1]?.trim() : undefined\n}\n\nfunction spentUsd(state: RunState): number {\n let total = 0\n for (const c of state.costBySession.values()) total += c\n return total\n}\n\n/** Sentinel a resolved input/prompt's absolute run-workspace path is\n * replaced with before hashing (see {@link hashResolvedInputs}). */\nconst WORKSPACE_HASH_PLACEHOLDER = \"\\u0000$run.workspace\\u0000\"\n\n/** Deterministic content hash of a step's resolved inputs. `workspace` —\n * this run's `$run.workspace` / `_workflowFsRoot` absolute path, when the\n * host wires one — is replaced by a stable placeholder wherever it occurs\n * as a substring (including trailing subpaths, e.g.\n * `<workspace>/cleaned/out.txt`) before hashing. AIP-58 §4 gives every run\n * its OWN, disjoint workspace directory — a fresh absolute path each\n * time — so without this a step whose resolved input/prompt embeds\n * `$run.workspace` would hash differently on every run and never hit the\n * journal even though nothing about the step's actual work changed\n * (regression: AIP-58 P4 / #1467 broke #1421's cache this way). */\nfunction hashResolvedInputs(kind: string, resolved: unknown, workspace: string | undefined): string {\n const serialized = `${kind}\\u0000${JSON.stringify(resolved) ?? \"undefined\"}`\n const normalized = workspace ? serialized.split(workspace).join(WORKSPACE_HASH_PLACEHOLDER) : serialized\n return createHash(\"sha256\").update(normalized).digest(\"hex\")\n}\n\n/** `value`, recursively, with every string that is `from` (or `from` plus a\n * trailing subpath) rewritten to start with `to` instead. Used both to\n * normalize resolved inputs (`hashResolvedInputs` — via a literal split/join\n * rather than this walk, since inputs are hashed as one serialized blob)\n * and — here — to rewrite a cache hit's RECORDED OUTPUT so a path naming\n * the ORIGINAL run's workspace points at the CURRENT run's own instead\n * ({@link relocateCachedOutput}). Arrays/plain objects are copied; anything\n * else (numbers, booleans, class instances, `null`) passes through as-is. */\nfunction rewriteWorkspacePaths(value: unknown, from: string, to: string): unknown {\n if (typeof value === \"string\") return value.split(from).join(to)\n if (Array.isArray(value)) return value.map((v) => rewriteWorkspacePaths(v, from, to))\n if (value !== null && typeof value === \"object\" && value.constructor === Object) {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = rewriteWorkspacePaths(v, from, to)\n return out\n }\n return value\n}\n\n/** Every string in `value` (recursively) that names a path under `workspace`,\n * as a workspace-relative path — collected into `out`. A candidate only,\n * not yet checked against the filesystem (see {@link collectWorkspaceFiles}). */\nfunction collectWorkspaceCandidates(value: unknown, workspace: string, out: Set<string>): void {\n if (typeof value === \"string\") {\n if (value === workspace || value.startsWith(`${workspace}/`)) {\n const rel = relative(workspace, value)\n if (rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel)) out.add(rel)\n }\n return\n }\n if (Array.isArray(value)) {\n for (const v of value) collectWorkspaceCandidates(v, workspace, out)\n return\n }\n if (value !== null && typeof value === \"object\" && value.constructor === Object) {\n for (const v of Object.values(value as Record<string, unknown>)) collectWorkspaceCandidates(v, workspace, out)\n }\n}\n\n/** Every workspace-relative file/directory a cacheable step's output points\n * at — checked against the real filesystem (so a string that merely LOOKS\n * like a workspace path, but names nothing, isn't recorded as something a\n * later cache hit must relocate). Recorded on the journal entry\n * ({@link StepCacheEntry.workspaceFiles}) and copied forward by\n * {@link relocateCachedOutput} on a hit in a later run's own workspace. */\nasync function collectWorkspaceFiles(out: unknown, workspace: string): Promise<string[]> {\n const candidates = new Set<string>()\n collectWorkspaceCandidates(out, workspace, candidates)\n const files: string[] = []\n for (const rel of candidates) {\n try {\n await stat(join(workspace, rel))\n files.push(rel)\n } catch {\n // Not a real file/dir under the workspace — nothing to relocate.\n }\n }\n return files\n}\n\n/** Journal entry for a fresh (non-hit) cacheable `tool`/`agent` step —\n * records the workspace it ran under, and (best-effort) every file/dir its\n * output pointed at under that workspace, so a cache hit in a LATER run\n * (necessarily a different workspace — AIP-58 §4) can relocate them\n * (see {@link relocateCachedOutput}) instead of replaying an output that\n * names a path that only ever existed in this now-gone run. */\nasync function buildCacheEntry(ctx: RunCtx, out: unknown, hash: string): Promise<StepCacheEntry> {\n if (ctx.workspace === undefined) return { output: out, resolvedInputHash: hash }\n const workspaceFiles = await collectWorkspaceFiles(out, ctx.workspace)\n return {\n output: out,\n resolvedInputHash: hash,\n workspaceAtCache: ctx.workspace,\n ...(workspaceFiles.length > 0 ? { workspaceFiles } : {}),\n }\n}\n\n/** A `tool`/`agent` cache hit's recorded output, relocated onto the CURRENT\n * run: every file/dir the entry recorded under the ORIGINAL run's workspace\n * is copied into the matching path under this run's own (same relocation\n * spirit as `kind:\"artifact\"`'s cache hit — \"two runs MUST NEVER share a\n * workspace\", AIP-58 §4), then the recorded output's path strings are\n * rewritten to point there. Best-effort: a source the original run's\n * `scratch/` retention already swept is not this run's problem to recover\n * (same posture `kind:\"artifact\"`'s relocation takes). A no-op when the\n * entry predates this field, or this run has no workspace wired at all. */\nasync function relocateCachedOutput(ctx: RunCtx, entry: StepCacheEntry): Promise<unknown> {\n const from = entry.workspaceAtCache\n const to = ctx.workspace\n if (from === undefined || to === undefined || from === to) return entry.output\n for (const rel of entry.workspaceFiles ?? []) {\n const dest = join(to, rel)\n try {\n await mkdir(dirname(dest), { recursive: true })\n await cp(join(from, rel), dest, { recursive: true })\n } catch {\n // Best-effort — see doc above.\n }\n }\n return rewriteWorkspacePaths(entry.output, from, to)\n}\n\n/** Namespaced journal key for a step under a run's cacheKey. A step inside a\n * `map`/`pipeline` body shares its static compiled id (and kind) across\n * every item — `ctx.cacheKeySuffix` (the item's `[<index>]` path, set by\n * {@link withIndexedHooks}) disambiguates them so each item's cache entry\n * is independent instead of every item overwriting one shared key (F33). */\nfunction stepJournalKey(ctx: RunCtx, step: RunStep): string {\n return `${ctx.cacheKey}\\u0000${step.id}\\u0000${step.kind}${ctx.cacheKeySuffix ?? \"\"}`\n}\n\n/** True when this step should consult/populate the journal. */\nfunction isCacheEnabled(ctx: RunCtx, step: { cacheable?: boolean }): boolean {\n return step.cacheable === true && ctx.cache !== undefined && ctx.cacheKey !== undefined\n}\n\n/** Identity of one step execution under `ctx` for {@link RunState.cachedHits}\n * — the step id plus the map/pipeline item path, so concurrent items of a\n * shared-id body don't see each other's hits. */\nfunction cachedHitKey(ctx: RunCtx, stepId: string): string {\n return `${stepId}${ctx.cacheKeySuffix ?? \"\"}`\n}\n\n/** Report a step's completion — `{ cached: true }` when {@link execStep}\n * replayed it from the journal (F35: a cache hit still surfaces as a step). */\nfunction completeStep(ctx: RunCtx, stepId: string, out: unknown): void {\n const cached = ctx.state.cachedHits.delete(cachedHitKey(ctx, stepId))\n ctx.onStepComplete?.(stepId, out, cached ? { cached: true } : undefined)\n}\n\n/** Read the journal; on a hit return the output, else the key+hash to write on miss. */\nasync function readStepCache(\n ctx: RunCtx,\n step: RunStep,\n resolvedInputs: unknown,\n): Promise<{ hit: true; output: unknown } | { hit: false; key: string; hash: string }> {\n const key = stepJournalKey(ctx, step)\n const hash = hashResolvedInputs(step.kind, resolvedInputs, ctx.workspace)\n const entry = await ctx.cache!.get(key)\n if (entry !== undefined && entry.resolvedInputHash === hash) {\n return { hit: true, output: await relocateCachedOutput(ctx, entry) }\n }\n return { hit: false, key, hash }\n}\n\n/** `err.message` if `err` is an `Error`, else its string coercion. */\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** Formats the failure branch of {@link OutputSchemaLike.safeParse} — a real\n * zod `ZodError` satisfies this structurally (its `issues[]` carry `path`/\n * `message` plus extra fields TS ignores here), so this reads either a zod\n * schema's rejection or the ajv-backed JSON Schema adapter's. */\nfunction formatSchemaError(err: Extract<ReturnType<OutputSchemaLike[\"safeParse\"]>, { success: false }>[\"error\"]): string {\n return err.issues\n .map((i) => `${i.path.length > 0 ? i.path.join(\".\") + \": \" : \"\"}${i.message}`)\n .join(\", \")\n}\n\n/**\n * F27: render an agent step's `outputSchema` into a prompt-affordance note —\n * appended to BOTH the first prompt and every retry, so the model sees the\n * contract before it ever replies, not just after a rejected first attempt.\n * Prefers the exact schema: `compileOutputSchema`'s `jsonSchema` marker for a\n * WORKFLOW.md-authored step, else a live zod schema's own `z.toJSONSchema()`\n * (a TS-authored `buildAgentStep` caller commonly passes one directly — see\n * `OutputSchemaLike`'s doc). Degrades to a short field list when neither\n * conversion is possible (an exotic zod type, or a hand-built\n * `OutputSchemaLike` with no `jsonSchema` marker) — never throws, since a\n * step's prompt must never fail to build over an unrelated schema quirk.\n */\nfunction describeOutputSchemaForPrompt(schema: OutputSchemaLike): string | undefined {\n if (schema.jsonSchema !== undefined) {\n return `When done, reply with ONLY a JSON object matching this JSON Schema: ${JSON.stringify(schema.jsonSchema)}`\n }\n try {\n const jsonSchema = z.toJSONSchema(schema as unknown as z.ZodType)\n return `When done, reply with ONLY a JSON object matching this JSON Schema: ${JSON.stringify(jsonSchema)}`\n } catch {\n // Not a convertible zod schema — fall through to the short field list.\n }\n const shape = (schema as { shape?: unknown }).shape\n if (shape && typeof shape === \"object\") {\n const fields = Object.keys(shape)\n if (fields.length > 0) {\n return `When done, reply with ONLY a JSON object with these fields: ${fields.join(\", \")}`\n }\n }\n return undefined\n}\n\n/**\n * The statically-known steps under `steps` that a skipped `branch` arm\n * reports via `onStepSkipped`: leaf steps, plus `map`/`pipeline`/\n * `subworkflow` steps by their own id (their bodies aren't enumerable here or\n * don't report through this run's hooks). Structural wrappers (group,\n * parallel, branch, loop) are walked, never reported themselves.\n */\nfunction skippableStepIds(steps: readonly RunStep[], acc: string[] = []): string[] {\n for (const s of steps) {\n switch (s.kind) {\n case \"group\":\n skippableStepIds(s.steps, acc)\n break\n case \"parallel\":\n for (const br of s.branches) skippableStepIds(br.steps, acc)\n break\n case \"branch\":\n skippableStepIds(s.then, acc)\n if (s.otherwise) skippableStepIds(s.otherwise, acc)\n break\n case \"loop\":\n skippableStepIds(s.body, acc)\n break\n default:\n acc.push(s.id)\n }\n }\n return acc\n}\n\n/** Run an ordered list of steps, binding each output under its id; return last. */\nasync function runSequence(\n steps: readonly RunStep[],\n ctx: RunCtx,\n item: unknown,\n index: number | undefined,\n): Promise<unknown> {\n let last: unknown\n for (const s of steps) {\n const out = await execStep(s, ctx, item, index)\n ctx.state.steps[s.id] = out\n completeStep(ctx, s.id, out)\n last = out\n }\n return last\n}\n\n/**\n * Send a prompt and wait for the turn to end; if the session signals AIP-58\n * §3(a) (`run.requestInput`) before this returns, durably suspend via\n * `ctx.onInputRequired` — the promise only resolves once an external event\n * supplies the resume payload — then forward that payload (JSON) as the\n * step's NEXT prompt to the SAME session and repeat. So a step may suspend,\n * resume, and suspend again before this ever returns to its caller. No\n * signal observed ⇒ an ordinary one-shot send.\n */\nasync function sendPromptAndAwaitOutcome(\n ctx: RunCtx,\n step: AgentStep,\n sessionId: string,\n prompt: string,\n): Promise<void> {\n let next = prompt\n for (;;) {\n await ctx.agents!.sendPromptAndWait(sessionId, next)\n const req = ctx.agents!.takeInputRequest?.(sessionId)\n if (!req) return\n if (!ctx.onInputRequired) {\n throw new AgentInputRequiredError(step.id, req.prompt, req.schema)\n }\n const payload = await ctx.onInputRequired({ stepId: step.id, prompt: req.prompt, schema: req.schema })\n next = JSON.stringify(payload)\n }\n}\n\n/** Execute the full AgentStep body — spawn, prompt, policy, budget, outputSchema retry loop. */\nasync function execAgentStep(step: AgentStep, ctx: RunCtx, b: Bindings): Promise<unknown> {\n // Notify step start before any execution\n ctx.onStepStart?.(step.id)\n\n if (\n step.adapter &&\n ctx.state.maxTotalCostUsd !== undefined &&\n spentUsd(ctx.state) >= ctx.state.maxTotalCostUsd\n ) {\n throw new Error(\n `step '${step.id}': budget_exceeded — run spend $${spentUsd(ctx.state).toFixed(4)} >= cap $${ctx.state.maxTotalCostUsd}`,\n )\n }\n // Harness precedence: step `harness.cwd` (highest, among what this runtime\n // sees) beats the step's own `cwd` selector, which beats the run-level\n // `ctx.cwd` — see `AgentHarness`'s doc for the full chain (AGENT.md\n // frontmatter / app_run args / adapter default are resolved upstream of\n // this runtime, by the host's spawn implementation).\n // A relative step cwd resolves against the run cwd, never the daemon's own.\n const stepCwd = step.cwd ? resolveSel(step.cwd, b) : undefined\n const cwd =\n step.harness?.cwd ??\n (stepCwd !== undefined ? (ctx.cwd !== undefined ? resolve(ctx.cwd, stepCwd) : stepCwd) : ctx.cwd)\n // AIP-15 P2 `harness.knowledge`: materialize matched corpus entries into\n // the step cwd's `.knowledge/` BEFORE the spawn, and prepend the prompt\n // note pointing the session at the INDEX. An empty match is not an error —\n // it's recorded (`matched: 0`) and surfaced as a harness warning after the\n // spawn gives us a session to attribute it to.\n let knowledgeOut: KnowledgeAppliedRecord[] | undefined\n let knowledgeWarnings: readonly string[] = []\n if (step.harness?.knowledge && step.harness.knowledge.length > 0) {\n if (cwd === undefined) {\n throw new Error(\n `step '${step.id}': harness.knowledge requires a resolvable working directory (set step cwd, harness.cwd, or the run cwd)`,\n )\n }\n // Deferred selectors (loader-flagged `$…` refs) resolve per run against\n // the bindings; a relative resolved workspace joins to this run cwd.\n const knowledgeSelectors = resolveKnowledgeSelectors(step.id, step.harness.knowledge, b).map(\n (sel) => ({\n ...sel,\n workspace: isAbsolute(sel.workspace) ? sel.workspace : join(cwd, sel.workspace),\n }),\n )\n const materialized = await materializeKnowledge(step.id, knowledgeSelectors, cwd)\n knowledgeOut = materialized.records\n knowledgeWarnings = materialized.warnings\n if (materialized.written > 0) {\n const note =\n `Knowledge for this step is materialized under .knowledge/ ` +\n `(see .knowledge/INDEX.md, ${materialized.written} entries).`\n const inner = step.prompt\n step = { ...step, prompt: (b: Bindings) => `${note}\\n\\n${inner(b)}` }\n }\n }\n // Sandbox ref: a selector resolves per-run (undefined ⇒ host spawn); a\n // literal (slug string or inline spec object) passes through as-is.\n const sandbox =\n typeof step.sandbox === \"function\" ? step.sandbox(b) : step.sandbox\n // Step-level `model` (same semantics as `agent_start.model`): a selector\n // resolves per-run against the bindings. It is folded into the spawn's\n // harness slot — the channel both spawn paths already forward as the\n // session's model — but an explicit `harness.model` pinning (AIP-15 P2)\n // still wins: the block is the more specific pinning layer.\n const model = step.model !== undefined ? resolveSel(step.model, b) : undefined\n const harness =\n step.harness !== undefined || model !== undefined\n ? {\n ...(step.harness ?? {}),\n ...(model !== undefined && step.harness?.model === undefined ? { model } : {}),\n }\n : undefined\n let sessionId: string | undefined\n if (step.adapter) {\n // A cancelled run winds down (its `finally` still runs) — it must not\n // start new agent sessions on the way (a fan-out would otherwise keep\n // spawning reviewers after the cancel killed the running ones). The\n // entry guard in `execStepBody` already catches this for a step that\n // hadn't started at all; this second check covers a cancel landing\n // WHILE this step's own body is already running (knowledge\n // materialization, sandbox/model resolution, …), before it reaches spawn.\n if (ctx.signal?.aborted) throw new WorkflowCancelledError(step.id)\n try {\n sessionId = await ctx.agents!.spawn(resolveSel(step.adapter, b), {\n cwd,\n workspaceSlug: ctx.workspaceSlug,\n stepId: step.id,\n ...(sandbox !== undefined ? { sandbox } : {}),\n ...(step.options !== undefined ? { options: step.options } : {}),\n ...(harness !== undefined ? { harness } : {}),\n ...(step.agentTools !== undefined ? { agentTools: step.agentTools } : {}),\n ...(b.index !== undefined ? { stepKey: `${step.id}[${b.index}]` } : {}),\n })\n } catch (err) {\n throw new AgentSpawnError(step.id, err)\n }\n } else {\n sessionId = ctx.agents!.resolveByLabel(resolveSessionRef(step.sessionRef!, b))\n }\n if (!sessionId) throw new Error(`step '${step.id}': no session (adapter and sessionRef both unresolved)`)\n if (step.adapter) ctx.spawned?.push(sessionId)\n if (knowledgeWarnings.length > 0 && ctx.agents!.emitHarnessWarning) {\n ctx.agents!.emitHarnessWarning({\n sessionId,\n warnings: knowledgeWarnings,\n label: step.id,\n })\n }\n // `harness.tools` has no generic per-spawn allowlist mechanism reaching\n // this runtime today (see `AgentHarness.tools`'s doc) — record that\n // honestly on the run record rather than silently dropping the field.\n const harnessOut =\n harness !== undefined\n ? {\n ...harness,\n ...(harness.tools && harness.tools.length > 0\n ? { toolsApplied: false as const }\n : {}),\n }\n : undefined\n // AIP-15 P2 prompt affordance: only when the host actually exposes the\n // `run_request_input` tool (signalled by `takeInputRequest` existing) —\n // a host without it never suspends on this signal, so telling the model\n // to call a tool that doesn't exist would be actively misleading.\n const inputRequestAffordance = ctx.agents!.takeInputRequest\n ? \"\\n\\nIf you need information you don't have, call the run_request_input tool instead of asking in your reply.\"\n : \"\"\n // F27: an `outputSchema` step states its contract on the FIRST prompt, not\n // only on a rejected-reply retry — the model should never have to guess\n // the shape and then get corrected.\n const outputSchemaNote = step.outputSchema ? describeOutputSchemaForPrompt(step.outputSchema) : undefined\n const outputSchemaAffordance = outputSchemaNote ? `\\n\\n${outputSchemaNote}` : \"\"\n await sendPromptAndAwaitOutcome(ctx, step, sessionId, step.prompt(b) + inputRequestAffordance + outputSchemaAffordance)\n if (step.policy && ctx.agents!.onAwaitingInput) {\n await ctx.agents!.onAwaitingInput(sessionId, step.policy)\n }\n\n if (ctx.agents!.readCostUsd) {\n ctx.state.costBySession.set(sessionId, await ctx.agents!.readCostUsd(sessionId))\n }\n\n if (!step.outputSchema) {\n let text: string | undefined\n if (ctx.agents!.readFinalMessage) {\n try {\n text = await ctx.agents!.readFinalMessage(sessionId)\n } catch {\n // ignore\n }\n }\n return { sessionId, ...(text !== undefined ? { text } : {}), ...(harnessOut ? { harness: harnessOut } : {}), ...(knowledgeOut ? { knowledgeApplied: knowledgeOut } : {}) }\n }\n\n // Validate-and-retry loop\n if (!ctx.agents!.readFinalMessage) {\n throw new Error(`step '${step.id}': outputSchema requires a host with readFinalMessage`)\n }\n const maxRetries = step.maxRetries ?? 2\n let lastErr = \"\"\n let lastRaw = \"\"\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const raw = await ctx.agents!.readFinalMessage(sessionId)\n lastRaw = raw\n const candidate = extractJsonCandidate(raw)\n let value: unknown\n try {\n value = JSON.parse(candidate)\n } catch {\n lastErr = \"not valid JSON\"\n if (attempt < maxRetries) {\n await sendPromptAndAwaitOutcome(\n ctx,\n step,\n sessionId,\n `Your previous reply did not match the required schema: ${lastErr}. ` +\n `Reply again with ONLY a JSON object that matches. No prose, no code fence needed.` +\n outputSchemaAffordance,\n )\n }\n continue\n }\n const res = step.outputSchema.safeParse(value)\n if (res.success) return { sessionId, output: res.data, ...(harnessOut ? { harness: harnessOut } : {}), ...(knowledgeOut ? { knowledgeApplied: knowledgeOut } : {}) }\n lastErr = formatSchemaError(res.error)\n if (attempt < maxRetries) {\n await sendPromptAndAwaitOutcome(\n ctx,\n step,\n sessionId,\n `Your previous reply did not match the required schema: ${lastErr}. ` +\n `Reply again with ONLY a JSON object that matches. No prose, no code fence needed.` +\n outputSchemaAffordance,\n )\n }\n }\n // AIP-58 §3 Outcome rule: a turn ending without producing a validated\n // output is `missing-output`, regardless of how the final message reads.\n // A trailing \"?\" is ONLY a triage hint — it never upgrades this to\n // `suspended` (that requires one of the two explicit signals above).\n const hint = lastRaw.trim().endsWith(\"?\") ? (\"possible-input-request\" as const) : undefined\n throw new StepOutcomeError(\n step.id,\n \"missing-output\",\n `step '${step.id}': missing-output — final message never matched outputSchema (${lastErr})`,\n hint,\n )\n}\n\n/** Best-effort `JSON.parse` — `undefined` (never a throw) on blank/invalid text. */\nfunction tryParseJson(text: string): unknown {\n const trimmed = text.trim()\n if (!trimmed) return undefined\n try {\n return JSON.parse(trimmed)\n } catch {\n return undefined\n }\n}\n\n/** Ceiling on how long to wait, after a gate's DIRECT child exits, for its\n * stdio to finish draining before giving up on it — see {@link\n * defaultRunGateCommand}'s doc. The ordinary case (no orphaned grandchild\n * sharing the pipe) resolves far sooner: as soon as both streams `end`. */\nconst GATE_STDIO_DRAIN_MS = 2_000\n\n/** How long a killed gate process group gets before an unresponsive survivor\n * is escalated from SIGTERM to SIGKILL. */\nconst GATE_KILL_GRACE_MS = 2_000\n\n/**\n * The runtime's own subprocess runner for `kind: \"gate\"` steps, used when no\n * `runGateCommand` host hook is injected — a plain `node:child_process`\n * argv-vector invocation (no shell interpolation). Exit code 0 always\n * resolves (never rejects on a non-zero exit); a timeout resolves with\n * `timedOut: true` and whatever partial output was captured.\n *\n * Settles on the DIRECT child's own `exit`, never on `close` — `close` only\n * fires once the child's stdout/stderr pipes have also closed, and a\n * subprocess that spawns its own child with inherited/piped stdio (e.g.\n * headless Chrome) can leave an orphaned grandchild holding that pipe open\n * long after the gate command itself finished, hanging the step forever\n * even though the command already completed (F45). A short drain window\n * after `exit` still gives any already-in-flight `data` a chance to land.\n *\n * `spec.timeoutMs` defaults to {@link DEFAULT_STEP_TIMEOUT_MS} when unset —\n * a gate's subprocess is never left unbounded. On timeout, or when\n * `spec.signal` aborts (a cancelled run must not leave a gate's subprocess\n * running any more than it leaves an agent step's session running —\n * {@link execGateStep} re-checks the signal right after this resolves to\n * turn the kill into a `WorkflowCancelledError`), the WHOLE process group is\n * killed via `process.kill(-pid)` (spawned detached), not just the direct\n * child — so an orphaned grandchild sharing that group doesn't survive it.\n */\nfunction defaultRunGateCommand(spec: {\n command: string\n args: readonly string[]\n cwd: string\n timeoutMs?: number\n signal?: AbortSignal\n}): Promise<GateCommandResult> {\n const timeoutMs = spec.timeoutMs ?? DEFAULT_STEP_TIMEOUT_MS\n return new Promise((resolve) => {\n const child = spawn(spec.command, [...spec.args], {\n cwd: spec.cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n })\n\n let stdout = \"\"\n let stderr = \"\"\n let settled = false\n let timedOut = false\n let stdoutEnded = !child.stdout\n let stderrEnded = !child.stderr\n let exitCode: number | undefined\n let drainTimer: NodeJS.Timeout | undefined\n\n const killGroup = (sig: NodeJS.Signals): void => {\n if (typeof child.pid !== \"number\") return\n try {\n if (process.platform !== \"win32\") process.kill(-child.pid, sig)\n else child.kill(sig)\n } catch {\n // Already gone.\n }\n }\n\n let killTimer: NodeJS.Timeout | undefined\n const kill = (): void => {\n killGroup(\"SIGTERM\")\n killTimer = setTimeout(() => killGroup(\"SIGKILL\"), GATE_KILL_GRACE_MS).unref()\n }\n\n const onAbort = () => kill()\n if (spec.signal?.aborted) kill()\n else spec.signal?.addEventListener(\"abort\", onAbort, { once: true })\n\n const timeoutTimer = setTimeout(() => {\n timedOut = true\n kill()\n }, timeoutMs).unref()\n\n const finish = (code: number): void => {\n if (settled) return\n settled = true\n clearTimeout(killTimer)\n clearTimeout(timeoutTimer)\n clearTimeout(drainTimer)\n spec.signal?.removeEventListener(\"abort\", onAbort)\n child.stdout?.destroy()\n child.stderr?.destroy()\n resolve({ exitCode: code, stdout, stderr, ...(timedOut ? { timedOut: true } : {}) })\n }\n\n // See the CLI driver's `runSubprocess` for why this resolves on `exit` +\n // both streams' own `end` (the ordinary case, near-instant) with\n // `drainTimer` only as a ceiling for the orphan-holds-the-pipe case.\n const maybeFinish = (): void => {\n if (exitCode !== undefined && stdoutEnded && stderrEnded) finish(exitCode)\n }\n\n child.stdout?.on(\"data\", (chunk) => {\n stdout += chunk.toString()\n })\n child.stdout?.on(\"end\", () => {\n stdoutEnded = true\n maybeFinish()\n })\n child.stderr?.on(\"data\", (chunk) => {\n stderr += chunk.toString()\n })\n child.stderr?.on(\"end\", () => {\n stderrEnded = true\n maybeFinish()\n })\n\n child.on(\"error\", () => {\n // A spawn-level error (e.g. ENOENT) means there's no process to time\n // out on — clear the timeout timer here so a slow drain window can't\n // race it and mislabel this result `timedOut: true`.\n clearTimeout(timeoutTimer)\n exitCode = 1\n drainTimer = setTimeout(() => finish(1), GATE_STDIO_DRAIN_MS).unref()\n maybeFinish()\n })\n child.on(\"exit\", (code, signal) => {\n exitCode = code ?? (signal ? 1 : 0)\n drainTimer = setTimeout(() => finish(exitCode!), GATE_STDIO_DRAIN_MS).unref()\n maybeFinish()\n })\n })\n}\n\n/** Resolve a gate's report: the command's stdout if it parses as JSON, else\n * the file at `reportPath` (relative to `cwd`), parsed as JSON. `undefined`\n * when neither yields parseable JSON — never a throw (a gate that emits no\n * structured report is still a valid pass/fail signal on its own). */\nasync function resolveGateReport(\n cmd: GateCommandResult,\n cwd: string,\n reportPath: string | undefined,\n): Promise<unknown> {\n const fromStdout = tryParseJson(cmd.stdout)\n if (fromStdout !== undefined) return fromStdout\n if (!reportPath) return undefined\n try {\n const abs = isAbsolute(reportPath) ? reportPath : join(cwd, reportPath)\n const raw = await readFile(abs, \"utf8\")\n return tryParseJson(raw)\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve a gate step's `cwd` against the run bindings. The same string-ref\n * rule as {@link resolveRefString} (leading `$input|$item|$steps.<id>|$index`\n * token + trailing literal text; `$$` escapes a literal `$`; an unresolvable\n * or malformed ref throws naming the step and the field). The RESOLVED cwd is\n * then made absolute: an absolute value stays as-is, a RELATIVE one (incl.\n * `.`) resolves against the run's own `ctx.cwd` — never the daemon process\n * cwd. No `cwd` (or a selector resolving to one) falls back to the run cwd.\n */\nfunction resolveGateCwd(step: GateStep, ctx: RunCtx, b: Bindings): string {\n const fallback = ctx.cwd ?? process.cwd()\n if (!step.cwd) return fallback\n const resolved = resolveRefString(step.id, \"cwd\", resolveSel(step.cwd, b), b, \"error\")\n return isAbsolute(resolved) ? resolved : resolve(fallback, resolved)\n}\n\n/** Execute the full GateStep body — run, parse report, retry-with-reprompt. */\nasync function execGateStep(step: GateStep, ctx: RunCtx, b: Bindings): Promise<unknown> {\n const cwd = resolveGateCwd(step, ctx, b)\n const args = (step.args ?? []).map((arg, index) =>\n resolveRefString(step.id, `args[${index}]`, resolveSel(arg, b), b, \"error\"),\n )\n const maxAttempts = Math.max(1, step.retry?.maxAttempts ?? 1)\n\n let last: { ok: boolean; exitCode: number; report: unknown } | undefined\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // A cancel landing between retry attempts must not reprompt a session\n // that cancel's releaseAll() may have already killed (which would\n // surface as a confusing \"session not found\" error instead of a clean\n // WorkflowCancelledError), nor wait out a retry backoff pointlessly.\n if (ctx.signal?.aborted) throw new WorkflowCancelledError(step.id)\n if (attempt > 1 && step.onFail?.reprompt) {\n if (!ctx.agents) {\n throw new Error(`step '${step.id}': on_fail.reprompt requires a host agents implementation`)\n }\n const targetSessionId = ctx.agents.resolveByLabel(step.onFail.reprompt)\n if (!targetSessionId) {\n throw new Error(\n `step '${step.id}': on_fail.reprompt targets unknown step '${step.onFail.reprompt}' — no session found`,\n )\n }\n const reportText = JSON.stringify(last?.report ?? null, null, 2)\n const extra = step.onFail.with ? `\\n\\nAdditional context:\\n${JSON.stringify(step.onFail.with, null, 2)}` : \"\"\n await ctx.agents.sendPromptAndWait(\n targetSessionId,\n `Gate '${step.id}' failed (exit code ${last?.exitCode}). Report:\\n${reportText}${extra}\\n\\n` +\n `Please address the findings above, then reply when done.`,\n )\n }\n\n if (attempt > 1 && step.retry?.initialMs) {\n const delayMs =\n step.retry.backoff === \"exponential\"\n ? step.retry.initialMs * 2 ** (attempt - 2)\n : step.retry.initialMs\n await new Promise((resolve) => setTimeout(resolve, delayMs))\n }\n\n const cmdResult = await (ctx.runGateCommand ?? defaultRunGateCommand)({\n command: step.command,\n args,\n cwd,\n timeoutMs: step.timeoutMs,\n signal: ctx.signal,\n })\n // The signal killed the subprocess mid-command (see\n // `defaultRunGateCommand`) — report the step as cancelled, not as\n // whatever exit code the kill happened to produce, so it's never\n // journaled as succeeded/failed and `workflow_retry` re-runs it.\n if (ctx.signal?.aborted) throw new WorkflowCancelledError(step.id)\n const report = await resolveGateReport(cmdResult, cwd, step.reportPath)\n const ok = cmdResult.exitCode === 0\n last = { ok, exitCode: cmdResult.exitCode, report }\n ctx.onGateReport?.({ stepId: step.id, ok, exitCode: cmdResult.exitCode, report, attempt })\n if (ok) break\n }\n\n if (!last!.ok) {\n const err = new Error(\n `step '${step.id}': gate failed after ${maxAttempts} attempt(s) — exit code ${last!.exitCode}`,\n ) as Error & { exitCode?: number; report?: unknown }\n err.exitCode = last!.exitCode\n err.report = last!.report\n throw err\n }\n return last\n}\n\n/**\n * Bound a `tool` step's dispatch with its own hard wall-clock cap\n * (independent of any tool-contract-level `timeoutMs` `runTool` already\n * enforces — F45 found NEITHER layer actually terminated a step whose\n * driver never settled its promise). `fn` receives a signal that aborts\n * either when `timeoutMs` elapses OR `parentSignal` (the run's own cancel\n * signal) aborts first — either way the driver underneath (the CLI driver's\n * `runSubprocess`, `defaultRunGateCommand`) is expected to kill its\n * subprocess on abort, same as a cancelled run already relies on. Only the\n * TIMER-triggered abort is reported as `'step '<id>': timed out after\n * <n>ms'`; a parent-signal abort rethrows whatever `fn` itself produced, so\n * a run cancel keeps its existing error shape.\n */\nasync function withStepTimeout<T>(\n stepId: string,\n timeoutMs: number,\n parentSignal: AbortSignal | undefined,\n fn: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const controller = new AbortController()\n const onParentAbort = (sig: AbortSignal): void => controller.abort(sig.reason)\n // The listener registered below must be the SAME function reference passed\n // to `removeEventListener` in `finally` — a fresh closure at each call site\n // (`() => onParentAbort(parentSignal)`) would never actually be removed,\n // leaking a listener on `parentSignal` for every step this wraps.\n const onParentAbortEvent = (): void => onParentAbort(parentSignal!)\n if (parentSignal?.aborted) onParentAbort(parentSignal)\n else parentSignal?.addEventListener(\"abort\", onParentAbortEvent, { once: true })\n\n let timedOut = false\n const timer = setTimeout(() => {\n timedOut = true\n controller.abort(new Error(`step '${stepId}': timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n\n try {\n return await fn(controller.signal)\n } catch (err) {\n if (timedOut) throw new Error(`step '${stepId}': timed out after ${timeoutMs}ms`)\n throw err\n } finally {\n clearTimeout(timer)\n parentSignal?.removeEventListener(\"abort\", onParentAbortEvent)\n }\n}\n\n/** A cache hit still surfaces as a step (F35): fire `onStepStart` with\n * `{ cached: true }` and flag it so its completion is tagged too. */\nfunction cacheHit(ctx: RunCtx, step: RunStep, output: unknown): unknown {\n ctx.state.cachedHits.add(cachedHitKey(ctx, step.id))\n ctx.onStepStart?.(step.id, { cached: true })\n return output\n}\n\nasync function execStep(\n step: RunStep,\n ctx: RunCtx,\n item: unknown,\n index: number | undefined,\n): Promise<unknown> {\n try {\n return await execStepBody(step, ctx, item, index)\n } catch (err) {\n // Innermost frame wins: an outer (composite) frame sees it already set.\n if (typeof err === \"object\" && err !== null && !failureOrigin.has(err)) {\n failureOrigin.set(err, (info) => ctx.onStepFailed?.(step.id, info))\n }\n throw err\n }\n}\n\nasync function execStepBody(\n step: RunStep,\n ctx: RunCtx,\n item: unknown,\n index: number | undefined,\n): Promise<unknown> {\n const { state, signal } = ctx\n\n // A cancelled run must not dispatch ANY further step — a sibling still\n // queued in the same stage/fan-out included, not just a later stage (the\n // old contract, \"no new stages will be started\", left a same-stage\n // successor like a `map`'s next item or the step right after it free to\n // start). Checked before `onStepStart` fires, so a step that never ran\n // never reports as started. `runFinally` clears `signal` on its own ctx\n // (cleanup must survive a cancel), so this never blocks a `finally` step.\n if (signal?.aborted) throw new WorkflowCancelledError(step.id)\n\n const b = view(ctx, item, index)\n\n // Notify step start for non-agent steps (agent steps notify in\n // execAgentStep; a tool/artifact step notifies in its own case, once it\n // knows whether it's a cache hit).\n if (step.kind !== \"agent\" && step.kind !== \"tool\" && step.kind !== \"artifact\") {\n ctx.onStepStart?.(step.id)\n }\n\n switch (step.kind) {\n case \"tool\": {\n const input = step.input(b)\n const runIt = (): Promise<unknown> =>\n withStepTimeout(step.id, step.timeoutMs ?? DEFAULT_STEP_TIMEOUT_MS, signal, (sig) =>\n runTool({\n tool: step.tool,\n candidates: step.candidates,\n input,\n context: step.context ? step.context(b) : undefined,\n resolverContext: step.resolverContext,\n secrets: step.secrets,\n signal: sig,\n }),\n )\n if (!isCacheEnabled(ctx, step)) {\n ctx.onStepStart?.(step.id)\n return runIt()\n }\n const c = await readStepCache(ctx, step, input)\n if (c.hit) return cacheHit(ctx, step, c.output)\n ctx.onStepStart?.(step.id)\n const out = await runIt()\n await ctx.cache!.set(c.key, await buildCacheEntry(ctx, out, c.hash))\n return out\n }\n\n case \"transform\":\n return step.compute(b)\n\n case \"map\": {\n const arr = [...step.over(b)]\n const parallelism = Math.max(1, step.parallelism ?? 1)\n const tolerant = step.onError === \"collect\"\n const results: unknown[] = new Array(arr.length)\n // Sliding window, not fixed batches: each of `parallelism` workers\n // pulls the next item as soon as its current one settles, so one slow\n // item never holds idle slots hostage. Same pool shape as `pipeline`.\n // Non-tolerant: after the first failure no NEW item starts (in-flight\n // ones finish), and the map rethrows that first error. Tolerant: a\n // failed item is reported on the step that threw, and the spawn\n // circuit breaker stops new items once spawning is systemically broken.\n let next = 0\n let failed = false\n const breaker = spawnBreaker(step.maxConsecutiveSpawnFailures ?? DEFAULT_MAX_CONSECUTIVE_SPAWN_FAILURES)\n const runItem = async (idx: number): Promise<void> => {\n const el = arr[idx]\n const inner = step.body(el, idx, view(ctx, el, idx))\n const wrapped = withReleaseScope(withIndexedHooks(ctx, idx))\n try {\n const out = await execStep(inner, wrapped, el, idx)\n completeStep(wrapped, inner.id, out)\n results[idx] = tolerant ? { status: \"fulfilled\", index: idx, value: out } : out\n breaker.settle()\n } catch (err) {\n if (!tolerant) {\n failed = true\n throw err\n }\n results[idx] = { status: \"rejected\", index: idx, item: el, error: errorMessage(err) }\n reportItemFailure(err, wrapped, inner.id)\n breaker.settle(err)\n } finally {\n await releaseScope(wrapped)\n }\n }\n const worker = async (): Promise<void> => {\n while (!failed && breaker.open === undefined && signal?.aborted !== true && next < arr.length) {\n const idx = next++\n await runItem(idx)\n }\n }\n await Promise.all(Array.from({ length: Math.min(parallelism, arr.length) }, () => worker()))\n // The run was cancelled while items remained unstarted: a non-tolerant\n // map must not report success over an incomplete `results` array — a\n // tolerant one instead marks the rest `skipped` (same shape a tripped\n // circuit breaker leaves), same as {@link skipUnstartedItems}'s other caller.\n if (signal?.aborted === true && next < arr.length) {\n if (!tolerant) throw new WorkflowCancelledError(step.id)\n skipUnstartedItems(ctx, step.id, next, arr, (el, idx) => [step.body(el, idx, view(ctx, el, idx))], \"run-cancelled\", \"run cancelled\", results)\n return tolerantResult(results, breaker.open)\n }\n if (!tolerant) return results\n if (breaker.open !== undefined) {\n skipUnstartedItems(ctx, step.id, next, arr, (el, idx) => [step.body(el, idx, view(ctx, el, idx))], \"circuit-open\", breaker.open, results)\n }\n return tolerantResult(results, breaker.open)\n }\n\n case \"pipeline\": {\n const items = [...step.over(b)]\n const tolerant = step.onError === \"collect\"\n if (items.length === 0) return tolerant ? tolerantResult([], undefined) : []\n const cap = Math.max(1, step.concurrency ?? items.length)\n const results: unknown[] = new Array(items.length)\n let next = 0\n const breaker = spawnBreaker(step.maxConsecutiveSpawnFailures ?? DEFAULT_MAX_CONSECUTIVE_SPAWN_FAILURES)\n const runItem = async (idx: number): Promise<void> => {\n let prev: unknown = undefined\n let stageId = step.id\n const wrapped = withReleaseScope(withIndexedHooks(ctx, idx))\n try {\n for (const stage of step.stages) {\n const inner = stage(items[idx], idx, prev, view(ctx, items[idx], idx))\n stageId = inner.id\n prev = await execStep(inner, wrapped, items[idx], idx)\n completeStep(wrapped, inner.id, prev)\n }\n results[idx] = tolerant ? { status: \"fulfilled\", index: idx, value: prev } : prev\n breaker.settle()\n } catch (err) {\n if (!tolerant) throw err\n results[idx] = { status: \"rejected\", index: idx, item: items[idx], error: errorMessage(err) }\n reportItemFailure(err, wrapped, stageId)\n breaker.settle(err)\n } finally {\n await releaseScope(wrapped)\n }\n }\n const worker = async (): Promise<void> => {\n while ((!tolerant || breaker.open === undefined) && signal?.aborted !== true && next < items.length) {\n const idx = next++\n await runItem(idx)\n }\n }\n await Promise.all(Array.from({ length: Math.min(cap, items.length) }, () => worker()))\n // See the `\"map\"` case's identical guard above.\n if (signal?.aborted === true && next < items.length) {\n if (!tolerant) throw new WorkflowCancelledError(step.id)\n skipUnstartedItems(\n ctx,\n step.id,\n next,\n items,\n (el, idx) => step.stages.map((stage) => stage(el, idx, undefined, view(ctx, el, idx))),\n \"run-cancelled\",\n \"run cancelled\",\n results,\n )\n return tolerantResult(results, breaker.open)\n }\n if (!tolerant) return results\n if (breaker.open !== undefined) {\n skipUnstartedItems(\n ctx,\n step.id,\n next,\n items,\n (el, idx) => step.stages.map((stage) => stage(el, idx, undefined, view(ctx, el, idx))),\n \"circuit-open\",\n breaker.open,\n results,\n )\n }\n return tolerantResult(results, breaker.open)\n }\n\n case \"branch\": {\n const taken = step.cond(b)\n const chosen = taken ? step.then : (step.otherwise ?? [])\n if (ctx.onStepSkipped) {\n // Report the untaken arm's steps as skipped (AIP-58 `step.skipped`)\n // — minus any id that also sits on the chosen path (arms sharing a\n // body, or a nested branch node that still has to decide).\n const onChosenPath = new Set(skippableStepIds(chosen))\n const untaken = taken ? (step.otherwise ?? []) : step.then\n for (const id of new Set(skippableStepIds(untaken))) {\n if (!onChosenPath.has(id)) ctx.onStepSkipped(id, { reason: \"branch-not-taken\", branchId: step.sourceId ?? step.id })\n }\n }\n return runSequence(chosen, ctx, item, index)\n }\n\n case \"loop\": {\n let iterations = 0\n let last: unknown\n while (\n iterations < step.maxIterations &&\n step.while(view(ctx, item, index))\n ) {\n last = await runSequence(step.body, ctx, item, index)\n iterations++\n }\n return last\n }\n\n case \"parallel\": {\n const outs = await Promise.all(\n step.branches.map((br) =>\n runSequence(br.steps, ctx, item, index).then((last) => ({\n id: br.id,\n last,\n })),\n ),\n )\n const record: Record<string, unknown> = {}\n for (const { id, last } of outs) record[id] = last\n return record\n }\n\n case \"approval\": {\n const prompt = step.prompt(b)\n const approvers = step.approvers ?? []\n const raw = ctx.approve\n ? await ctx.approve({\n stepId: step.id,\n prompt,\n approvers,\n ...(step.artifacts !== undefined ? { artifacts: step.artifacts } : {}),\n ...(step.timeoutMs !== undefined ? { timeoutMs: step.timeoutMs } : {}),\n })\n : true\n // A bare boolean is a host that doesn't record who decided — normalize\n // it to a full decision so downstream ledger/audit writes always have a\n // `who`.\n const decision: ApprovalDecision =\n typeof raw === \"boolean\" ? { approved: raw, who: \"host\" } : raw\n const approved = decision.approved\n const followups = approved\n ? (step.onApprove ?? [])\n : (step.onReject ?? [])\n await runSequence(followups, ctx, item, index)\n return { approved, who: decision.who, ...(decision.note !== undefined ? { note: decision.note } : {}) }\n }\n\n case \"suspend\": {\n if (!ctx.resume) throw new WorkflowSuspendedError(step.id, step.on)\n return ctx.resume({ stepId: step.id, on: step.on })\n }\n\n case \"group\":\n return runSequence(step.steps, ctx, item, index)\n\n case \"subworkflow\": {\n const childInput = step.input ? step.input(b) : state.input\n const child = await runWorkflowInner(step.workflow, childInput, {\n approve: ctx.approve,\n resume: ctx.resume,\n onInputRequired: ctx.onInputRequired,\n signal,\n agents: ctx.agents,\n cwd: ctx.cwd,\n workspaceSlug: ctx.workspaceSlug,\n workspace: ctx.workspace,\n artifactsDir: ctx.artifactsDir,\n runId: ctx.runId,\n onArtifact: ctx.onArtifact,\n cache: ctx.cache,\n cacheKey: ctx.cacheKey,\n runGateCommand: ctx.runGateCommand,\n onGateReport: ctx.onGateReport,\n spawned: ctx.spawned,\n usedArtifactNames: ctx.usedArtifactNames,\n })\n return child.output\n }\n\n case \"agent\": {\n if (!ctx.agents) throw new Error(`step '${step.id}': AgentStep requires a host agents implementation`)\n if (!isCacheEnabled(ctx, step)) return execAgentStep(step, ctx, b)\n const resolved = {\n prompt: step.prompt(b),\n adapter: step.adapter ? resolveSel(step.adapter, b) : undefined,\n model: step.model ? resolveSel(step.model, b) : undefined,\n sessionRef: step.sessionRef !== undefined ? resolveSessionRef(step.sessionRef, b) : undefined,\n }\n const c = await readStepCache(ctx, step, resolved)\n if (c.hit) return cacheHit(ctx, step, c.output) // cache hit ⇒ NO spawn, NO budget spend\n const out = await execAgentStep(step, ctx, b)\n await ctx.cache!.set(c.key, await buildCacheEntry(ctx, out, c.hash))\n return out\n }\n\n case \"gate\":\n return execGateStep(step, ctx, b)\n\n case \"artifact\":\n return execArtifactStep(step, ctx, b)\n }\n}\n\n/** Filesystem-safe filename — sanitizes either a bare artifact key (the\n * empty-basename fallback) or a declared file's basename. */\nfunction sanitizeArtifactFilename(name: string): string {\n const cleaned = name.replace(/[^a-zA-Z0-9._-]/g, \"_\")\n return cleaned.length > 0 ? cleaned : \"artifact\"\n}\n\n/**\n * F42 — an artifact's on-disk name under `artifactsDir` is the declared\n * source file's own basename (sanitized), not its key: `outputsFiles.pdf:\n * {path: transcript.pdf}` lands at `artifacts/transcript.pdf`, keeping the\n * extension, instead of P4's extension-less `artifacts/pdf`.\n *\n * Two keys whose source files share a basename (e.g. two different steps\n * each producing their own `report.json`) would otherwise silently\n * overwrite one another in the flat `artifactsDir` namespace — disambiguated\n * deterministically by prefixing a colliding name with its own sanitized\n * key (and a counter, in the practically-unreachable case that ALSO\n * collides), so the same workflow produces the same names run to run.\n * `usedNames` is one Set per top-level run, shared across subworkflows —\n * see `RunCtx.usedArtifactNames`.\n */\nfunction reserveArtifactDestName(rawPath: string, key: string, usedNames: Set<string>): string {\n const base = sanitizeArtifactFilename(basename(rawPath))\n let candidate = base\n if (usedNames.has(candidate)) {\n const keyPart = sanitizeArtifactFilename(key)\n candidate = `${keyPart}-${base}`\n for (let n = 2; usedNames.has(candidate); n++) {\n candidate = `${keyPart}-${n}-${base}`\n }\n }\n usedNames.add(candidate)\n return candidate\n}\n\n/** Read + hash the file at `rawPath` (resolved against `workspace`, which\n * MUST contain it) and copy it into `artifactsDir/<basename, disambiguated>`\n * (see {@link reserveArtifactDestName}). Shared by {@link execArtifactStep}'s\n * fresh path and {@link checkOutputsFiles}. */\nasync function copyIntoArtifacts(\n stepId: string,\n key: string,\n rawPath: string,\n workspace: string,\n artifactsDir: string,\n contentType: string | undefined,\n usedNames: Set<string>,\n): Promise<ArtifactEntry> {\n const abs = isAbsolute(rawPath) ? resolve(rawPath) : resolve(workspace, rawPath)\n const rel = relative(workspace, abs)\n if (rel.startsWith(\"..\") || isAbsolute(rel)) {\n throw new Error(`step '${stepId}': artifact path '${rawPath}' resolves outside the run workspace`)\n }\n const buf = await readFile(abs)\n const sha256 = createHash(\"sha256\").update(buf).digest(\"hex\")\n const destName = reserveArtifactDestName(rawPath, key, usedNames)\n await mkdir(artifactsDir, { recursive: true })\n await writeFile(join(artifactsDir, destName), buf)\n return {\n key,\n path: `artifacts/${destName}`,\n sha256,\n size: buf.length,\n stepId,\n ...(contentType !== undefined ? { contentType } : {}),\n }\n}\n\n/** `kind: \"artifact\"` — see {@link ArtifactStep}'s doc for the cache/relocate\n * mechanics. */\nasync function execArtifactStep(step: ArtifactStep, ctx: RunCtx, b: Bindings): Promise<ArtifactEntry> {\n if (ctx.workspace === undefined || ctx.artifactsDir === undefined) {\n throw new Error(`step '${step.id}': kind:\"artifact\" requires a run workspace (no workspace/artifactsDir wired)`)\n }\n const workspace = ctx.workspace\n const artifactsDir = ctx.artifactsDir\n const key = resolveSel(step.key, b)\n const rawPath = resolveSel(step.path, b)\n const contentType = step.contentType ? resolveSel(step.contentType, b) : undefined\n const resolvedInputs = { key, path: rawPath }\n const cacheOn = ctx.cache !== undefined && ctx.cacheKey !== undefined\n const journalKey = cacheOn ? stepJournalKey(ctx, step) : undefined\n const hash = cacheOn ? hashResolvedInputs(step.kind, resolvedInputs, ctx.workspace) : undefined\n\n if (cacheOn) {\n const entry = await ctx.cache!.get(journalKey!)\n if (entry !== undefined && entry.resolvedInputHash === hash) {\n const out = entry.output as ArtifactEntry\n // F42: reuse the EXACT name recorded at cache-write time — it may have\n // been collision-disambiguated (see `reserveArtifactDestName`), so\n // recomputing it fresh from `key` here could pick a different name\n // than what THIS run's other artifacts already claimed.\n const destName = out.path.slice(\"artifacts/\".length)\n ctx.usedArtifactNames?.add(destName)\n const destAbs = join(artifactsDir, destName)\n const srcAbs = join(entry.artifactsDirAtCache ?? artifactsDir, destName)\n if (srcAbs !== destAbs) {\n // AIP-58 §4 — \"two runs MUST NEVER share a workspace\": relocate the\n // bytes into THIS run's own artifactsDir rather than reading from\n // (or worse, pointing the run record at) the prior run's directory.\n await mkdir(dirname(destAbs), { recursive: true })\n try {\n await copyFile(srcAbs, destAbs)\n } catch {\n // Best-effort — the source may have been cleaned up by a host\n // retention policy (AIP-58 §4 permits discarding `scratch/`, but\n // `artifacts/` SHOULD be retained; a missing source here is a\n // deployment/retention issue, not something this run can fix).\n }\n }\n ctx.onArtifact?.(out)\n return cacheHit(ctx, step, out) as ArtifactEntry\n }\n }\n\n ctx.onStepStart?.(step.id)\n const out = await copyIntoArtifacts(step.id, key, rawPath, workspace, artifactsDir, contentType, ctx.usedArtifactNames!)\n if (cacheOn) {\n await ctx.cache!.set(journalKey!, { output: out, resolvedInputHash: hash!, artifactsDirAtCache: artifactsDir })\n }\n ctx.onArtifact?.(out)\n return out\n}\n\n/** Replace AIP-16's `<runId>`/`<workflowId>`/`<isoDate>` interpolation tokens\n * in a declared `outputsFiles.<key>.path`. `<toolId>` has no meaning at the\n * workflow level and is left literal. */\nfunction interpolateFileContractPath(path: string, workflowId: string, runId: string | undefined): string {\n return path\n .replace(/<runId>/g, runId ?? \"\")\n .replace(/<workflowId>/g, workflowId)\n .replace(/<isoDate>/g, new Date().toISOString().slice(0, 10))\n}\n\n/**\n * AIP-58 §4 / AIP-16 §Amendments — checked once every top-level step has\n * finished successfully. For each declared `outputsFiles.<key>`: present ⇒\n * copied into `artifactsDir` and reported via `onArtifact`, same as a\n * `kind:\"artifact\"` step (but never cache-aware — see the README's \"Cache/\n * replay interplay\" section for why that's a deliberate, documented limit —\n * route a step's file-shaped output through an explicit `kind:\"artifact\"`\n * step instead, if it needs to survive a cache hit in a later run);\n * absent + `required === true` ⇒ throws {@link MissingArtifactError}. Absent\n * OR `false` (the default — `required` is opt-in, matching AIP-16\n * `IO.schema.json`'s `fileContractEntry.required` doc and the V3 vector's own\n * note: \"with required absent or false, the same scenario would be a\n * warning\") ⇒ advisory only, a `console.warn`, the run still succeeds.\n */\nasync function checkOutputsFiles(\n outputsFiles: RuntimeWorkflow[\"outputsFiles\"],\n ctx: RunCtx,\n workflowId: string,\n lastStepId: string | undefined,\n): Promise<void> {\n if (!outputsFiles) return\n if (ctx.workspace === undefined || ctx.artifactsDir === undefined) return\n for (const [key, contract] of Object.entries(outputsFiles)) {\n const rawPath = interpolateFileContractPath(contract.path, workflowId, ctx.runId)\n const abs = isAbsolute(rawPath) ? rawPath : resolve(ctx.workspace, rawPath)\n let out: ArtifactEntry\n try {\n out = await copyIntoArtifacts(lastStepId ?? workflowId, key, abs, ctx.workspace, ctx.artifactsDir, contract.contentType, ctx.usedArtifactNames!)\n } catch {\n if (contract.required === true) {\n throw new MissingArtifactError(key, lastStepId)\n }\n console.warn(\n `[workflow-runtime] outputsFiles.${key} ('${contract.path}') is missing and not marked required — the run still succeeds (AIP-58 §4)`,\n )\n continue\n }\n ctx.onArtifact?.(out)\n }\n}\n\n/**\n * A workflow's `finally` steps ({@link RuntimeWorkflow.finally}): every one\n * runs, in order, without the run's abort signal (cleanup must survive a\n * cancel). After a failed body, a cleanup error is reported on its step and\n * swallowed so the original error wins; after a successful body the first\n * cleanup error is rethrown once every cleanup step has had its turn.\n */\nasync function runFinally(steps: readonly RunStep[], ctx: RunCtx, bodyFailed: boolean): Promise<void> {\n const cleanupCtx: RunCtx = { ...ctx, signal: undefined }\n let firstError: unknown\n for (const step of steps) {\n try {\n const out = await execStep(step, cleanupCtx, undefined, undefined)\n cleanupCtx.state.steps[step.id] = out\n completeStep(cleanupCtx, step.id, out)\n } catch (err) {\n cleanupCtx.onStepFailed?.(step.id, { error: errorMessage(err) })\n if (firstError === undefined) firstError = err\n }\n }\n if (!bodyFailed && firstError !== undefined) throw firstError\n}\n\nasync function runWorkflowInner(\n workflow: RuntimeWorkflow,\n input: unknown,\n hooks: Pick<RunCtx, \"approve\" | \"resume\" | \"onInputRequired\" | \"signal\" | \"agents\" | \"cwd\" | \"workspaceSlug\" | \"workspace\" | \"artifactsDir\" | \"runId\" | \"onArtifact\" | \"cache\" | \"cacheKey\" | \"onStepStart\" | \"onStepComplete\" | \"onStepSkipped\" | \"onStepFailed\" | \"runGateCommand\" | \"onGateReport\" | \"spawned\" | \"usedArtifactNames\">,\n maxTotalCostUsd?: number,\n): Promise<WorkflowRunResult> {\n const state: RunState = { input, steps: {}, costBySession: new Map(), maxTotalCostUsd, cachedHits: new Set() }\n // A subworkflow shares its parent's release scope (a parent step may\n // `sessionRef` a child's session); only the outermost run owns one — same\n // test (`hooks.spawned === undefined`) doubles as \"own a fresh\n // `usedArtifactNames`\", since a subworkflow always passes both down\n // together (see the `\"subworkflow\"` case above).\n const ownsScope = hooks.spawned === undefined\n const ctx: RunCtx = {\n state,\n ...hooks,\n ...(ownsScope ? { spawned: [], usedArtifactNames: new Set<string>() } : {}),\n }\n let lastId: string | undefined\n let bodyFailed = false\n try {\n for (const step of workflow.steps) {\n const out = await execStep(step, ctx, undefined, undefined)\n state.steps[step.id] = out\n completeStep(ctx, step.id, out)\n lastId = step.id\n }\n await checkOutputsFiles(workflow.outputsFiles, ctx, workflow.id, lastId)\n } catch (err) {\n bodyFailed = true\n throw err\n } finally {\n try {\n if (workflow.finally && workflow.finally.length > 0) await runFinally(workflow.finally, ctx, bodyFailed)\n } finally {\n if (ownsScope) await releaseScope(ctx)\n }\n }\n const bindings = view(ctx)\n const output = workflow.output\n ? workflow.output(bindings)\n : lastId !== undefined\n ? state.steps[lastId]\n : undefined\n return { output, bindings }\n}\n\nexport async function runWorkflow(\n args: RunWorkflowArgs,\n): Promise<WorkflowRunResult> {\n return runWorkflowInner(args.workflow, args.input, {\n approve: args.approve,\n resume: args.resume,\n onInputRequired: args.onInputRequired,\n signal: args.signal,\n agents: args.agents,\n cwd: args.cwd,\n workspaceSlug: args.workspaceSlug,\n workspace: args.workspace,\n artifactsDir: args.artifactsDir,\n runId: args.runId,\n onArtifact: args.onArtifact,\n cache: args.cache,\n cacheKey: args.cacheKey,\n onStepStart: args.onStepStart,\n onStepComplete: args.onStepComplete,\n onStepSkipped: args.onStepSkipped,\n onStepFailed: args.onStepFailed,\n runGateCommand: args.runGateCommand,\n onGateReport: args.onGateReport,\n }, args.maxTotalCostUsd)\n}\n","/**\n * compileWorkflowManifest — the connective step between an authored\n * `WORKFLOW.md` and a runnable workflow.\n *\n * AIP-15 ships every piece needed to run a declarative manifest except the\n * seam that joins them: `parseWorkflowManifest` (md + frontmatter → manifest)\n * and `workflowFromManifest` (manifest → `WorkflowHandle`) live in\n * `@agentproto/workflow`; `compileWorkflow` (handle → `RuntimeWorkflow`) lives\n * here. Without this chain an authored `WORKFLOW.md` parses and validates but\n * never reaches the executor. This joins the three so a manifest source string\n * compiles straight to a runnable workflow — no hand-built handle.\n *\n * Framework-pure: the caller owns reading the file off disk (this package does\n * no I/O), and passes the source string in. The tool registry + driver\n * candidates are injected via {@link CompileWorkflowOptions}, same as the\n * hand-built path.\n */\n\nimport {\n parseWorkflowManifest,\n workflowFromManifest,\n} from \"@agentproto/workflow/manifest\"\n\nimport { compileWorkflow } from \"./compile-workflow.js\"\nimport type { CompileWorkflowOptions } from \"./compile-workflow.js\"\nimport type { RuntimeWorkflow } from \"./types.js\"\n\n/**\n * Compile a `WORKFLOW.md` source string into a {@link RuntimeWorkflow} ready\n * for `runWorkflow`. Parses + validates the frontmatter against the AIP-15\n * schema, lifts it to a `WorkflowHandle`, then compiles its step graph against\n * the injected tool registry. Throws on invalid frontmatter (the parser's\n * diagnostic) or an unresolved tool / non-linear step (the compiler's).\n */\nexport function compileWorkflowManifest(\n source: string,\n opts: CompileWorkflowOptions,\n): RuntimeWorkflow {\n const manifest = parseWorkflowManifest(source)\n const handle = workflowFromManifest(manifest)\n return compileWorkflow(handle, opts)\n}\n"]}
|