@warble/codex-local 0.10.0 → 0.11.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/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/ask_prepare.ts","../src/error.ts","../src/dispatch_registry.ts","../src/ir.ts","../src/render_contract.ts","../src/request_transport.ts","../src/target_profile.ts","../src/app_server_transport.ts","../src/config.ts","../src/ask_config.ts","../src/session_types.ts","../src/ask_runtime.ts","../src/enrich_prepare.ts","../src/step_engine.ts","../src/prepare.ts","../src/dispatch_contract.ts","../src/manifest.ts","../src/model_catalog.ts","../src/session.ts","../src/enrich_run.ts","../src/run.ts","../src/events.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { parseArgs } from \"node:util\";\n\nimport { prepareAsk, type AskMcpServerConfig } from \"./ask_prepare.js\";\nimport { CodexAskRuntime } from \"./ask_runtime.js\";\nimport { classifyDispatchContract, supportsSetupAggregate } from \"./dispatch_contract.js\";\nimport { CodexDispatchError } from \"./error.js\";\nimport {\n buildAskManifest,\n buildEnrichManifest,\n buildManifest,\n describeAskTarget,\n describeEnrichTarget,\n describeTarget,\n} from \"./manifest.js\";\nimport { discoverCodexModels } from \"./model_catalog.js\";\nimport { prepareEnrich, type EnrichMcpServerConfig } from \"./enrich_prepare.js\";\nimport { parseIr } from \"./ir.js\";\nimport { prepareAllSetup, prepareSetup, type McpServerConfig } from \"./prepare.js\";\nimport { runEnrich } from \"./enrich_run.js\";\nimport { runSetup } from \"./run.js\";\n\nconst USAGE =\n \"usage: warble-codex-local <dispatch|manifest|describe> <ir.json> [request] \" +\n \"--component <id> --server-command <absolute-path> [options]\\n\" +\n \" warble-codex-local list-models [--project <dir>] [--codex-home <dir>] [--codex-bin <path>] [--timeout <ms>]\";\n\nfunction fail(message: string): never {\n process.stderr.write(`error: ${message}\\n`);\n process.exit(1);\n}\n\nfunction valuesList(value: string[] | string | undefined): string[] {\n if (value === undefined) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nasync function main(): Promise<void> {\n const { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n component: { type: \"string\" },\n model: { type: \"string\" },\n project: { type: \"string\" },\n out: { type: \"string\" },\n timeout: { type: \"string\" },\n \"codex-bin\": { type: \"string\" },\n server: { type: \"string\" },\n \"server-command\": { type: \"string\" },\n \"server-arg\": { type: \"string\", multiple: true },\n \"source-tool\": { type: \"string\", multiple: true },\n \"context-tool\": { type: \"string\", multiple: true },\n \"inspect-tool\": { type: \"string\", multiple: true },\n \"query-tool\": { type: \"string\", multiple: true },\n \"semantic-tool\": { type: \"string\", multiple: true },\n \"raw-material-tool\": { type: \"string\", multiple: true },\n \"orchestrator-model\": { type: \"string\" },\n \"cheap-model\": { type: \"string\" },\n \"strong-model\": { type: \"string\" },\n \"codex-home\": { type: \"string\" },\n \"stream-json\": { type: \"boolean\" },\n },\n });\n const [subcommand, irPathArg, request] = positionals;\n if (subcommand === \"list-models\") {\n if (irPathArg !== undefined || request !== undefined) fail(\"list-models does not take an <ir.json> or request\");\n const timeout = values.timeout === undefined ? undefined : Number(values.timeout);\n if (timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0)) fail(\"--timeout must be a positive number\");\n const catalog = await discoverCodexModels({\n ...(values.project ? { cwd: values.project } : {}),\n ...(values[\"codex-home\"] ? { codexHome: values[\"codex-home\"] } : {}),\n ...(values[\"codex-bin\"] ? { codexBin: values[\"codex-bin\"] } : {}),\n ...(timeout !== undefined ? { timeoutMs: timeout } : {}),\n });\n process.stdout.write(`${JSON.stringify(catalog)}\\n`);\n return;\n }\n if (![\"dispatch\", \"manifest\", \"describe\"].includes(subcommand ?? \"\")) fail(USAGE);\n if (!irPathArg) fail(\"missing <ir.json>\");\n if (!values[\"server-command\"]) fail(\"missing --server-command\");\n const raw = readFileSync(resolve(irPathArg), \"utf8\");\n const ir = parseIr(raw);\n const model = values.model ?? \"gpt-5.4\";\n\n if (!values.component && subcommand !== \"dispatch\" && supportsSetupAggregate(ir)) {\n const mcp: McpServerConfig = {\n name: values.server ?? \"setup\",\n command: resolve(values[\"server-command\"]),\n args: valuesList(values[\"server-arg\"]),\n toolsByCapability: {\n source_connect: valuesList(values[\"source-tool\"]),\n context_build: valuesList(values[\"context-tool\"]),\n },\n };\n const prepared = prepareAllSetup(raw, { model, mcp });\n const output = subcommand === \"manifest\" ? buildManifest(prepared) : describeTarget(prepared);\n const text = `${JSON.stringify(output, null, 2)}\\n`;\n if (values.out) writeFileSync(resolve(values.out), text);\n else process.stdout.write(text);\n return;\n }\n\n const component = values.component;\n if (!component) fail(`${subcommand} requires --component for the selected component execution contract`);\n const contract = classifyDispatchContract(ir, component);\n\n if (contract === \"enrich\") {\n const enrichMcp: EnrichMcpServerConfig = {\n name: values.server ?? \"enrich\",\n command: resolve(values[\"server-command\"]),\n args: valuesList(values[\"server-arg\"]),\n toolsByCapability: {\n semantic_introspection: valuesList(values[\"semantic-tool\"]),\n raw_material_read: valuesList(values[\"raw-material-tool\"]),\n },\n };\n const preparedEnrich = prepareEnrich({ ir: raw, component, model, mcp: enrichMcp });\n if (subcommand === \"manifest\" || subcommand === \"describe\") {\n const output =\n subcommand === \"manifest\"\n ? buildEnrichManifest(preparedEnrich)\n : describeEnrichTarget(preparedEnrich);\n const text = `${JSON.stringify(output, null, 2)}\\n`;\n if (values.out) writeFileSync(resolve(values.out), text);\n else process.stdout.write(text);\n return;\n }\n if (!request) fail(\"dispatch requires a request\");\n if (!values[\"codex-home\"]) fail(\"selected component requires --codex-home\");\n const result = await runEnrich(preparedEnrich, request, {\n codexHome: resolve(values[\"codex-home\"]),\n cwd: resolve(values.project ?? \".\"),\n externalAuthentication: \"provisioned\",\n ...(values[\"codex-bin\"] ? { codexBin: resolve(values[\"codex-bin\"]) } : {}),\n ...(values.timeout ? { timeoutMs: Number(values.timeout) } : {}),\n ...(values[\"stream-json\"]\n ? { onEvent: (event) => process.stdout.write(`${JSON.stringify(event)}\\n`) }\n : {}),\n });\n if (!values[\"stream-json\"]) process.stdout.write(`${result.finalText}\\n`);\n return;\n }\n\n if (contract === \"ask\") {\n for (const option of [\"orchestrator-model\", \"cheap-model\", \"strong-model\"] as const) {\n if (!values[option]) fail(`selected component requires --${option}`);\n }\n const askMcp: AskMcpServerConfig = {\n name: values.server ?? \"wren\",\n command: resolve(values[\"server-command\"]),\n args: valuesList(values[\"server-arg\"]),\n toolsByStep: {\n resolve_intent: valuesList(values[\"inspect-tool\"]),\n generate_sql: valuesList(values[\"query-tool\"]),\n repair_sql: valuesList(values[\"query-tool\"]),\n plan_dashboard: valuesList(values[\"inspect-tool\"]),\n compose_layout: valuesList(values[\"query-tool\"]),\n },\n };\n const preparedAsk = prepareAsk({\n ir: raw,\n component,\n models: {\n orchestrator: values[\"orchestrator-model\"]!,\n cheap: values[\"cheap-model\"]!,\n strong: values[\"strong-model\"]!,\n },\n mcp: askMcp,\n });\n if (subcommand === \"manifest\" || subcommand === \"describe\") {\n const output =\n subcommand === \"manifest\"\n ? buildAskManifest(preparedAsk)\n : describeAskTarget(preparedAsk);\n const text = `${JSON.stringify(output, null, 2)}\\n`;\n if (values.out) writeFileSync(resolve(values.out), text);\n else process.stdout.write(text);\n return;\n }\n if (!request) fail(\"dispatch requires a request\");\n if (!values[\"codex-home\"]) fail(\"selected component requires --codex-home\");\n const runtime = await CodexAskRuntime.connect(preparedAsk, {\n codexHome: resolve(values[\"codex-home\"]),\n cwd: resolve(values.project ?? \".\"),\n externalAuthentication: \"provisioned\",\n ...(values[\"codex-bin\"] ? { codexBin: resolve(values[\"codex-bin\"]) } : {}),\n ...(values.timeout ? { turnTimeoutMs: Number(values.timeout) } : {}),\n ...(values[\"stream-json\"]\n ? { onAskEvent: (event) => process.stdout.write(`${JSON.stringify(event)}\\n`) }\n : {}),\n });\n try {\n const session = await runtime.start();\n const result = await runtime.run(session, request);\n if (values[\"stream-json\"]) {\n process.stdout.write(`${JSON.stringify({ t: \"answer\", text: result.finalText })}\\n`);\n } else {\n process.stdout.write(`${result.finalText}\\n`);\n }\n } finally {\n await runtime.close();\n }\n return;\n }\n\n const mcp: McpServerConfig = {\n name: values.server ?? \"setup\",\n command: resolve(values[\"server-command\"]),\n args: valuesList(values[\"server-arg\"]),\n toolsByCapability: {\n source_connect: valuesList(values[\"source-tool\"]),\n context_build: valuesList(values[\"context-tool\"]),\n },\n };\n const prepared = prepareSetup({ ir: raw, component, model, mcp });\n if (subcommand === \"manifest\" || subcommand === \"describe\") {\n const output = subcommand === \"manifest\" ? buildManifest([prepared]) : describeTarget([prepared]);\n const text = `${JSON.stringify(output, null, 2)}\\n`;\n if (values.out) writeFileSync(resolve(values.out), text);\n else process.stdout.write(text);\n return;\n }\n\n if (!request) fail(\"dispatch requires a request\");\n const result = await runSetup(prepared, {\n cwd: resolve(values.project ?? \".\"),\n request,\n ...(values[\"codex-bin\"] ? { codexBin: resolve(values[\"codex-bin\"]) } : {}),\n ...(values.timeout ? { timeoutMs: Number(values.timeout) } : {}),\n ...(values[\"stream-json\"]\n ? {\n onEvent: (event) => process.stdout.write(`${JSON.stringify(event)}\\n`),\n }\n : {}),\n });\n if (!values[\"stream-json\"]) process.stdout.write(`${result.finalText}\\n`);\n}\n\nmain().catch((error: unknown) => {\n if (error instanceof CodexDispatchError) fail(error.message);\n fail(error instanceof Error ? error.stack ?? error.message : String(error));\n});\n","import { isAbsolute } from \"node:path\";\n\nimport { CodexDispatchError } from \"./error.js\";\nimport { assertDispatchableComponentIdentity } from \"./dispatch_registry.js\";\nimport {\n parseIr,\n SUPPORTED_IR_VERSION,\n TARGET,\n type ComponentNode,\n type LlmCall,\n type WarbleIr,\n} from \"./ir.js\";\nimport type { CapabilityResolution } from \"./prepare.js\";\nimport { parseDashboardRenderBlockContracts } from \"./render_contract.js\";\nimport { REQUEST_TRANSPORT_SERVER } from \"./request_transport.js\";\nimport {\n ASK_ANSWER_CAPABILITIES,\n ASK_DASHBOARD_CAPABILITIES,\n guardrailMatches,\n hasExactCapabilities,\n resolveCapabilities,\n} from \"./target_profile.js\";\n\nexport interface AskMcpServerConfig {\n name: string;\n command: string;\n args?: string[];\n toolsByStep: Record<string, string[]>;\n}\n\nexport interface AskTierModels {\n orchestrator: string;\n cheap: string;\n strong: string;\n}\n\nexport interface AskWhenGuard {\n guard: \"on_failure\";\n target: string;\n}\n\nexport interface PreparedAskStep {\n name: string;\n role: string;\n tier: \"cheap\" | \"strong\";\n model: string;\n prompt: string;\n consumes: string[];\n produces: string;\n conditional: boolean;\n when: AskWhenGuard | null;\n enabledTools: string[];\n requireSuccessfulTool: boolean;\n}\n\nexport type AnalyticalExecutionKind = \"answer_query\" | \"generate_dashboard\";\n\nexport interface PreparedAskComponent {\n target: typeof TARGET;\n profile: string;\n node: ComponentNode;\n componentId: string;\n steps: PreparedAskStep[];\n capabilities: CapabilityResolution[];\n mcp: AskMcpServerConfig;\n models: AskTierModels;\n executionKind: AnalyticalExecutionKind;\n maxRepairAttempts: number;\n}\n\nexport interface PrepareAskInput {\n ir: string | WarbleIr;\n component: string;\n models: AskTierModels;\n mcp: AskMcpServerConfig;\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n\nconst TOOLS_BY_EXECUTION_KIND = {\n answer_query: [[\"get_context\"], [\"run_sql\"], [\"run_sql\"]],\n generate_dashboard: [[\"get_context\"], [\"run_sql\"]],\n} as const;\n\nfunction requireNonEmpty(value: string, field: string): void {\n if (value.trim().length === 0) throw new CodexDispatchError(`${field} must not be empty`);\n}\n\nfunction parseWhen(step: LlmCall): AskWhenGuard | null {\n if (!step.conditional) {\n if (step.when !== null) {\n throw new CodexDispatchError(`step '${step.name}' is unconditional but has a when guard`);\n }\n return null;\n }\n if (\n typeof step.when !== \"object\" ||\n step.when === null ||\n Array.isArray(step.when) ||\n (step.when as Record<string, unknown>)[\"guard\"] !== \"on_failure\" ||\n typeof (step.when as Record<string, unknown>)[\"target\"] !== \"string\"\n ) {\n throw new CodexDispatchError(\n `step '${step.name}' wall-hit: Ask repair requires on_failure(target)`,\n );\n }\n return {\n guard: \"on_failure\",\n target: (step.when as Record<string, string>)[\"target\"]!,\n };\n}\n\nfunction validateCommonAnalyticalShape(node: ComponentNode): void {\n if (\n node.type !== \"analytical\" ||\n node.realization_kind !== \"skill\" ||\n node.trigger.kind !== \"one_shot\" ||\n node.effect.outcome.kind !== \"none\"\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: Codex analytical execution requires analytical/skill/one_shot/none`,\n );\n }\n if (node.context_binding.binding_mode !== \"runtime_selected\") {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: Codex analytical execution requires runtime_selected context binding`,\n );\n }\n}\n\n/**\n * Generic IR-driven chain validator shared by both Ask shapes (answer_query, generate_dashboard).\n * Enforces the topology the runtime can honestly execute: any step count, any\n * tier per step (cheap|strong, not position-bound), each non-first unconditional step consumes\n * exactly its immediately-preceding step's output, each conditional step is an on_failure repair\n * targeting its immediately-preceding step and consumes that step's output, and — because the\n * runtime aligns `active.spawns[i]` to `steps[i]` with no gap-skipping support, and because an\n * always-run step cannot honestly depend on a conditionally-produced value — no unconditional\n * step may follow a conditional one (repairs form a maximal trailing suffix).\n */\nfunction validateStepChain(node: ComponentNode): void {\n const calls = node.llm_calls;\n if (calls.length === 0) {\n throw new CodexDispatchError(`component '${node.id}' wall-hit: Ask requires at least one llm_call`);\n }\n let sawConditional = false;\n calls.forEach((call, index) => {\n if (call.tier !== \"cheap\" && call.tier !== \"strong\") {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${call.name}' has unsupported tier '${call.tier}'`,\n );\n }\n if (call.produces === null) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${call.name}' must produce a named output`,\n );\n }\n const when = parseWhen(call);\n if (index === 0) {\n if (call.conditional || call.consumes.length !== 0) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: first Ask step must be unconditional with no consumes and one output`,\n );\n }\n return;\n }\n const previous = calls[index - 1]!;\n if (call.conditional) {\n if (\n when?.target !== previous.name ||\n call.consumes.length !== 1 ||\n call.consumes[0] !== previous.produces\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${call.name}' must be an on_failure repair of the immediately preceding step '${previous.name}'`,\n );\n }\n sawConditional = true;\n return;\n }\n if (sawConditional) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: an unconditional step cannot follow a repair step`,\n );\n }\n if (call.consumes.length !== 1 || call.consumes[0] !== previous.produces) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${call.name}' must consume exactly the preceding step's output`,\n );\n }\n });\n}\n\nfunction validateAnswerShape(node: ComponentNode): void {\n validateCommonAnalyticalShape(node);\n validateStepChain(node);\n\n if (!hasExactCapabilities(node.required_capabilities, ASK_ANSWER_CAPABILITIES)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: Ask capability set must be read-only SQL plus cheap/strong per-step tiering`,\n );\n }\n const guards = new Map(node.guardrails.map((guard) => [guard.name, guard]));\n if (\n guards.size !== 4 ||\n !guardrailMatches(guards.get(\"read_only_execution\"), \"read_only_execution\") ||\n !guardrailMatches(guards.get(\"deterministic_gate\"), \"deterministic_gate\") ||\n !guardrailMatches(guards.get(\"row_limit\"), \"row_limit\") ||\n !guardrailMatches(guards.get(\"statement_timeout\"), \"statement_timeout\")\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: Ask guardrails must match the locked read-only/deterministic and bounded row/timeout contract`,\n );\n }\n}\n\nfunction validateDashboardShape(node: ComponentNode): void {\n validateCommonAnalyticalShape(node);\n validateStepChain(node);\n\n if (!hasExactCapabilities(node.required_capabilities, ASK_DASHBOARD_CAPABILITIES)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: dashboard capability set must match read-only SQL, build, render, artifact, and cheap/strong per-step tiering`,\n );\n }\n const guards = new Map(node.guardrails.map((guard) => [guard.name, guard]));\n if (\n guards.size !== 2 ||\n !guardrailMatches(guards.get(\"read_only_execution\"), \"read_only_execution\") ||\n !guardrailMatches(guards.get(\"artifact_write\"), \"artifact_write\")\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: dashboard guardrails must be locked read-only execution plus scoped artifact_write`,\n );\n }\n if (node.effect.render_blocks.length === 0) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: dashboard render contract must declare at least one render block type`,\n );\n }\n // Wall-hits early on a structurally malformed render-block declaration using the\n // same parse that later validates the terminal envelope (render_contract.ts) — never\n // a second, independent check of the declared contract's *content*.\n parseDashboardRenderBlockContracts(node.effect.render_blocks);\n}\n\nfunction executionKind(node: ComponentNode): AnalyticalExecutionKind {\n const capabilities = new Set(node.required_capabilities);\n if (capabilities.has(\"render_contract\") || capabilities.has(\"artifact_write\")) {\n validateDashboardShape(node);\n return \"generate_dashboard\";\n }\n validateAnswerShape(node);\n return \"answer_query\";\n}\n\nexport function matchesAskContractShape(node: ComponentNode): boolean {\n try {\n executionKind(node);\n return true;\n } catch (error) {\n if (error instanceof CodexDispatchError) return false;\n throw error;\n }\n}\n\n/**\n * The specific reason a component's IR shape does not match either Ask contract (answer_query or\n * generate_dashboard), or null when it matches one of them. Mirrors `matchesAskContractShape`'s\n * try/catch but preserves the validator's own wall-hit message so a caller classifying across all\n * three families can surface precisely which structural expectation failed.\n */\nexport function askContractMismatchReason(node: ComponentNode): string | null {\n try {\n executionKind(node);\n return null;\n } catch (error) {\n if (error instanceof CodexDispatchError) return error.message;\n throw error;\n }\n}\n\nfunction roleName(stepName: string): string {\n const value = `warble_${stepName}`.replace(/[^A-Za-z0-9_-]/g, \"_\");\n if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(value)) {\n throw new CodexDispatchError(`step '${stepName}' cannot be mapped to a Codex agent role`);\n }\n return value;\n}\n\nexport function prepareAsk(input: PrepareAskInput): PreparedAskComponent {\n const ir = typeof input.ir === \"string\" ? parseIr(input.ir) : input.ir;\n if (ir.warble_ir_version !== SUPPORTED_IR_VERSION) {\n throw new CodexDispatchError(\n `unsupported warble_ir_version '${ir.warble_ir_version}' (supported: ${SUPPORTED_IR_VERSION})`,\n );\n }\n const node = ir.components.find((candidate) => candidate.id === input.component);\n if (!node) {\n throw new CodexDispatchError(\n `component '${input.component}' was not found in profile '${ir.profile}'`,\n );\n }\n assertDispatchableComponentIdentity(node);\n const kind = executionKind(node);\n if (!/^[A-Za-z0-9_-]+$/.test(input.mcp.name)) {\n throw new CodexDispatchError(\n `MCP server name '${input.mcp.name}' must contain only letters, digits, '_' or '-'`,\n );\n }\n if (input.mcp.name === REQUEST_TRANSPORT_SERVER) {\n throw new CodexDispatchError(`MCP server name '${input.mcp.name}' is reserved by the Ask request transport`);\n }\n if (!isAbsolute(input.mcp.command)) {\n throw new CodexDispatchError(\"Ask MCP server command must be absolute\");\n }\n requireNonEmpty(input.models.orchestrator, \"orchestrator model binding\");\n requireNonEmpty(input.models.cheap, \"cheap-tier model binding\");\n requireNonEmpty(input.models.strong, \"strong-tier model binding\");\n\n const steps = node.llm_calls.map((step, index): PreparedAskStep => {\n const tier = step.tier;\n if (tier !== \"cheap\" && tier !== \"strong\") {\n throw new CodexDispatchError(`step '${step.name}' has unsupported tier '${tier}'`);\n }\n const enabledTools = unique(input.mcp.toolsByStep[step.name] ?? []);\n const expectedTools = TOOLS_BY_EXECUTION_KIND[kind][index];\n if (expectedTools === undefined) {\n throw new CodexDispatchError(\n `step '${step.name}' has no declared MCP tool allowlist for target index ${index}`,\n );\n }\n if (\n enabledTools.length !== expectedTools.length ||\n enabledTools.some((tool, toolIndex) => tool !== expectedTools[toolIndex])\n ) {\n throw new CodexDispatchError(\n `step '${step.name}' requires exact MCP tools: ${expectedTools.join(\", \")}`,\n );\n }\n if (step.produces === null) {\n throw new CodexDispatchError(`step '${step.name}' must produce a named slot`);\n }\n return {\n name: step.name,\n role: roleName(step.name),\n tier,\n model: input.models[tier],\n prompt: step.prompt,\n consumes: [...step.consumes],\n produces: step.produces,\n conditional: step.conditional,\n when: parseWhen(step),\n enabledTools,\n requireSuccessfulTool: kind === \"generate_dashboard\" || index > 0,\n };\n });\n\n return {\n target: TARGET,\n profile: ir.profile,\n node,\n componentId: node.id,\n steps,\n capabilities: resolveCapabilities(node.required_capabilities, input.mcp.name),\n mcp: input.mcp,\n models: input.models,\n executionKind: kind,\n maxRepairAttempts: steps.filter((step) => step.conditional).length,\n };\n}\n","export class CodexDispatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodexDispatchError\";\n }\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport type { ComponentNode } from \"./ir.js\";\n\n/**\n * Refuses a component on IR grounds alone, before any family-specific shape check runs: this\n * target only ever executes `skill`-realized components (`realization_kind: skill | tool |\n * gated-tool` — every family's own shape validator already requires exactly `skill` too, so this\n * mirrors that, just earlier and uniformly). A `tool`/`gated-tool` component is host-owned by\n * definition — it names a lifecycle contract this target has no approval channel or write\n * authority to run, regardless of what required_capabilities it happens to declare.\n *\n * A component's id/verb carries no dispatch meaning (invariant #1): a genuinely host-owned\n * component wall-hits under any name, and a `skill`-realized component that declares only\n * capabilities a family here can honestly realize is dispatchable under any name — including one\n * that collides with a host-owned component's. Rejecting on capability content beyond\n * `realization_kind` is left to each family's own shape validator, which already enforces its\n * exact allowed capability set and reports which specific capability/shape expectation failed;\n * duplicating that check here would only replace those precise, family-scoped diagnostics with a\n * generic message.\n */\nexport function assertDispatchableComponentIdentity(node: ComponentNode): void {\n if (node.realization_kind !== \"skill\") {\n throw new CodexDispatchError(\n `component '${node.id}' is host-executed and cannot be dispatched by codex:local: ` +\n `realization_kind '${node.realization_kind}' is not 'skill'`,\n );\n }\n}\n","import { CodexDispatchError } from \"./error.js\";\n\nexport const TARGET = \"codex:local\" as const;\nexport const SUPPORTED_IR_VERSION = \"0.6\" as const;\n\nexport interface LlmCall {\n name: string;\n tier: string;\n prompt: string;\n consumes: string[];\n produces: string | null;\n conditional: boolean;\n when: unknown;\n}\n\nexport interface Guardrail {\n name: string;\n locked: boolean;\n scope?: string;\n threshold?: number;\n}\n\nexport interface ComponentNode {\n id: string;\n verb: string;\n type: string;\n realization_kind: string;\n llm_calls: LlmCall[];\n required_capabilities: string[];\n guardrails: Guardrail[];\n trigger: { kind: string };\n effect: {\n outcome: { kind: string };\n render_blocks: unknown[];\n };\n context_binding: {\n binding_mode: string;\n project: string;\n };\n}\n\nexport interface WarbleIr {\n warble_ir_version: string;\n profile: string;\n components: ComponentNode[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringArray(value: unknown, field: string): string[] {\n if (!Array.isArray(value) || !value.every((entry) => typeof entry === \"string\")) {\n throw new CodexDispatchError(`${field} must be an array of strings`);\n }\n return value;\n}\n\nfunction parseCall(value: unknown, componentId: string): LlmCall {\n if (!isRecord(value)) {\n throw new CodexDispatchError(`component '${componentId}' has a malformed llm_call`);\n }\n const { name, tier, prompt } = value;\n if (\n typeof name !== \"string\" ||\n typeof tier !== \"string\" ||\n typeof prompt !== \"string\" ||\n typeof value[\"conditional\"] !== \"boolean\" ||\n (value[\"produces\"] !== null && typeof value[\"produces\"] !== \"string\")\n ) {\n throw new CodexDispatchError(\n `component '${componentId}' llm_call has malformed name/tier/prompt/conditional/produces`,\n );\n }\n return {\n name,\n tier,\n prompt,\n consumes: stringArray(value[\"consumes\"] ?? [], `${componentId}.${name}.consumes`),\n produces: value[\"produces\"],\n conditional: value[\"conditional\"],\n when: value[\"when\"] ?? null,\n };\n}\n\nfunction parseGuardrail(value: unknown, componentId: string): Guardrail {\n if (\n !isRecord(value) ||\n typeof value[\"name\"] !== \"string\" ||\n typeof value[\"locked\"] !== \"boolean\"\n ) {\n throw new CodexDispatchError(`component '${componentId}' has a malformed guardrail`);\n }\n return {\n name: value[\"name\"],\n locked: value[\"locked\"],\n ...(typeof value[\"scope\"] === \"string\" ? { scope: value[\"scope\"] } : {}),\n ...(typeof value[\"threshold\"] === \"number\" ? { threshold: value[\"threshold\"] } : {}),\n };\n}\n\nfunction parseComponent(value: unknown): ComponentNode {\n if (!isRecord(value) || typeof value[\"id\"] !== \"string\") {\n throw new CodexDispatchError(\"IR component must be an object with a string id\");\n }\n const id = value[\"id\"];\n const trigger = value[\"trigger\"];\n const effect = value[\"effect\"];\n const outcome = isRecord(effect) ? effect[\"outcome\"] : null;\n const context = value[\"context_binding\"];\n if (\n typeof value[\"verb\"] !== \"string\" ||\n typeof value[\"type\"] !== \"string\" ||\n typeof value[\"realization_kind\"] !== \"string\" ||\n !Array.isArray(value[\"llm_calls\"]) ||\n !Array.isArray(value[\"guardrails\"]) ||\n !isRecord(trigger) ||\n typeof trigger[\"kind\"] !== \"string\" ||\n !isRecord(effect) ||\n !isRecord(outcome) ||\n typeof outcome[\"kind\"] !== \"string\" ||\n !Array.isArray(effect[\"render_blocks\"]) ||\n !isRecord(context) ||\n typeof context[\"binding_mode\"] !== \"string\" ||\n typeof context[\"project\"] !== \"string\"\n ) {\n throw new CodexDispatchError(`component '${id}' is missing required IR fields`);\n }\n return {\n id,\n verb: value[\"verb\"],\n type: value[\"type\"],\n realization_kind: value[\"realization_kind\"],\n llm_calls: value[\"llm_calls\"].map((call) => parseCall(call, id)),\n required_capabilities: stringArray(\n value[\"required_capabilities\"] ?? [],\n `${id}.required_capabilities`,\n ),\n guardrails: value[\"guardrails\"].map((guard) => parseGuardrail(guard, id)),\n trigger: { kind: trigger[\"kind\"] },\n effect: {\n outcome: { kind: outcome[\"kind\"] },\n render_blocks: effect[\"render_blocks\"],\n },\n context_binding: {\n binding_mode: context[\"binding_mode\"],\n project: context[\"project\"],\n },\n };\n}\n\nexport function parseIr(raw: string): WarbleIr {\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch (error) {\n throw new CodexDispatchError(`invalid IR JSON: ${String(error)}`);\n }\n if (\n !isRecord(value) ||\n typeof value[\"warble_ir_version\"] !== \"string\" ||\n typeof value[\"profile\"] !== \"string\" ||\n !Array.isArray(value[\"components\"])\n ) {\n throw new CodexDispatchError(\"IR requires warble_ir_version, profile, and components\");\n }\n if (value[\"warble_ir_version\"] !== SUPPORTED_IR_VERSION) {\n throw new CodexDispatchError(\n `unsupported warble_ir_version '${value[\"warble_ir_version\"]}' (supported: ${SUPPORTED_IR_VERSION})`,\n );\n }\n return {\n warble_ir_version: value[\"warble_ir_version\"],\n profile: value[\"profile\"],\n components: value[\"components\"].map(parseComponent),\n };\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport type { ComponentNode } from \"./ir.js\";\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\nexport interface DashboardRenderEnvelope {\n blocks: JsonRecord[];\n summary?: string;\n verified: boolean;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Parses an IR-declared dashboard render-block contract (`effect.render_blocks`)\n * into a type -> field-type map, loud-failing on any structurally malformed\n * declaration. This is the single source of truth for the render contract's\n * shape: Ask prepare time calls it to wall-hit early on a malformed IR, and\n * envelope validation below calls the same function against the same IR to\n * validate the actual terminal value — never a second, independent\n * implementation of this parse.\n */\nexport function parseDashboardRenderBlockContracts(\n renderBlocks: readonly unknown[],\n): Map<string, Record<string, string>> {\n const contracts = new Map<string, Record<string, string>>();\n for (const entry of renderBlocks) {\n if (!isRecord(entry) || typeof entry[\"type\"] !== \"string\" || !isRecord(entry[\"fields\"])) {\n throw new CodexDispatchError(\"dashboard IR contains a malformed render block contract\");\n }\n const fields = entry[\"fields\"];\n if (!Object.values(fields).every((field) => typeof field === \"string\")) {\n throw new CodexDispatchError(\"dashboard IR contains a malformed render field contract\");\n }\n contracts.set(entry[\"type\"], fields as Record<string, string>);\n }\n return contracts;\n}\n\nfunction validatePrimitive(value: unknown, type: string, context: string): void {\n if (type.endsWith(\"?\")) {\n if (value === undefined || value === null) return;\n validatePrimitive(value, type.slice(0, -1), context);\n return;\n }\n if (type.endsWith(\"[]\")) {\n if (!Array.isArray(value)) throw new CodexDispatchError(`${context} must be an array`);\n const itemType = type.slice(0, -2);\n for (const [index, item] of value.entries()) {\n validatePrimitive(item, itemType, `${context}[${index}]`);\n }\n return;\n }\n if (type.includes(\"|\")) {\n const alternatives = type.split(\"|\");\n if (alternatives.includes(\"string\") && typeof value === \"string\") return;\n if (alternatives.includes(\"number\") && typeof value === \"number\" && Number.isFinite(value)) return;\n if (typeof value === \"string\" && alternatives.includes(value)) return;\n throw new CodexDispatchError(`${context} does not match '${type}'`);\n }\n if (type === \"string\" && typeof value === \"string\") return;\n if (type === \"number\" && typeof value === \"number\" && Number.isFinite(value)) return;\n if (type === \"boolean\" && typeof value === \"boolean\") return;\n if (type === \"row\" && isRecord(value)) return;\n throw new CodexDispatchError(`${context} does not match '${type}'`);\n}\n\nexport function validateDashboardRenderEnvelope(\n value: unknown,\n node: ComponentNode,\n): DashboardRenderEnvelope {\n if (!isRecord(value)) throw new CodexDispatchError(\"dashboard output must be a JSON object\");\n const keys = Object.keys(value);\n if (\n keys.some((key) => !new Set([\"blocks\", \"summary\", \"verified\"]).has(key)) ||\n !Array.isArray(value[\"blocks\"]) ||\n value[\"blocks\"].length === 0 ||\n typeof value[\"verified\"] !== \"boolean\" ||\n (value[\"summary\"] !== undefined && typeof value[\"summary\"] !== \"string\")\n ) {\n throw new CodexDispatchError(\n \"dashboard output requires only non-empty blocks, optional summary, and boolean verified\",\n );\n }\n\n const contracts = parseDashboardRenderBlockContracts(node.effect.render_blocks);\n\n const blocks = value[\"blocks\"].map((entry, index): JsonRecord => {\n if (!isRecord(entry) || typeof entry[\"type\"] !== \"string\") {\n throw new CodexDispatchError(`dashboard block[${index}] requires a string type`);\n }\n const fields = contracts.get(entry[\"type\"]);\n if (!fields) {\n throw new CodexDispatchError(`dashboard block[${index}] uses undeclared type '${entry[\"type\"]}'`);\n }\n const allowed = new Set([\"type\", ...Object.keys(fields)]);\n if (Object.keys(entry).some((key) => !allowed.has(key))) {\n throw new CodexDispatchError(`dashboard block[${index}] contains undeclared fields`);\n }\n const normalized = { ...entry };\n for (const [field, type] of Object.entries(fields)) {\n validatePrimitive(normalized[field], type, `dashboard block[${index}].${field}`);\n // JSON producers commonly spell an absent optional value as null. The\n // consumer wire contract represents absence by omitting the field, so\n // canonicalize both accepted forms before emitting the terminal value.\n if (type.endsWith(\"?\") && normalized[field] === null) delete normalized[field];\n }\n return normalized;\n });\n return {\n blocks,\n ...(typeof value[\"summary\"] === \"string\" ? { summary: value[\"summary\"] } : {}),\n verified: value[\"verified\"],\n };\n}\n","export const REQUEST_TRANSPORT_SERVER = \"warble_request_transport\";\nexport const REQUEST_TRANSPORT_TOOL = \"get_original_request\";\nexport const STEP_TRANSPORT_TOOL = \"get_step_request\";\n","import { CodexDispatchError } from \"./error.js\";\nimport type { Guardrail } from \"./ir.js\";\n\n// This module is codex:local's single answer to two questions every family validator used to\n// answer separately: \"what can this target honestly realize, and how\" (capability →\n// realization) and \"what does a guardrail occurrence have to look like to count as enforced\"\n// (guardrail → enforcement). Setup, Ask, and Enrich preparers all read from here instead of\n// each carrying its own literal capability sets and scattered guardrail assertions.\n//\n// codex:local's honesty posture is deliberate and non-negotiable: no capability that would\n// require a cwd-scoped native read or write primitive is ever claimed native here. Codex\n// child agents get only a per-step MCP allowlist and this target has no native read\n// primitive — unlike claude-agent-sdk's SDK-level Read tool — so every data/context/\n// introspection capability (source_connect, context_build, semantic_introspection,\n// raw_material_read, sql_execution:read_only) resolves `realize-via` an allowlisted MCP\n// tool, no matter how tempting a single shared table makes native alignment look. This is\n// narrower than \"only llm:* is native\": genbi_build and render_contract are also native,\n// because the target validates the render envelope itself and borrows nothing from an MCP\n// tool to do it; artifact_write stays realize-via because the consumer persists the\n// artifact, never this target.\n\nexport type CapabilityOutcome = \"native\" | \"realize-via\";\n\nexport interface CapabilityResolution {\n capability: string;\n outcome: CapabilityOutcome;\n via: string | null;\n}\n\ninterface CapabilityRealizationEntry {\n outcome: CapabilityOutcome;\n /** A fixed native `via`, or a function of the invocation's configured MCP server name. */\n via: string | null | ((mcpName: string) => string);\n}\n\nconst mcpVia = (mcpName: string): string => `mcp:${mcpName}`;\n\n/** The target-level table: every capability codex:local can honestly resolve, and how. */\nexport const CAPABILITY_REALIZATION: Readonly<Record<string, CapabilityRealizationEntry>> = {\n \"llm:strong\": { outcome: \"native\", via: null },\n \"llm:cheap\": { outcome: \"native\", via: null },\n \"llm:per_step_tier\": { outcome: \"native\", via: null },\n source_connect: { outcome: \"realize-via\", via: mcpVia },\n context_build: { outcome: \"realize-via\", via: mcpVia },\n semantic_introspection: { outcome: \"realize-via\", via: mcpVia },\n raw_material_read: { outcome: \"realize-via\", via: mcpVia },\n \"sql_execution:read_only\": { outcome: \"realize-via\", via: mcpVia },\n genbi_build: { outcome: \"native\", via: \"validated-render-envelope\" },\n render_contract: { outcome: \"native\", via: \"validated-render-envelope\" },\n artifact_write: { outcome: \"realize-via\", via: \"consumer-persisted-render-envelope\" },\n};\n\n/**\n * Resolves a component's required capabilities against the target-level table, in the order\n * they were declared. Throws if a capability has no entry — this is a defensive backstop only:\n * every caller validates the exact capability set before reaching this point, so an unresolved\n * capability here means a family's shape check let something through it shouldn't have.\n */\nexport function resolveCapabilities(\n requiredCapabilities: readonly string[],\n mcpName: string,\n): CapabilityResolution[] {\n return requiredCapabilities.map((capability) => {\n const entry = CAPABILITY_REALIZATION[capability];\n if (!entry) {\n throw new CodexDispatchError(`capability '${capability}' has no realization on codex:local`);\n }\n return {\n capability,\n outcome: entry.outcome,\n via: typeof entry.via === \"function\" ? entry.via(mcpName) : entry.via,\n };\n });\n}\n\n/** True iff `requiredCapabilities` is exactly `expected` (same size, same members). */\nexport function hasExactCapabilities(\n requiredCapabilities: readonly string[],\n expected: ReadonlySet<string>,\n): boolean {\n return (\n requiredCapabilities.length === expected.size &&\n requiredCapabilities.every((capability) => expected.has(capability))\n );\n}\n\n// --- Setup family capability grouping ---\n\nexport const SETUP_DOMAIN_CAPABILITIES = [\"source_connect\", \"context_build\"] as const;\nexport type SetupDomainCapability = (typeof SETUP_DOMAIN_CAPABILITIES)[number];\n\nconst SETUP_DOMAIN_CAPABILITY_SET: ReadonlySet<string> = new Set(SETUP_DOMAIN_CAPABILITIES);\n\nexport function isSetupDomainCapability(value: string): value is SetupDomainCapability {\n return SETUP_DOMAIN_CAPABILITY_SET.has(value);\n}\n\n// --- Ask family capability sets (fixed per execution kind — not derived from the IR) ---\n\nexport const ASK_ANSWER_CAPABILITIES: ReadonlySet<string> = new Set([\n \"sql_execution:read_only\",\n \"llm:per_step_tier\",\n \"llm:strong\",\n \"llm:cheap\",\n]);\n\nexport const ASK_DASHBOARD_CAPABILITIES: ReadonlySet<string> = new Set([\n \"sql_execution:read_only\",\n \"genbi_build\",\n \"render_contract\",\n \"artifact_write\",\n \"llm:per_step_tier\",\n \"llm:strong\",\n \"llm:cheap\",\n]);\n\n// --- Enrich family capability grouping ---\n\nexport const ENRICH_DOMAIN_CAPABILITIES = [\"semantic_introspection\", \"raw_material_read\"] as const;\nexport type EnrichDomainCapability = (typeof ENRICH_DOMAIN_CAPABILITIES)[number];\n\nconst ENRICH_DOMAIN_CAPABILITY_SET: ReadonlySet<string> = new Set(ENRICH_DOMAIN_CAPABILITIES);\n\nexport function isEnrichDomainCapability(value: string): value is EnrichDomainCapability {\n return ENRICH_DOMAIN_CAPABILITY_SET.has(value);\n}\n\n// Deliberately narrower than CAPABILITY_REALIZATION's full key set: some capabilities this\n// target can honestly realize for OTHER families (e.g. `context_build`, for Setup) are not\n// legal for Enrich's own components. The allowlist must name only what Enrich itself may\n// require, so a foreign-but-realizable capability still fails Enrich's by-name check (and does\n// so before any shape error can mask which capability was illegal) rather than silently passing\n// the name check and only failing later with a message that doesn't name it.\nexport const ENRICH_ALLOWED_CAPABILITIES: ReadonlySet<string> = new Set<string>([\n ...ENRICH_DOMAIN_CAPABILITIES,\n \"llm:cheap\",\n \"llm:strong\",\n]);\n\n// --- Guardrail enforcement ---\n\nexport interface GuardrailRequirement {\n locked: boolean;\n scope?: string;\n threshold?: number;\n}\n\n/** The target-level table: the canonical locked/scope/threshold values for each guardrail name. */\nexport const GUARDRAIL_ENFORCEMENT: Readonly<Record<string, GuardrailRequirement>> = {\n setup_execution: { locked: true, scope: \".\" },\n read_only_execution: { locked: true },\n deterministic_gate: { locked: true },\n row_limit: { locked: false, threshold: 1000 },\n statement_timeout: { locked: false, threshold: 30 },\n artifact_write: { locked: true, scope: \".\" },\n};\n\n/**\n * True iff `guard` is present, named `name`, and matches every value `GUARDRAIL_ENFORCEMENT`\n * defines for that name (locked-state always; scope/threshold only when the table defines\n * them for this guardrail — callers that need a stricter check, such as Enrich's requirement\n * that `read_only_execution` carry no scope at all, pass `requireScopeAbsent`).\n */\nexport function guardrailMatches(\n guard: Guardrail | undefined,\n name: string,\n options?: { requireScopeAbsent?: boolean },\n): boolean {\n const requirement = GUARDRAIL_ENFORCEMENT[name];\n if (!requirement || !guard || guard.name !== name || guard.locked !== requirement.locked) {\n return false;\n }\n if (requirement.scope !== undefined && guard.scope !== requirement.scope) {\n return false;\n }\n if (requirement.threshold !== undefined && guard.threshold !== requirement.threshold) {\n return false;\n }\n if (options?.requireScopeAbsent && guard.scope !== undefined) {\n return false;\n }\n return true;\n}\n","import { spawn, type ChildProcess } from \"node:child_process\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, relative, resolve } from \"node:path\";\nimport { createInterface, type Interface } from \"node:readline\";\n\nimport { buildIsolationArgs, sanitizeCodexEnvironment } from \"./config.js\";\nimport { CodexDispatchError } from \"./error.js\";\nimport type { PreparedSetupComponent } from \"./prepare.js\";\nimport type { PreparedEnrichComponent } from \"./enrich_prepare.js\";\nimport type { SessionIsolationOptions } from \"./session_types.js\";\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\ninterface PendingRequest {\n method: string;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isWithin(parent: string, candidate: string): boolean {\n const path = relative(parent, candidate);\n return path === \"\" || (!path.startsWith(\"..\") && !isAbsolute(path));\n}\n\nexport function validateSessionIsolation(options: SessionIsolationOptions): {\n codexHome: string;\n cwd: string;\n} {\n if (options.externalAuthentication !== \"provisioned\") {\n throw new CodexDispatchError(\n \"persistent session authentication must be provisioned externally\",\n );\n }\n if (!isAbsolute(options.codexHome) || !isAbsolute(options.cwd)) {\n throw new CodexDispatchError(\"session codexHome and cwd must be absolute\");\n }\n if (!existsSync(options.codexHome)) {\n throw new CodexDispatchError(\"dedicated session codexHome must be provisioned before start\");\n }\n if (existsSync(join(options.codexHome, \"config.toml\"))) {\n throw new CodexDispatchError(\"dedicated session codexHome must not contain config.toml\");\n }\n const codexHome = realpathSync(options.codexHome);\n const cwd = realpathSync(options.cwd);\n const inheritedCodexHome =\n options.env === undefined ? process.env[\"CODEX_HOME\"] : options.env[\"CODEX_HOME\"];\n const defaultHome = resolve(inheritedCodexHome ?? join(homedir(), \".codex\"));\n const comparableDefault = existsSync(defaultHome) ? realpathSync(defaultHome) : defaultHome;\n if (codexHome === comparableDefault) {\n throw new CodexDispatchError(\"persistent sessions require a dedicated non-default codexHome\");\n }\n if (isWithin(cwd, codexHome) || isWithin(codexHome, cwd)) {\n throw new CodexDispatchError(\n \"dedicated session codexHome and project cwd must not overlap\",\n );\n }\n return { codexHome, cwd };\n}\n\nexport function buildAppServerArgs(\n prepared: PreparedSetupComponent | PreparedEnrichComponent,\n options: SessionIsolationOptions,\n): string[] {\n return [\n ...(options.codexArgsPrefix ?? []),\n \"app-server\",\n \"--stdio\",\n \"--strict-config\",\n ...buildIsolationArgs(prepared),\n ];\n}\n\n/** Read-only app-server startup for model discovery. It deliberately has no thread/session config. */\nexport interface CatalogTransportOptions {\n cwd: string;\n codexHome?: string;\n codexBin?: string;\n codexArgsPrefix?: string[];\n timeoutMs?: number;\n terminationGraceMs?: number;\n env?: NodeJS.ProcessEnv;\n}\n\nfunction validateCatalogTransport(options: CatalogTransportOptions): {\n cwd: string;\n codexHome: string | undefined;\n} {\n if (!isAbsolute(options.cwd) || !existsSync(options.cwd)) {\n throw new CodexDispatchError(\"model catalog cwd must be an existing absolute path\");\n }\n if (options.codexHome !== undefined && (!isAbsolute(options.codexHome) || !existsSync(options.codexHome))) {\n throw new CodexDispatchError(\"model catalog codexHome must be an existing absolute path\");\n }\n return {\n cwd: realpathSync(options.cwd),\n codexHome: options.codexHome === undefined ? undefined : realpathSync(options.codexHome),\n };\n}\n\nexport class CodexAppServerTransport {\n private nextId = 1;\n private readonly pending = new Map<number, PendingRequest>();\n private readonly lines: Interface;\n private readonly child: ChildProcess;\n private closing = false;\n private closed = false;\n private killTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly closePromise: Promise<void>;\n\n private constructor(\n child: ChildProcess,\n private readonly timeoutMs: number,\n private readonly terminationGraceMs: number,\n private readonly onNotification: (method: string, params: unknown) => void,\n private readonly onDisconnect: (error?: CodexDispatchError) => void,\n ) {\n this.child = child;\n if (child.stdout === null || child.stdin === null || child.stderr === null) {\n throw new CodexDispatchError(\"app-server requires piped stdio\");\n }\n child.stderr.resume();\n this.lines = createInterface({ input: child.stdout });\n this.lines.on(\"line\", (line) => this.onLine(line));\n this.closePromise = new Promise((resolveClose) => {\n child.once(\"close\", (code, signal) => {\n this.closed = true;\n this.lines.close();\n const detail = signal !== null ? `signal ${signal}` : `exit ${code ?? \"unknown\"}`;\n this.rejectPending(`app-server transport disconnected (${detail})`);\n if (!this.closing) this.onDisconnect();\n resolveClose();\n });\n child.once(\"error\", () => {\n this.rejectPending(\"failed to start app-server\");\n });\n });\n }\n\n static async start(\n prepared: PreparedSetupComponent | PreparedEnrichComponent,\n options: SessionIsolationOptions,\n onNotification: (method: string, params: unknown) => void,\n onDisconnect: (error?: CodexDispatchError) => void,\n ): Promise<CodexAppServerTransport> {\n return CodexAppServerTransport.startWithArgs(\n buildAppServerArgs(prepared, options),\n options,\n onNotification,\n onDisconnect,\n );\n }\n\n static async startWithArgs(\n args: string[],\n options: SessionIsolationOptions,\n onNotification: (method: string, params: unknown) => void,\n onDisconnect: (error?: CodexDispatchError) => void,\n ): Promise<CodexAppServerTransport> {\n const isolated = validateSessionIsolation(options);\n const child = spawn(options.codexBin ?? \"codex\", args, {\n cwd: isolated.cwd,\n env: {\n ...sanitizeCodexEnvironment(options.env),\n CODEX_HOME: isolated.codexHome,\n },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n const transport = new CodexAppServerTransport(\n child,\n options.timeoutMs ?? 10_000,\n options.terminationGraceMs ?? 1_000,\n onNotification,\n onDisconnect,\n );\n try {\n const initialized = await transport.request(\"initialize\", {\n clientInfo: { name: \"warble_codex_local\", title: \"Warble Codex Local\", version: \"0.1.0\" },\n capabilities: { experimentalApi: true, requestAttestation: false },\n });\n if (!isRecord(initialized) || resolve(String(initialized[\"codexHome\"] ?? \"\")) !== isolated.codexHome) {\n throw new CodexDispatchError(\"app-server initialize returned an unexpected codexHome\");\n }\n transport.notify(\"initialized\");\n return transport;\n } catch (error) {\n await transport.close();\n throw error;\n }\n }\n\n /**\n * Start a narrowly read-only app-server transport for `model/list`. Unlike persistent sessions,\n * catalog discovery may use the caller's normal logged-in Codex identity, but it never starts a\n * thread or applies the session's MCP/tool isolation configuration.\n */\n static async startCatalog(options: CatalogTransportOptions): Promise<CodexAppServerTransport> {\n const catalog = validateCatalogTransport(options);\n const child = spawn(options.codexBin ?? \"codex\", [\n ...(options.codexArgsPrefix ?? []),\n \"app-server\",\n \"--stdio\",\n ], {\n cwd: catalog.cwd,\n env: {\n ...sanitizeCodexEnvironment(options.env),\n ...(catalog.codexHome === undefined ? {} : { CODEX_HOME: catalog.codexHome }),\n },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n const transport = new CodexAppServerTransport(\n child,\n options.timeoutMs ?? 10_000,\n options.terminationGraceMs ?? 1_000,\n () => undefined,\n () => undefined,\n );\n try {\n const initialized = await transport.request(\"initialize\", {\n clientInfo: { name: \"warble_codex_local_catalog\", title: \"Warble Codex Model Catalog\", version: \"0.1.0\" },\n capabilities: { experimentalApi: true, requestAttestation: false },\n });\n const returnedCodexHome = isRecord(initialized) ? initialized[\"codexHome\"] : undefined;\n if (\n typeof returnedCodexHome !== \"string\" ||\n !isAbsolute(returnedCodexHome) ||\n (catalog.codexHome !== undefined && resolve(returnedCodexHome) !== catalog.codexHome)\n ) {\n throw new CodexDispatchError(\"app-server initialize returned an invalid catalog response\");\n }\n transport.notify(\"initialized\");\n return transport;\n } catch (error) {\n await transport.close();\n throw error;\n }\n }\n\n request(method: string, params: unknown = {}): Promise<unknown> {\n if (this.closed || this.closing || this.child.stdin === null) {\n return Promise.reject(new CodexDispatchError(\"app-server transport is not available\"));\n }\n const id = this.nextId++;\n return new Promise((resolveRequest, rejectRequest) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n rejectRequest(new CodexDispatchError(`app-server request '${method}' timed out`));\n void this.close();\n }, this.timeoutMs);\n this.pending.set(id, { method, resolve: resolveRequest, reject: rejectRequest, timer });\n this.write({ jsonrpc: \"2.0\", id, method, params });\n });\n }\n\n notify(method: string, params?: unknown): void {\n this.write({ jsonrpc: \"2.0\", method, ...(params === undefined ? {} : { params }) });\n }\n\n async close(): Promise<void> {\n if (this.closing || this.closed) return this.closePromise;\n this.closing = true;\n this.signalTree(\"SIGTERM\");\n this.killTimer = setTimeout(() => {\n if (!this.closed) this.signalTree(\"SIGKILL\");\n }, this.terminationGraceMs);\n await this.closePromise;\n if (this.killTimer !== undefined) clearTimeout(this.killTimer);\n }\n\n private write(message: JsonRecord): void {\n if (this.child.stdin === null || this.child.stdin.destroyed) {\n throw new CodexDispatchError(\"app-server stdin is closed\");\n }\n this.child.stdin.write(`${JSON.stringify(message)}\\n`);\n }\n\n private onLine(line: string): void {\n let message: unknown;\n try {\n message = JSON.parse(line);\n } catch {\n this.protocolFailure(\"app-server emitted non-JSON output\");\n return;\n }\n if (!isRecord(message)) {\n this.protocolFailure(\"app-server emitted a non-object message\");\n return;\n }\n if (typeof message[\"id\"] === \"number\" && (\"result\" in message || \"error\" in message)) {\n const pending = this.pending.get(message[\"id\"]);\n if (!pending) {\n this.protocolFailure(\"app-server emitted a response for an unknown request\");\n return;\n }\n this.pending.delete(message[\"id\"]);\n clearTimeout(pending.timer);\n if (message[\"error\"] !== undefined) {\n // `model/list` needs one user-actionable classification, but must not expose raw RPC\n // messages (which can contain provider/account details) to the catalog caller.\n if (\n pending.method === \"model/list\" &&\n isRecord(message[\"error\"]) &&\n typeof message[\"error\"][\"message\"] === \"string\" &&\n /not authenticated|unauthenticated|authentication|login required|sign in/i.test(message[\"error\"][\"message\"])\n ) {\n pending.reject(new CodexDispatchError(\"app-server model catalog is not authenticated\"));\n } else {\n pending.reject(new CodexDispatchError(`app-server request '${pending.method}' failed`));\n }\n } else {\n pending.resolve(message[\"result\"]);\n }\n return;\n }\n if (typeof message[\"method\"] === \"string\" && message[\"id\"] === undefined) {\n try {\n this.onNotification(message[\"method\"], message[\"params\"]);\n } catch {\n this.protocolFailure(\"app-server notification violated the session contract\");\n }\n return;\n }\n if (typeof message[\"method\"] === \"string\" && message[\"id\"] !== undefined) {\n this.write({\n jsonrpc: \"2.0\",\n id: message[\"id\"],\n error: { code: -32601, message: \"client request not supported\" },\n });\n return;\n }\n this.protocolFailure(\"app-server emitted an invalid JSON-RPC message\");\n }\n\n private protocolFailure(message: string): void {\n this.rejectPending(message);\n this.onDisconnect(new CodexDispatchError(message));\n void this.close();\n }\n\n private rejectPending(message: string): void {\n for (const pending of this.pending.values()) {\n clearTimeout(pending.timer);\n pending.reject(new CodexDispatchError(message));\n }\n this.pending.clear();\n }\n\n private signalTree(signal: NodeJS.Signals): void {\n if (this.closed || this.child.pid === undefined) return;\n if (process.platform !== \"win32\") {\n try {\n process.kill(-this.child.pid, signal);\n return;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ESRCH\") return;\n }\n }\n this.child.kill(signal);\n }\n}\n","import type { PreparedSetupComponent } from \"./prepare.js\";\nimport type { PreparedEnrichComponent } from \"./enrich_prepare.js\";\n\ntype PreparedOneShotComponent = PreparedSetupComponent | PreparedEnrichComponent;\n\n/** Structurally matches both `PreparedSetupStep` and `PreparedEnrichStep` — the two engines stay\n * separate types, but a single prepared step is enough to build this target's args/prompt for\n * either one. */\nexport interface PreparedStepLike {\n name: string;\n model: string;\n prompt: string;\n consumes: string[];\n produces: string;\n}\n\nexport interface BuildPromptOptions {\n /** Setup's host consumes the produced slot as terminal text; Enrich may marshal structured JSON. */\n producedValue?: \"string\" | \"json\";\n}\n\nconst API_BILLING_ENV_KEYS = new Set([\n \"OPENAI_API_KEY\",\n \"CODEX_API_KEY\",\n \"AZURE_OPENAI_API_KEY\",\n \"OPENAI_ORGANIZATION\",\n \"OPENAI_ORG_ID\",\n \"OPENAI_PROJECT\",\n \"OPENAI_PROJECT_ID\",\n]);\n\nexport const DISABLED_FEATURES = [\n \"shell_tool\",\n \"unified_exec\",\n \"shell_zsh_fork\",\n \"unified_exec_zsh_fork\",\n \"standalone_web_search\",\n \"apps\",\n \"plugins\",\n \"in_app_browser\",\n \"browser_use\",\n \"computer_use\",\n \"image_generation\",\n \"skill_search\",\n \"multi_agent\",\n] as const;\n\nexport function tomlString(value: string): string {\n return JSON.stringify(value);\n}\n\nexport function tomlStringArray(values: readonly string[]): string {\n return `[${values.map(tomlString).join(\",\")}]`;\n}\n\nfunction sanitizeCodexToolName(value: string): string {\n return value.replace(/[^A-Za-z0-9_]/g, \"_\");\n}\n\nexport function codexMcpCallableNamespace(server: string): string {\n return `mcp__${sanitizeCodexToolName(server)}`;\n}\n\nexport function codexMcpCallableName(server: string, tool: string): string {\n return `${codexMcpCallableNamespace(server)}__${sanitizeCodexToolName(tool)}`;\n}\n\nexport function sanitizeCodexEnvironment(\n source: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n const clean: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(source)) {\n if (!API_BILLING_ENV_KEYS.has(key.toUpperCase()) && value !== undefined) clean[key] = value;\n }\n return clean;\n}\n\nexport interface InvocationArgsOptions {\n cwd: string;\n codexArgsPrefix?: string[];\n}\n\nexport function buildIsolationArgs(prepared: PreparedOneShotComponent): string[] {\n const serverKey = `mcp_servers.${prepared.mcp.name}`;\n const args = [\n \"-c\",\n \"shell_environment_policy.inherit=none\",\n \"-c\",\n \"project_doc_max_bytes=0\",\n \"-c\",\n \"project_root_markers=[]\",\n \"-c\",\n `web_search=${tomlString(\"disabled\")}`,\n \"-c\",\n \"features.code_mode.enabled=false\",\n \"-c\",\n `features.code_mode.direct_only_tool_namespaces=${tomlStringArray([codexMcpCallableNamespace(prepared.mcp.name)])}`,\n \"-c\",\n `${serverKey}.command=${tomlString(prepared.mcp.command)}`,\n \"-c\",\n `${serverKey}.args=${tomlStringArray(prepared.mcp.args ?? [])}`,\n \"-c\",\n `${serverKey}.enabled_tools=${tomlStringArray(prepared.enabledTools)}`,\n \"-c\",\n `${serverKey}.default_tools_approval_mode=${tomlString(\"approve\")}`,\n \"-c\",\n `${serverKey}.required=true`,\n ];\n for (const feature of DISABLED_FEATURES) args.push(\"--disable\", feature);\n return args;\n}\n\nexport function buildIsolationConfig(prepared: PreparedOneShotComponent): Record<string, unknown> {\n const serverKey = `mcp_servers.${prepared.mcp.name}`;\n return {\n \"shell_environment_policy.inherit\": \"none\",\n project_doc_max_bytes: 0,\n project_root_markers: [],\n web_search: \"disabled\",\n \"features.code_mode.enabled\": false,\n \"features.code_mode.direct_only_tool_namespaces\": [\n codexMcpCallableNamespace(prepared.mcp.name),\n ],\n [`${serverKey}.command`]: prepared.mcp.command,\n [`${serverKey}.args`]: prepared.mcp.args ?? [],\n [`${serverKey}.enabled_tools`]: prepared.enabledTools,\n [`${serverKey}.default_tools_approval_mode`]: \"approve\",\n [`${serverKey}.required`]: true,\n ...Object.fromEntries(DISABLED_FEATURES.map((feature) => [`features.${feature}`, false])),\n };\n}\n\nexport function buildCodexArgs(\n prepared: PreparedOneShotComponent,\n step: PreparedStepLike,\n options: InvocationArgsOptions,\n): string[] {\n const args = [\n ...(options.codexArgsPrefix ?? []),\n \"--ask-for-approval\",\n \"never\",\n \"exec\",\n \"--json\",\n \"--ephemeral\",\n \"--ignore-user-config\",\n \"--ignore-rules\",\n \"--strict-config\",\n \"--skip-git-repo-check\",\n \"--sandbox\",\n \"read-only\",\n \"--cd\",\n options.cwd,\n \"--model\",\n step.model,\n ...buildIsolationArgs(prepared),\n ];\n args.push(\"-\");\n return args;\n}\n\n/**\n * `inputs` carries the marshalled values this step's `consumes` names resolve to from earlier\n * steps' outputs in this same dispatch. When a step declares no `consumes` (every existing\n * single-step fixture, and the first step of any multi-step component), no input section is added.\n */\nexport function buildPrompt(\n prepared: PreparedOneShotComponent,\n step: PreparedStepLike,\n request: string,\n inputs: Record<string, unknown> = {},\n options: BuildPromptOptions = {},\n): string {\n const tools = prepared.enabledTools\n .map(\n (tool) =>\n `${prepared.mcp.name}.${tool} -> ${codexMcpCallableName(prepared.mcp.name, tool)}`,\n )\n .join(\", \");\n const terminalContract = [\n `The final answer must be one JSON object with exactly the produced field '${step.produces}'.`,\n ...(options.producedValue === \"string\"\n ? [`The value of '${step.produces}' must be a JSON string, not an object, array, number, boolean, or null.`]\n : []),\n \"Do not wrap the JSON in Markdown or include prose.\",\n ];\n const inputSection =\n step.consumes.length === 0\n ? []\n : [\n \"\",\n \"Inputs from earlier steps (JSON):\",\n JSON.stringify(Object.fromEntries(step.consumes.map((name) => [name, inputs[name]]))),\n ];\n return [\n `You are executing Warble target ${prepared.target}.`,\n `Run exactly one profile step: ${prepared.componentId}.${step.name}.`,\n `Only use the allowlisted MCP tools (raw identity -> Codex callable name): ${tools}.`,\n \"The raw and qualified names identify the same MCP tool; call the qualified Codex name, not a fallback.\",\n \"Do not use shell, file mutation, web, browser, apps, plugins, skills, or delegation.\",\n \"If the required MCP tool is unavailable or fails, fail loudly; do not substitute another mechanism.\",\n ...terminalContract,\n ...inputSection,\n \"\",\n \"Step contract:\",\n step.prompt,\n \"\",\n \"User request:\",\n request,\n ].join(\"\\n\");\n}\n","import { existsSync, mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n DISABLED_FEATURES,\n codexMcpCallableName,\n tomlString,\n tomlStringArray,\n} from \"./config.js\";\nimport type { PreparedAskComponent, PreparedAskStep } from \"./ask_prepare.js\";\nimport {\n REQUEST_TRANSPORT_SERVER,\n REQUEST_TRANSPORT_TOOL,\n STEP_TRANSPORT_TOOL,\n} from \"./request_transport.js\";\n\nconst ASK_DISABLED_FEATURES = DISABLED_FEATURES.filter(\n (feature) => feature !== \"multi_agent\",\n);\n\nexport interface AskAgentConfigFile {\n role: string;\n path: string;\n model: string;\n tools: string[];\n}\n\nexport interface AskAgentConfigBundle {\n directory: string;\n requestFile: string;\n stepRequestFile: string;\n agents: AskAgentConfigFile[];\n parentConfig: Record<string, unknown>;\n bindRequest: (request: string) => void;\n bindStepRequest: (request: string) => void;\n cleanup: () => void;\n}\n\nfunction renderConfigValue(value: unknown): string {\n if (typeof value === \"string\") return tomlString(value);\n if (typeof value === \"boolean\" || typeof value === \"number\") return String(value);\n if (Array.isArray(value) && value.every((entry) => typeof entry === \"string\")) {\n return tomlStringArray(value);\n }\n throw new Error(\"Ask app-server config contains an unsupported value\");\n}\n\n/**\n * Custom-agent roles must be registered when app-server starts. Supplying the\n * same keys only in thread/start is too late: the collaboration tool's agent\n * registry has already been constructed and spawnAgent rejects the role.\n */\nexport function buildAskAppServerArgs(bundle: AskAgentConfigBundle): string[] {\n const args = [\"app-server\", \"--stdio\", \"--strict-config\"];\n for (const [key, value] of Object.entries(bundle.parentConfig)) {\n args.push(\"-c\", `${key}=${renderConfigValue(value)}`);\n }\n return args;\n}\n\nfunction childInstructions(prepared: PreparedAskComponent, step: PreparedAskStep): string {\n const toolNames = step.enabledTools\n .map(\n (tool) =>\n `${prepared.mcp.name}.${tool} -> ${codexMcpCallableName(prepared.mcp.name, tool)}`,\n )\n .join(\", \");\n const requestTransportCallable = codexMcpCallableName(\n REQUEST_TRANSPORT_SERVER,\n REQUEST_TRANSPORT_TOOL,\n );\n const stepTransportCallable = codexMcpCallableName(\n REQUEST_TRANSPORT_SERVER,\n STEP_TRANSPORT_TOOL,\n );\n const dashboardContract =\n prepared.executionKind === \"generate_dashboard\"\n ? [\n `The exact allowed dashboard block contract is ${JSON.stringify(prepared.node.effect.render_blocks)}.`,\n \"Each contract entry's fields object is schema metadata, not an output wrapper: emit each declared field directly beside type at the block top level and never emit a fields key.\",\n \"A field whose type ends in ? is optional: omit it when unavailable and never emit null for it.\",\n \"Use every required field declared for a chosen block type, use no undeclared fields, and represent each row as a JSON object keyed by its column names.\",\n ]\n : [];\n const dashboardOutput =\n prepared.executionKind === \"generate_dashboard\" &&\n step.name === prepared.steps.at(-1)?.name\n ? [\n \"The value in the successful step envelope must be the dashboard render artifact: a JSON object with non-empty blocks, optional summary, and boolean verified.\",\n \"Blocks may use only the block types and fields declared in the exact allowed dashboard block contract above; include at least one data panel and one definition block.\",\n \"Set verified=true only when the required MCP queries completed successfully and the returned values were validated.\",\n ]\n : [];\n const requiredTool = step.requireSuccessfulTool\n ? [\n \"This step requires at least one successful call to an enabled MCP tool. The configured tool is available: attempt the call before reporting any tool availability failure.\",\n ]\n : [];\n const wrenToolArguments = step.enabledTools.includes(\"get_context\")\n ? [\n \"For wren.get_context, pass exactly one argument named question whose value is the authoritative original request text returned by the request transport call.\",\n ]\n : [];\n const queryCardinality = step.enabledTools.includes(\"run_sql\")\n ? [\n \"Before claiming verified=true, check join cardinality and fanout. Never compute independent table counts over a raw CROSS JOIN; use scalar subqueries or independently aggregated CTEs. For joined facts, use declared semantic relationships and distinct entity keys where needed so row multiplication cannot inflate aggregates.\",\n ]\n : [];\n return [\n `You are the named Warble step agent '${step.role}'.`,\n `Execute only IR step '${step.name}' and produce slot '${step.produces}'.`,\n `Before any reasoning or business MCP call, call ${REQUEST_TRANSPORT_SERVER}.${REQUEST_TRANSPORT_TOOL} through its exact qualified Codex callable ${requestTransportCallable} exactly once. Its returned text is the authoritative original user request for this turn.`,\n `Then call ${REQUEST_TRANSPORT_SERVER}.${STEP_TRANSPORT_TOOL} through its exact qualified Codex callable ${stepTransportCallable} exactly once. Its returned WARBLE_STEP_REQUEST envelope is the authoritative step and input slots; ignore any task-message copy of those inputs.`,\n `When MCP tools are exposed through code-mode exec, invoke exactly await tools.${requestTransportCallable}({}); do not guess, shorten, or rename the callable.`,\n \"Never ask the parent to copy, summarize, or reconstruct the original request, and never continue if the request transport call fails.\",\n `Use only these MCP tools when needed (raw identity -> exact qualified Codex callable): ${toolNames}.`,\n \"Under code-mode exec, invoke the qualified callable shown above through tools; do not guess an alias or use exec for any non-MCP operation.\",\n \"Do not use shell, file mutation, web, browser, apps, plugins, skills, or child agents.\",\n \"Return exactly one JSON object with keys warble_step, produces, ok, value, and error.\",\n `warble_step must equal '${step.name}' and produces must equal '${step.produces}'.`,\n \"On success set ok=true, put the produced slot value in value, and set error=null exactly; never use an empty error string.\",\n \"On failure set ok=false, keep the produced slot value with any diagnostics needed by a declared repair step, and use a non-empty stable non-secret error string.\",\n \"Do not wrap the JSON in markdown and do not add prose.\",\n ...requiredTool,\n ...wrenToolArguments,\n ...queryCardinality,\n ...dashboardContract,\n ...dashboardOutput,\n \"\",\n \"Step contract:\",\n step.prompt,\n ].join(\"\\n\");\n}\n\nexport function renderAskAgentToml(\n prepared: PreparedAskComponent,\n step: PreparedAskStep,\n requestFile: string,\n stepRequestFile: string,\n): string {\n const serverKey = `mcp_servers.${prepared.mcp.name}`;\n const requestServerKey = `mcp_servers.${REQUEST_TRANSPORT_SERVER}`;\n const builtRequestMcp = fileURLToPath(new URL(\"./request_mcp.js\", import.meta.url));\n const sourceRequestMcp = fileURLToPath(new URL(\"./request_mcp.ts\", import.meta.url));\n const sourceTsx = fileURLToPath(new URL(\"../node_modules/.bin/tsx\", import.meta.url));\n const requestMcp = existsSync(builtRequestMcp) ? builtRequestMcp : sourceRequestMcp;\n const requestMcpCommand = existsSync(builtRequestMcp) ? process.execPath : sourceTsx;\n if (!existsSync(requestMcp) || !existsSync(requestMcpCommand)) {\n throw new Error(\"Ask request transport executable is unavailable\");\n }\n const lines = [\n `name = ${tomlString(step.role)}`,\n `description = ${tomlString(`Executes Warble IR step ${step.name}`)}`,\n `developer_instructions = ${tomlString(childInstructions(prepared, step))}`,\n `model = ${tomlString(step.model)}`,\n `approval_policy = ${tomlString(\"never\")}`,\n `sandbox_mode = ${tomlString(\"read-only\")}`,\n \"\",\n \"[agents]\",\n \"enabled = false\",\n \"\",\n `[${serverKey}]`,\n `command = ${tomlString(prepared.mcp.command)}`,\n `args = ${tomlStringArray(prepared.mcp.args ?? [])}`,\n `enabled_tools = ${tomlStringArray(step.enabledTools)}`,\n `default_tools_approval_mode = ${tomlString(\"approve\")}`,\n \"required = true\",\n \"\",\n `[${requestServerKey}]`,\n `command = ${tomlString(requestMcpCommand)}`,\n `args = ${tomlStringArray([requestMcp, \"--request-file\", requestFile, \"--step-file\", stepRequestFile])}`,\n `enabled_tools = ${tomlStringArray([REQUEST_TRANSPORT_TOOL, STEP_TRANSPORT_TOOL])}`,\n `default_tools_approval_mode = ${tomlString(\"approve\")}`,\n \"required = true\",\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\nexport function createAskAgentConfigBundle(\n prepared: PreparedAskComponent,\n): AskAgentConfigBundle {\n const directory = mkdtempSync(join(tmpdir(), \"warble-codex-agents-\"));\n try {\n const requestFile = join(directory, \"original-request.txt\");\n const stepRequestFile = join(directory, \"step-request.txt\");\n writeFileSync(requestFile, \"\", { encoding: \"utf8\", mode: 0o600 });\n writeFileSync(stepRequestFile, \"\", { encoding: \"utf8\", mode: 0o600 });\n const agents = prepared.steps.map((step): AskAgentConfigFile => {\n const path = join(directory, `${step.role}.toml`);\n writeFileSync(path, renderAskAgentToml(prepared, step, requestFile, stepRequestFile), { encoding: \"utf8\", mode: 0o600 });\n return { role: step.role, path, model: step.model, tools: [...step.enabledTools] };\n });\n const parentConfig: Record<string, unknown> = {\n \"shell_environment_policy.inherit\": \"none\",\n project_doc_max_bytes: 0,\n project_root_markers: [],\n web_search: \"disabled\",\n // Current Codex collaboration tools are invoked through code-mode exec.\n // The parent has no business MCP servers and every non-collaboration\n // surface remains disabled below, so this only exposes the IR driver.\n \"features.code_mode.enabled\": true,\n \"features.multi_agent\": true,\n \"agents.enabled\": true,\n // Codex applies this as the total spawned-thread capacity for the session.\n // Warble enforces sequential spawn -> wait ordering in the event validator.\n \"agents.max_concurrent_threads_per_session\": prepared.steps.length,\n ...Object.fromEntries(\n ASK_DISABLED_FEATURES.map((feature) => [`features.${feature}`, false]),\n ),\n };\n for (const agent of agents) {\n parentConfig[`agents.${agent.role}.description`] =\n `Execute only the Warble step mapped to ${agent.role}`;\n parentConfig[`agents.${agent.role}.config_file`] = agent.path;\n }\n return {\n directory,\n requestFile,\n stepRequestFile,\n agents,\n parentConfig,\n bindRequest: (request) => writeFileSync(requestFile, request, { encoding: \"utf8\", mode: 0o600 }),\n bindStepRequest: (request) => writeFileSync(stepRequestFile, request, { encoding: \"utf8\", mode: 0o600 }),\n cleanup: () => rmSync(directory, { recursive: true, force: true }),\n };\n } catch (error) {\n rmSync(directory, { recursive: true, force: true });\n throw error;\n }\n}\n","import type { WarbleCodexEvent } from \"./events.js\";\n\nexport const SESSION_REFERENCE_VERSION = \"0.1\" as const;\n\nexport interface CodexSessionReference {\n version: typeof SESSION_REFERENCE_VERSION;\n target: \"codex:local\";\n threadId: string;\n forkedFromThreadId: string | null;\n}\n\nexport type SessionTurnStatus = \"in_progress\" | \"completed\" | \"interrupted\" | \"failed\";\n\nexport interface CodexTurnReference {\n threadId: string;\n turnId: string;\n status: SessionTurnStatus;\n}\n\nexport interface CodexArtifactReference {\n version: typeof SESSION_REFERENCE_VERSION;\n kind: \"mcp_tool_result\";\n threadId: string;\n turnId: string;\n itemId: string;\n server: string;\n tool: string;\n ok: boolean;\n}\n\nexport type CodexHistoryItem =\n | { type: \"user\" | \"assistant\"; itemId: string }\n | { type: \"artifact\"; reference: CodexArtifactReference };\n\nexport interface CodexHistoryTurn {\n id: string;\n status: SessionTurnStatus;\n items: CodexHistoryItem[];\n}\n\nexport interface CodexSessionHistory {\n session: CodexSessionReference;\n turns: CodexHistoryTurn[];\n}\n\nexport type CodexSessionEvent =\n | { t: \"session_started\" | \"session_resumed\" | \"session_forked\"; session: CodexSessionReference }\n | { t: \"session_recoverable\"; threadId: string | null; reason: \"transport_disconnect\" | \"app_server_crash\" | \"turn_timeout\" }\n | { t: \"session_failed\"; threadId: string | null; reason: \"protocol_violation\" }\n | { t: \"turn_started\"; turn: CodexTurnReference }\n | { t: \"turn_completed\"; turn: CodexTurnReference }\n | { t: \"artifact\"; reference: CodexArtifactReference }\n | ({ threadId: string; turnId: string } & WarbleCodexEvent);\n\nexport interface SessionIsolationOptions {\n codexHome: string;\n cwd: string;\n externalAuthentication: \"provisioned\";\n codexBin?: string;\n codexArgsPrefix?: string[];\n timeoutMs?: number;\n terminationGraceMs?: number;\n env?: NodeJS.ProcessEnv;\n onEvent?: (event: CodexSessionEvent) => void;\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport { CodexAppServerTransport } from \"./app_server_transport.js\";\nimport {\n buildAskAppServerArgs,\n createAskAgentConfigBundle,\n type AskAgentConfigBundle,\n} from \"./ask_config.js\";\nimport type { PreparedAskComponent, PreparedAskStep } from \"./ask_prepare.js\";\nimport {\n SESSION_REFERENCE_VERSION,\n type CodexSessionReference,\n type CodexTurnReference,\n type SessionIsolationOptions,\n} from \"./session_types.js\";\nimport { validateDashboardRenderEnvelope } from \"./render_contract.js\";\nimport {\n REQUEST_TRANSPORT_SERVER,\n REQUEST_TRANSPORT_TOOL,\n STEP_TRANSPORT_TOOL,\n} from \"./request_transport.js\";\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\nexport interface CodexAskStepResult {\n step: string;\n agentRole: string;\n agentThreadId: string;\n model: string;\n produced: string;\n ok: boolean;\n value: unknown;\n artifacts: CodexAskArtifactReference[];\n}\n\nexport interface CodexAskArtifactReference {\n version: typeof SESSION_REFERENCE_VERSION;\n kind: \"mcp_tool_result\";\n parentThreadId: string;\n parentTurnId: string;\n agentThreadId: string;\n step: string;\n agentRole: string;\n itemId: string;\n server: string;\n tool: string;\n ok: boolean;\n}\n\nexport interface CodexRenderArtifactReference {\n version: typeof SESSION_REFERENCE_VERSION;\n kind: \"render_envelope\";\n parentThreadId: string;\n parentTurnId: string;\n agentThreadId: string;\n step: string;\n agentRole: string;\n verified: boolean;\n blockTypes: string[];\n}\n\nexport type CodexAskEvent =\n | { t: \"session_started\" | \"session_resumed\"; session: CodexSessionReference }\n | { t: \"turn_started\" | \"turn_completed\"; turn: CodexTurnReference }\n | {\n t: \"agent_started\";\n parentThreadId: string;\n parentTurnId: string;\n step: string;\n agentRole: string;\n agentThreadId: string;\n model: string;\n }\n | {\n t: \"step_finished\";\n parentThreadId: string;\n parentTurnId: string;\n step: string;\n agentRole: string;\n agentThreadId: string;\n ok: boolean;\n }\n | { t: \"artifact\"; reference: CodexAskArtifactReference }\n | { t: \"render_artifact\"; reference: CodexRenderArtifactReference }\n | {\n t: \"render_degraded\";\n parentThreadId: string;\n parentTurnId: string;\n reason: \"invalid_render_envelope\";\n }\n | {\n t: \"session_recoverable\";\n threadId: string | null;\n reason: \"transport_disconnect\" | \"app_server_crash\" | \"turn_timeout\" | \"turn_cancelled\";\n }\n | { t: \"session_failed\"; threadId: string | null; reason: \"protocol_violation\" };\n\nexport interface CodexAskRuntimeOptions extends SessionIsolationOptions {\n turnTimeoutMs?: number;\n onAskEvent?: (event: CodexAskEvent) => void;\n}\n\nexport interface CodexAskRunResult {\n target: \"codex:local\";\n component: string;\n session: CodexSessionReference;\n turn: CodexTurnReference;\n finalText: string;\n value: unknown;\n steps: CodexAskStepResult[];\n artifact: CodexRenderArtifactReference | null;\n renderDegraded: boolean;\n}\n\ninterface SpawnRecord {\n callId: string;\n expected: PreparedAskStep;\n agentThreadId: string | null;\n model: string | null;\n prompt: string | null;\n stepRequest: string;\n waited: boolean;\n}\n\ninterface ActiveRun {\n threadId: string;\n turnId: string;\n started: boolean;\n completed: boolean;\n status: CodexTurnReference[\"status\"];\n spawns: SpawnRecord[];\n pendingItems: Map<string, string>;\n pendingChildThreadIds: Set<string>;\n pendingChildCompletedIds: Set<string>;\n deferredWaitItems: JsonRecord[];\n stepRequests: Array<string | undefined>;\n slots: Record<string, unknown>;\n childAnswers: Map<string, string>;\n finalText: string | null;\n deferredTurnCompletion: CodexTurnReference | null;\n stopReason: \"turn_timeout\" | \"turn_cancelled\" | null;\n stopCompleted: (() => void) | null;\n resolve: () => void;\n reject: (error: Error) => void;\n}\n\ninterface StepEnvelope {\n warble_step: string;\n produces: string;\n ok: boolean;\n value: unknown;\n error: string | null;\n}\n\ninterface AnswerQueryValue {\n columns: string[];\n rows: unknown[];\n summary: string;\n verified: true;\n definition: {\n sql: string;\n source_tables: string[];\n filters: unknown[];\n };\n}\n\nconst PASSIVE_PARENT_ITEMS = new Set([\n \"userMessage\",\n \"agentMessage\",\n \"reasoning\",\n \"plan\",\n \"subAgentActivity\",\n \"contextCompaction\",\n]);\n\nconst IGNORED_NOTIFICATIONS = new Set([\n \"thread/started\",\n \"thread/status/changed\",\n \"thread/tokenUsage/updated\",\n \"turn/plan/updated\",\n \"item/agentMessage/delta\",\n \"item/plan/delta\",\n \"item/reasoning/summaryTextDelta\",\n \"item/reasoning/summaryPartAdded\",\n \"item/reasoning/textDelta\",\n \"skills/changed\",\n \"mcpServer/startupStatus/updated\",\n \"account/updated\",\n \"account/rateLimits/updated\",\n \"remoteControl/status/changed\",\n \"model/rerouted\",\n \"configWarning\",\n \"warning\",\n]);\n\nconst CHILD_THREAD_NOTIFICATIONS = new Set([\n \"turn/started\",\n \"item/started\",\n \"item/completed\",\n \"turn/completed\",\n]);\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction record(value: unknown, context: string): JsonRecord {\n if (!isRecord(value)) throw new CodexDispatchError(`${context} requires an object`);\n return value;\n}\n\nfunction string(recordValue: JsonRecord, key: string, context: string): string {\n const value = recordValue[key];\n if (typeof value !== \"string\" || value.length === 0) {\n throw new CodexDispatchError(`${context} requires string ${key}`);\n }\n return value;\n}\n\nfunction sessionReference(thread: JsonRecord): CodexSessionReference {\n return {\n version: SESSION_REFERENCE_VERSION,\n target: \"codex:local\",\n threadId: string(thread, \"id\", \"thread\"),\n forkedFromThreadId:\n typeof thread[\"forkedFromId\"] === \"string\" ? thread[\"forkedFromId\"] : null,\n };\n}\n\nfunction turnStatus(value: unknown): CodexTurnReference[\"status\"] {\n switch (value) {\n case \"inProgress\":\n return \"in_progress\";\n case \"completed\":\n case \"interrupted\":\n case \"failed\":\n return value;\n default:\n throw new CodexDispatchError(\"turn requires a recognized status\");\n }\n}\n\nfunction turnReference(threadId: string, value: unknown): CodexTurnReference {\n const turn = record(value, \"turn\");\n return { threadId, turnId: string(turn, \"id\", \"turn\"), status: turnStatus(turn[\"status\"]) };\n}\n\nfunction validateReference(reference: CodexSessionReference): void {\n if (\n reference.version !== SESSION_REFERENCE_VERSION ||\n reference.target !== \"codex:local\" ||\n reference.threadId.length === 0\n ) {\n throw new CodexDispatchError(\"invalid codex session reference\");\n }\n}\n\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (isRecord(value)) {\n return `{${Object.keys(value)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value);\n}\n\nfunction parseEnvelope(text: string, step: PreparedAskStep): StepEnvelope {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n throw new CodexDispatchError(`agent '${step.role}' returned a non-JSON step envelope`);\n }\n const envelope = record(value, `agent '${step.role}' envelope`);\n const keys = Object.keys(envelope).sort();\n const expectedKeys = [\"error\", \"ok\", \"produces\", \"value\", \"warble_step\"];\n if (canonical(keys) !== canonical(expectedKeys)) {\n throw new CodexDispatchError(`agent '${step.role}' returned an unexpected envelope shape`);\n }\n if (\n envelope[\"warble_step\"] !== step.name ||\n envelope[\"produces\"] !== step.produces ||\n typeof envelope[\"ok\"] !== \"boolean\" ||\n (envelope[\"error\"] !== null && typeof envelope[\"error\"] !== \"string\")\n ) {\n throw new CodexDispatchError(`agent '${step.role}' returned a mismatched step envelope`);\n }\n if (envelope[\"ok\"] === true && envelope[\"error\"] !== null) {\n throw new CodexDispatchError(`agent '${step.role}' marked success with an error`);\n }\n if (\n envelope[\"ok\"] === false &&\n (typeof envelope[\"error\"] !== \"string\" || envelope[\"error\"].trim().length === 0)\n ) {\n throw new CodexDispatchError(`agent '${step.role}' marked failure without an error`);\n }\n return envelope as unknown as StepEnvelope;\n}\n\nfunction validateAnswerQueryValue(value: unknown): AnswerQueryValue {\n const answer = record(value, \"answer_query final value\");\n if (\n canonical(Object.keys(answer).sort()) !==\n canonical([\"columns\", \"definition\", \"rows\", \"summary\", \"verified\"])\n ) {\n throw new CodexDispatchError(\"answer_query success requires the canonical rich result shape\");\n }\n const definition = record(answer[\"definition\"], \"answer_query definition\");\n if (\n canonical(Object.keys(definition).sort()) !==\n canonical([\"filters\", \"source_tables\", \"sql\"])\n ) {\n throw new CodexDispatchError(\"answer_query success requires complete run provenance\");\n }\n if (\n !Array.isArray(answer[\"columns\"]) ||\n !answer[\"columns\"].every((column) => typeof column === \"string\" && column.length > 0) ||\n !Array.isArray(answer[\"rows\"]) ||\n typeof answer[\"summary\"] !== \"string\" ||\n answer[\"summary\"].trim().length === 0 ||\n answer[\"verified\"] !== true ||\n typeof definition[\"sql\"] !== \"string\" ||\n definition[\"sql\"].trim().length === 0 ||\n !Array.isArray(definition[\"source_tables\"]) ||\n !definition[\"source_tables\"].every(\n (table) => typeof table === \"string\" && table.length > 0,\n ) ||\n !Array.isArray(definition[\"filters\"])\n ) {\n throw new CodexDispatchError(\n \"answer_query success requires a grounded summary, verification, and complete run provenance\",\n );\n }\n return answer as unknown as AnswerQueryValue;\n}\n\nfunction parseStepRequest(text: string, step: PreparedAskStep): JsonRecord {\n const prefix = \"WARBLE_STEP_REQUEST\\n\";\n if (!text.startsWith(prefix)) {\n throw new CodexDispatchError(`agent '${step.role}' input lacks the Warble step envelope`);\n }\n let value: unknown;\n try {\n value = JSON.parse(text.slice(prefix.length));\n } catch {\n throw new CodexDispatchError(`agent '${step.role}' input has malformed JSON`);\n }\n const request = record(value, `agent '${step.role}' input`);\n const keys = Object.keys(request).sort();\n if (\n canonical(keys) !== canonical([\"inputs\", \"step\"]) ||\n request[\"step\"] !== step.name ||\n !isRecord(request[\"inputs\"])\n ) {\n throw new CodexDispatchError(`agent '${step.role}' input does not match its IR step`);\n }\n return request;\n}\n\nfunction buildStepRequest(step: PreparedAskStep, slots: Record<string, unknown>): string {\n return `WARBLE_STEP_REQUEST\\n${JSON.stringify({\n step: step.name,\n inputs: Object.fromEntries(step.consumes.map((slot) => [slot, slots[slot]])),\n })}`;\n}\n\n/**\n * Minimum/maximum spawn count implied purely by the prepared step chain: every unconditional\n * step is required (contributes to the floor), every step (unconditional or repair) contributes\n * to the ceiling. Shared by validateChildren and synthesizeDirectCollaboration so the two never\n * drift onto independent hardcoded bounds.\n */\nfunction stepCountBounds(steps: readonly PreparedAskStep[]): {\n minimumSteps: number;\n maximumSteps: number;\n} {\n return {\n minimumSteps: steps.filter((step) => !step.conditional).length,\n maximumSteps: steps.length,\n };\n}\n\n/**\n * Maps each step name to the step that repairs it, derived purely from IR-declared adjacency:\n * step[i] repairs step[i-1] when step[i].conditional and step[i].when.target === step[i-1].name.\n * A step with no entry in this map is \"required\" — validateStepChain guarantees no unconditional\n * step follows a repair, so this scan never needs to look past the immediate predecessor.\n */\nfunction repairersByTarget(steps: readonly PreparedAskStep[]): Map<string, PreparedAskStep> {\n const map = new Map<string, PreparedAskStep>();\n for (let index = 1; index < steps.length; index += 1) {\n const step = steps[index]!;\n const previous = steps[index - 1]!;\n if (step.conditional && step.when?.target === previous.name) {\n map.set(previous.name, step);\n }\n }\n return map;\n}\n\nexport function buildAskDriverPrompt(prepared: PreparedAskComponent): string {\n const steps = prepared.steps.map((step, index) => {\n const inputDescription =\n step.consumes.length === 0\n ? \"an empty inputs object\"\n : `inputs containing only ${step.consumes.join(\", \")} copied exactly from the prior agent value`;\n return `${index + 1}. Spawn agent_type=${step.role} for step=${step.name} with ${inputDescription}. Wait for it before any later spawn.`;\n });\n const repairers = repairersByTarget(prepared.steps);\n const repairRules = prepared.steps.flatMap((step) => {\n const repairer = repairers.get(step.name);\n if (repairer === undefined) return [];\n return [\n `If '${step.name}' returns ok=true, do not spawn '${repairer.role}'.`,\n `If it returns ok=false, spawn '${repairer.role}' exactly once; if repair fails, fail loudly.`,\n ];\n });\n const producesRenderEnvelope = prepared.executionKind === \"generate_dashboard\";\n const executionRules = producesRenderEnvelope\n ? [\n \"Every declared step is required. If any child returns ok=false, fail loudly and stop.\",\n \"Do not write files in the parent or children; the final validated render envelope is the consumer-persistable artifact output.\",\n ...repairRules,\n ]\n : repairRules;\n return [\n `Execute Warble component '${prepared.componentId}' by named child-agent delegation only.`,\n \"Do not perform any IR step in the parent and do not use business MCP tools in the parent.\",\n \"Use Codex's direct collaboration tools for every spawn and wait. Call spawn_agent and wait_agent as tool calls; do not invoke collaboration through exec or code mode.\",\n 'Select the exact custom agent type named for each step and send the exact child message below. Give the spawn a short unique task name when the current tool schema requires one.',\n \"Do not override the child model or reasoning effort, and do not fork the parent conversation into the child. After each spawn, wait for that child to complete before any later spawn.\",\n `The dispatcher supplies the authoritative original request directly to each child through ${REQUEST_TRANSPORT_SERVER}.${REQUEST_TRANSPORT_TOOL}; never copy, summarize, or include the request in a child message.`,\n \"For every child, send exactly this message:\",\n \"WARBLE_STEP_REQUEST\",\n '{\"step\":\"<step>\",\"inputs\":{\"<slot>\":<prior value>}}',\n \"The JSON object must contain only step and inputs. Never add the original request, a request summary, or any extra field.\",\n \"Each child returns a JSON envelope. Copy its value exactly into the next declared input slot.\",\n \"Spawn without an explicit model override: the named custom-agent config owns the model.\",\n \"\",\n ...steps,\n \"\",\n ...executionRules,\n \"Do not copy the final child value into the parent response; large structured values must remain authoritative in the child thread.\",\n 'Your final message must be exactly {\"warble_final_step\":\"<actual final successful step name>\",\"ok\":true} with no prose.',\n ].join(\"\\n\");\n}\n\nexport class CodexAskRuntime {\n private transport!: CodexAppServerTransport;\n private bundle!: AskAgentConfigBundle;\n private session: CodexSessionReference | null = null;\n private active: ActiveRun | null = null;\n private startingTurn = false;\n private pendingTurnNotifications: Array<readonly [method: string, params: unknown]> = [];\n private disconnected = false;\n\n private constructor(\n private readonly prepared: PreparedAskComponent,\n private readonly options: CodexAskRuntimeOptions,\n ) {}\n\n static async connect(\n prepared: PreparedAskComponent,\n options: CodexAskRuntimeOptions,\n ): Promise<CodexAskRuntime> {\n const runtime = new CodexAskRuntime(prepared, options);\n runtime.bundle = createAskAgentConfigBundle(prepared);\n try {\n runtime.transport = await CodexAppServerTransport.startWithArgs(\n [...(options.codexArgsPrefix ?? []), ...buildAskAppServerArgs(runtime.bundle)],\n options,\n (method, params) => runtime.onNotification(method, params),\n (error) => runtime.onDisconnect(error),\n );\n return runtime;\n } catch (error) {\n runtime.bundle.cleanup();\n throw error;\n }\n }\n\n async start(): Promise<CodexSessionReference> {\n this.ensureConnected();\n if (this.session !== null) throw new CodexDispatchError(\"an Ask session is already loaded\");\n const result = record(\n await this.transport.request(\"thread/start\", {\n model: this.prepared.models.orchestrator,\n cwd: this.options.cwd,\n approvalPolicy: \"never\",\n sandbox: \"read-only\",\n config: this.bundle.parentConfig,\n ephemeral: false,\n historyMode: \"legacy\",\n environments: [],\n runtimeWorkspaceRoots: [],\n selectedCapabilityRoots: [],\n dynamicTools: [],\n experimentalRawEvents: false,\n }),\n \"thread/start response\",\n );\n this.session = sessionReference(record(result[\"thread\"], \"thread/start thread\"));\n this.emit({ t: \"session_started\", session: this.session });\n return this.session;\n }\n\n async resume(reference: CodexSessionReference): Promise<CodexSessionReference> {\n validateReference(reference);\n this.ensureConnected();\n if (this.active !== null) throw new CodexDispatchError(\"cannot resume while an Ask turn is active\");\n const result = record(\n await this.transport.request(\"thread/resume\", {\n threadId: reference.threadId,\n model: this.prepared.models.orchestrator,\n cwd: this.options.cwd,\n approvalPolicy: \"never\",\n sandbox: \"read-only\",\n config: this.bundle.parentConfig,\n runtimeWorkspaceRoots: [],\n }),\n \"thread/resume response\",\n );\n const resumed = sessionReference(record(result[\"thread\"], \"thread/resume thread\"));\n if (resumed.threadId !== reference.threadId) {\n throw new CodexDispatchError(\"thread/resume returned a different thread id\");\n }\n this.session = resumed;\n this.emit({ t: \"session_resumed\", session: resumed });\n return resumed;\n }\n\n async run(\n reference: CodexSessionReference,\n request: string,\n signal?: AbortSignal,\n ): Promise<CodexAskRunResult> {\n validateReference(reference);\n this.ensureConnected();\n if (this.session?.threadId !== reference.threadId) {\n throw new CodexDispatchError(\"Ask session reference is not loaded; resume it first\");\n }\n if (this.active !== null) throw new CodexDispatchError(\"an Ask turn is already active\");\n if (request.trim().length === 0) throw new CodexDispatchError(\"Ask request must not be empty\");\n if (signal?.aborted) throw new CodexDispatchError(\"Ask turn was cancelled before start\");\n let resolveRun!: () => void;\n let rejectRun!: (error: Error) => void;\n const completion = new Promise<void>((resolve, reject) => {\n resolveRun = resolve;\n rejectRun = reject;\n });\n let turn: CodexTurnReference;\n this.startingTurn = true;\n this.pendingTurnNotifications = [];\n try {\n this.bundle.bindRequest(request);\n const initialStepRequest = buildStepRequest(this.prepared.steps[0]!, {});\n this.bundle.bindStepRequest(initialStepRequest);\n const result = record(\n await this.transport.request(\"turn/start\", {\n threadId: reference.threadId,\n input: [{ type: \"text\", text: buildAskDriverPrompt(this.prepared), text_elements: [] }],\n approvalPolicy: \"never\",\n environments: [],\n runtimeWorkspaceRoots: [],\n }),\n \"turn/start response\",\n );\n turn = turnReference(reference.threadId, result[\"turn\"]);\n if (turn.status !== \"in_progress\") {\n throw new CodexDispatchError(\"turn/start did not return an in-progress turn\");\n }\n this.active = {\n threadId: reference.threadId,\n turnId: turn.turnId,\n started: false,\n completed: false,\n status: \"in_progress\",\n spawns: [],\n pendingItems: new Map(),\n pendingChildThreadIds: new Set(),\n pendingChildCompletedIds: new Set(),\n deferredWaitItems: [],\n stepRequests: [initialStepRequest],\n slots: {},\n childAnswers: new Map(),\n finalText: null,\n deferredTurnCompletion: null,\n stopReason: null,\n stopCompleted: null,\n resolve: resolveRun,\n reject: rejectRun,\n };\n } catch (error) {\n this.startingTurn = false;\n this.pendingTurnNotifications = [];\n throw error;\n }\n this.startingTurn = false;\n const pendingNotifications = this.pendingTurnNotifications;\n this.pendingTurnNotifications = [];\n for (const [method, params] of pendingNotifications) {\n this.onNotification(method, params);\n }\n const timeoutMs = this.options.turnTimeoutMs ?? 120_000;\n const timer = setTimeout(() => {\n void this.stopTurn(turn, \"turn_timeout\");\n }, timeoutMs);\n const cancel = (): void => {\n void this.stopTurn(turn, \"turn_cancelled\");\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n if (signal?.aborted) cancel();\n try {\n await completion;\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", cancel);\n const active = this.active;\n if (active === null || active.turnId !== turn.turnId) {\n throw new CodexDispatchError(\"Ask turn state was displaced\");\n }\n const steps = await this.validateChildren(active);\n const finalStep = steps.at(-1);\n if (!finalStep?.ok) throw new CodexDispatchError(\"Ask run has no successful final step\");\n if (!isRecord(finalStep.value)) {\n throw new CodexDispatchError(\"Ask final value must be a JSON object\");\n }\n let parentFinal: unknown;\n try {\n parentFinal = JSON.parse(active.finalText ?? \"\");\n } catch {\n throw new CodexDispatchError(\"Ask parent final message is not JSON\");\n }\n const expectedReceipt = { warble_final_step: finalStep.step, ok: true };\n if (canonical(parentFinal) !== canonical(expectedReceipt)) {\n throw new CodexDispatchError(\"Ask parent final message does not match the final child receipt\");\n }\n let artifact: CodexRenderArtifactReference | null = null;\n let renderDegraded = false;\n let finalValue: unknown = finalStep.value;\n if (this.prepared.executionKind === \"answer_query\") {\n finalValue = validateAnswerQueryValue(finalStep.value);\n finalStep.value = finalValue;\n } else {\n try {\n const envelope = validateDashboardRenderEnvelope(finalStep.value, this.prepared.node);\n finalValue = envelope;\n finalStep.value = envelope;\n artifact = {\n version: SESSION_REFERENCE_VERSION,\n kind: \"render_envelope\",\n parentThreadId: active.threadId,\n parentTurnId: active.turnId,\n agentThreadId: finalStep.agentThreadId,\n step: finalStep.step,\n agentRole: finalStep.agentRole,\n verified: envelope.verified,\n blockTypes: envelope.blocks.map((block) => String(block[\"type\"])),\n };\n this.emit({ t: \"render_artifact\", reference: artifact });\n } catch (error) {\n if (!(error instanceof CodexDispatchError)) throw error;\n renderDegraded = true;\n this.emit({\n t: \"render_degraded\",\n parentThreadId: active.threadId,\n parentTurnId: active.turnId,\n reason: \"invalid_render_envelope\",\n });\n }\n }\n const completed: CodexTurnReference = {\n threadId: active.threadId,\n turnId: active.turnId,\n status: active.status,\n };\n this.emit({ t: \"turn_completed\", turn: completed });\n return {\n target: \"codex:local\",\n component: this.prepared.componentId,\n session: reference,\n turn: completed,\n finalText: JSON.stringify(finalValue),\n value: finalValue,\n steps,\n artifact,\n renderDegraded,\n };\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", cancel);\n this.startingTurn = false;\n this.pendingTurnNotifications = [];\n this.active = null;\n }\n }\n\n async restartAndResume(reference: CodexSessionReference): Promise<CodexSessionReference> {\n if (this.active !== null) throw new CodexDispatchError(\"cannot restart while an Ask turn is active\");\n await this.transport.close();\n this.transport = await CodexAppServerTransport.startWithArgs(\n [...(this.options.codexArgsPrefix ?? []), ...buildAskAppServerArgs(this.bundle)],\n this.options,\n (method, params) => this.onNotification(method, params),\n (error) => this.onDisconnect(error),\n );\n this.disconnected = false;\n try {\n return await this.resume(reference);\n } catch (error) {\n this.disconnected = true;\n await this.transport.close();\n throw error;\n }\n }\n\n async close(): Promise<void> {\n this.disconnected = true;\n this.active?.reject(new CodexDispatchError(\"Ask runtime closed during an active turn\"));\n this.active = null;\n await this.transport.close();\n this.bundle.cleanup();\n }\n\n private onNotification(method: string, paramsValue: unknown): void {\n try {\n if (IGNORED_NOTIFICATIONS.has(method)) return;\n const params = record(paramsValue, `${method} notification`);\n if (this.active === null && this.startingTurn) {\n this.pendingTurnNotifications.push([method, paramsValue]);\n return;\n }\n if (method === \"error\") {\n if (params[\"willRetry\"] === true) return;\n throw new CodexDispatchError(\"app-server reported a terminal Ask error\");\n }\n const active = this.active;\n if (active === null) throw new CodexDispatchError(`unexpected '${method}' without an active Ask turn`);\n const notificationThreadId = params[\"threadId\"];\n if (\n typeof notificationThreadId === \"string\" &&\n notificationThreadId !== active.threadId\n ) {\n const knownChild = active.spawns.some(\n (spawn) => spawn.agentThreadId === notificationThreadId,\n );\n if (knownChild && CHILD_THREAD_NOTIFICATIONS.has(method)) {\n this.observeChildNotification(method, params, active, notificationThreadId);\n return;\n }\n // Codex 0.146 can begin a child turn before completing the parent's\n // spawnAgent item. Buffer only the foreign thread identity until that\n // completion attributes exactly one receiver; no child content is\n // consumed here, and an unmatched identity still fails closed.\n if (\n CHILD_THREAD_NOTIFICATIONS.has(method) &&\n active.spawns.length < this.prepared.steps.length\n ) {\n active.pendingChildThreadIds.add(notificationThreadId);\n this.observeChildNotification(method, params, active, notificationThreadId);\n if (method === \"turn/completed\") {\n active.pendingChildCompletedIds.add(notificationThreadId);\n }\n if (active.pendingChildThreadIds.size > this.prepared.steps.length - active.spawns.length) {\n throw new CodexDispatchError(\"Ask received too many unattributed child threads\");\n }\n return;\n }\n throw new CodexDispatchError(\"Ask notification belongs to an unknown thread\");\n }\n if (method === \"turn/started\") {\n const turn = turnReference(string(params, \"threadId\", method), params[\"turn\"]);\n if (turn.threadId !== active.threadId || turn.turnId !== active.turnId || active.started) {\n throw new CodexDispatchError(\"Ask turn start notification does not match active state\");\n }\n active.started = true;\n this.emit({ t: \"turn_started\", turn });\n return;\n }\n if (method === \"item/started\" || method === \"item/completed\") {\n this.onItem(method, params, active);\n this.tryFinalizeTurn(active);\n return;\n }\n if (method === \"turn/completed\") {\n const turn = turnReference(string(params, \"threadId\", method), params[\"turn\"]);\n if (!active.started || turn.threadId !== active.threadId || turn.turnId !== active.turnId) {\n throw new CodexDispatchError(\"Ask turn completion does not match active state\");\n }\n if (active.stopReason !== null && turn.status === \"interrupted\") {\n active.completed = true;\n active.status = turn.status;\n active.stopCompleted?.();\n return;\n }\n if (turn.status !== \"completed\" || active.finalText === null) {\n throw new CodexDispatchError(\"Ask parent turn did not complete with a final answer\");\n }\n this.synthesizeDirectCollaboration(active);\n // Codex 0.146 may publish the parent turn completion before the\n // delayed spawnAgent/wait item completions that attribute children.\n // Retain the terminal turn and finalize as soon as those bounded,\n // ordered collaboration records arrive.\n active.deferredTurnCompletion = turn;\n this.tryFinalizeTurn(active);\n return;\n }\n throw new CodexDispatchError(`unsupported app-server notification '${method}'`);\n } catch (error) {\n const failure = error instanceof Error ? error : new Error(String(error));\n this.active?.reject(failure);\n this.onDisconnect(\n failure instanceof CodexDispatchError ? failure : new CodexDispatchError(failure.message),\n );\n void this.transport.close();\n }\n }\n\n private onItem(\n method: \"item/started\" | \"item/completed\",\n params: JsonRecord,\n active: ActiveRun,\n ): void {\n if (string(params, \"threadId\", method) !== active.threadId || string(params, \"turnId\", method) !== active.turnId) {\n throw new CodexDispatchError(\"Ask item belongs to a different parent turn\");\n }\n const item = record(params[\"item\"], `${method} item`);\n const type = string(item, \"type\", `${method} item`);\n if (type === \"collabAgentToolCall\") {\n this.onCollabItem(method, item, active);\n return;\n }\n if (!PASSIVE_PARENT_ITEMS.has(type)) {\n throw new CodexDispatchError(`isolation violation: Ask parent emitted forbidden '${type}'`);\n }\n if (method === \"item/completed\" && type === \"agentMessage\") {\n active.finalText = string(item, \"text\", type);\n }\n }\n\n private observeChildNotification(\n method: string,\n params: JsonRecord,\n active: ActiveRun,\n childThreadId: string,\n ): void {\n if (method !== \"item/completed\") return;\n const item = record(params[\"item\"], \"child item/completed item\");\n if (item[\"type\"] !== \"agentMessage\") return;\n if (active.childAnswers.has(childThreadId)) {\n throw new CodexDispatchError(\"Ask child emitted more than one final answer\");\n }\n const answer = string(item, \"text\", \"child agentMessage\");\n active.childAnswers.set(childThreadId, answer);\n const knownIndex = active.spawns.findIndex((spawn) => spawn.agentThreadId === childThreadId);\n const pendingIndex = [...active.pendingChildThreadIds].indexOf(childThreadId);\n const stepIndex = knownIndex >= 0 ? knownIndex : active.spawns.length + pendingIndex;\n const step = this.prepared.steps[stepIndex];\n if (!step) throw new CodexDispatchError(\"Ask child answer has no IR step attribution\");\n const envelope = parseEnvelope(answer, step);\n active.slots[step.produces] = envelope.value;\n const next = this.prepared.steps[stepIndex + 1];\n const repairers = repairersByTarget(this.prepared.steps);\n const isRecoverable = repairers.has(step.name);\n const shouldPrepareNext = next !== undefined && (isRecoverable ? !envelope.ok : envelope.ok);\n if (!shouldPrepareNext || next === undefined) return;\n const request = buildStepRequest(next, active.slots);\n active.stepRequests[stepIndex + 1] = request;\n this.bundle.bindStepRequest(request);\n }\n\n private onCollabItem(\n method: \"item/started\" | \"item/completed\",\n item: JsonRecord,\n active: ActiveRun,\n ): void {\n const id = string(item, \"id\", \"collaboration item\");\n const tool = string(item, \"tool\", \"collaboration item\");\n if (tool !== \"spawnAgent\" && tool !== \"wait\") {\n throw new CodexDispatchError(`Ask parent used unsupported collaboration tool '${tool}'`);\n }\n if (method === \"item/started\") {\n if (item[\"status\"] !== \"inProgress\" || active.pendingItems.has(id)) {\n throw new CodexDispatchError(\"collaboration item has an invalid start state\");\n }\n active.pendingItems.set(id, tool);\n return;\n }\n if (active.pendingItems.get(id) !== tool) {\n throw new CodexDispatchError(\"collaboration item completed without a matching start\");\n }\n active.pendingItems.delete(id);\n if (item[\"status\"] !== \"completed\") {\n throw new CodexDispatchError(`collaboration '${tool}' failed`);\n }\n if (tool === \"spawnAgent\") {\n const previous = active.spawns.at(-1);\n if (previous && !previous.waited) {\n throw new CodexDispatchError(\"Ask parent spawned the next agent before waiting for the prior one\");\n }\n const expected = this.prepared.steps[active.spawns.length];\n if (!expected) throw new CodexDispatchError(\"Ask parent spawned too many agents\");\n const receiverIds = item[\"receiverThreadIds\"];\n if (!Array.isArray(receiverIds) || receiverIds.length !== 1 || typeof receiverIds[0] !== \"string\") {\n throw new CodexDispatchError(\"spawnAgent must return exactly one child thread\");\n }\n const firstPendingChild = active.pendingChildThreadIds.values().next().value as string | undefined;\n if (firstPendingChild !== undefined && firstPendingChild !== receiverIds[0]) {\n throw new CodexDispatchError(\"spawnAgent attributed a different child thread than its notifications\");\n }\n if (firstPendingChild !== undefined) active.pendingChildThreadIds.delete(firstPendingChild);\n active.pendingChildCompletedIds.delete(receiverIds[0]);\n // Codex 0.146 reports `model: null` when the selected custom-agent\n // config owns the model. Older versions echoed the resolved model here.\n // A non-null value is an explicit override and must still match exactly;\n // the host-owned custom-agent layer is authoritative otherwise.\n const requestedModel = item[\"model\"];\n if (requestedModel !== null && requestedModel !== expected.model) {\n throw new CodexDispatchError(`agent '${expected.role}' ran on the wrong model`);\n }\n const stepRequest = active.stepRequests[active.spawns.length];\n if (stepRequest === undefined) {\n throw new CodexDispatchError(`agent '${expected.role}' spawned before its host input was ready`);\n }\n const spawn: SpawnRecord = {\n callId: id,\n expected,\n agentThreadId: receiverIds[0],\n model: expected.model,\n prompt: item[\"prompt\"] === null ? null : string(item, \"prompt\", \"spawnAgent\"),\n stepRequest,\n waited: false,\n };\n active.spawns.push(spawn);\n const deferred = active.deferredWaitItems.shift();\n if (deferred !== undefined) this.completeWait(deferred, active);\n return;\n }\n const current = active.spawns.at(-1);\n if (!current?.agentThreadId) {\n // Codex 0.146 may complete the direct wait_agent tool before the parent\n // spawnAgent item is delivered. Defer its attribution until that spawn\n // supplies the exact receiver thread id.\n if (active.deferredWaitItems.length >= this.prepared.steps.length - active.spawns.length) {\n throw new CodexDispatchError(\"too many waits completed before child attribution\");\n }\n active.deferredWaitItems.push(item);\n return;\n }\n this.completeWait(item, active);\n }\n\n private completeWait(item: JsonRecord, active: ActiveRun): void {\n const current = active.spawns.at(-1);\n if (!current?.agentThreadId || current.waited) {\n throw new CodexDispatchError(\"wait did not follow exactly one active child spawn\");\n }\n const receiverIds = item[\"receiverThreadIds\"];\n if (!Array.isArray(receiverIds) || receiverIds.length !== 1 || receiverIds[0] !== current.agentThreadId) {\n throw new CodexDispatchError(\"wait targeted a different child thread\");\n }\n const states = record(item[\"agentsStates\"], \"wait agentsStates\");\n const childState = record(states[current.agentThreadId], \"wait child state\");\n if (childState[\"status\"] !== \"completed\") {\n throw new CodexDispatchError(\"wait completed before the child agent succeeded\");\n }\n current.waited = true;\n }\n\n private tryFinalizeTurn(active: ActiveRun): void {\n const turn = active.deferredTurnCompletion;\n if (\n turn === null ||\n active.pendingItems.size > 0 ||\n active.pendingChildThreadIds.size > 0 ||\n active.deferredWaitItems.length > 0\n ) {\n return;\n }\n active.deferredTurnCompletion = null;\n active.completed = true;\n active.status = turn.status;\n active.resolve();\n }\n\n private synthesizeDirectCollaboration(active: ActiveRun): void {\n if (active.spawns.length > 0 || active.pendingChildThreadIds.size === 0) return;\n const childIds = [...active.pendingChildThreadIds];\n const { minimumSteps, maximumSteps } = stepCountBounds(this.prepared.steps);\n if (\n childIds.length < minimumSteps ||\n childIds.length > maximumSteps ||\n childIds.some((id) => !active.pendingChildCompletedIds.has(id))\n ) {\n throw new CodexDispatchError(\"direct collaboration children did not complete in the required sequence\");\n }\n if (active.deferredWaitItems.length !== childIds.length) {\n throw new CodexDispatchError(\"direct collaboration did not wait once for every child\");\n }\n active.spawns = childIds.map((agentThreadId, index) => {\n const stepRequest = active.stepRequests[index];\n if (stepRequest === undefined) {\n throw new CodexDispatchError(\"direct collaboration child spawned before its host input was ready\");\n }\n return {\n callId: `direct-${agentThreadId}`,\n expected: this.prepared.steps[index]!,\n agentThreadId,\n model: this.prepared.steps[index]!.model,\n prompt: null,\n stepRequest,\n waited: true,\n };\n });\n active.pendingChildThreadIds.clear();\n active.pendingChildCompletedIds.clear();\n active.deferredWaitItems = [];\n }\n\n private async validateChildren(active: ActiveRun): Promise<CodexAskStepResult[]> {\n const { minimumSteps, maximumSteps } = stepCountBounds(this.prepared.steps);\n if (\n active.spawns.length < minimumSteps ||\n active.spawns.length > maximumSteps ||\n active.spawns.some((spawn) => !spawn.waited)\n ) {\n throw new CodexDispatchError(\"Ask parent did not complete the required named-agent sequence\");\n }\n const results: CodexAskStepResult[] = [];\n const slots: Record<string, unknown> = {};\n const repairers = repairersByTarget(this.prepared.steps);\n for (const [index, spawn] of active.spawns.entries()) {\n const step = this.prepared.steps[index]!;\n if (spawn.expected !== step || spawn.agentThreadId === null || spawn.model !== step.model) {\n throw new CodexDispatchError(\"Ask child sequence does not match the IR\");\n }\n const child = record(\n await this.transport.request(\"thread/read\", {\n threadId: spawn.agentThreadId,\n includeTurns: true,\n }),\n \"child thread/read response\",\n );\n const thread = record(child[\"thread\"], \"child thread/read thread\");\n if (\n thread[\"id\"] !== spawn.agentThreadId ||\n thread[\"parentThreadId\"] !== active.threadId ||\n thread[\"agentRole\"] !== step.role\n ) {\n throw new CodexDispatchError(`child thread attribution failed for agent '${step.role}'`);\n }\n // Child artifacts are read and validated only after the parent turn completes.\n // Emit the public lifecycle after attribution succeeds and as one IR-ordered\n // unit instead of leaking the parent notification order (where a later spawn\n // can be observed before the prior child's deferred artifacts and finish).\n this.emit({\n t: \"agent_started\",\n parentThreadId: active.threadId,\n parentTurnId: active.turnId,\n step: step.name,\n agentRole: step.role,\n agentThreadId: spawn.agentThreadId,\n model: step.model,\n });\n const turns = thread[\"turns\"];\n if (!Array.isArray(turns) || turns.length !== 1) {\n throw new CodexDispatchError(`agent '${step.role}' must have exactly one turn`);\n }\n const turn = record(turns[0], `agent '${step.role}' turn`);\n if (turn[\"status\"] !== \"completed\" || !Array.isArray(turn[\"items\"])) {\n throw new CodexDispatchError(`agent '${step.role}' turn did not complete`);\n }\n let inputText: string | null = null;\n let answerText: string | null = null;\n const artifacts: CodexAskArtifactReference[] = [];\n let originalRequestCalls = 0;\n let stepRequestCalls = 0;\n let businessToolSeen = false;\n for (const itemValue of turn[\"items\"]) {\n const item = record(itemValue, `agent '${step.role}' item`);\n const type = string(item, \"type\", `agent '${step.role}' item`);\n if (type === \"userMessage\") {\n const content = item[\"content\"];\n if (!Array.isArray(content) || !isRecord(content[0]) || typeof content[0][\"text\"] !== \"string\") {\n throw new CodexDispatchError(`agent '${step.role}' user input is malformed`);\n }\n inputText = content[0][\"text\"];\n } else if (type === \"agentMessage\") {\n answerText = string(item, \"text\", `agent '${step.role}' answer`);\n } else if (type === \"mcpToolCall\") {\n const server = string(item, \"server\", \"child MCP item\");\n const tool = string(item, \"tool\", \"child MCP item\");\n const status = string(item, \"status\", \"child MCP item\");\n if (status !== \"completed\" && status !== \"failed\") {\n throw new CodexDispatchError(`agent '${step.role}' has an unfinished MCP tool`);\n }\n if (server === REQUEST_TRANSPORT_SERVER) {\n const successful =\n !businessToolSeen &&\n status === \"completed\" &&\n (item[\"error\"] === null || item[\"error\"] === undefined);\n if (tool === REQUEST_TRANSPORT_TOOL) {\n if (!successful || originalRequestCalls !== 0 || stepRequestCalls !== 0) {\n throw new CodexDispatchError(`agent '${step.role}' violated the original request transport contract`);\n }\n originalRequestCalls += 1;\n } else if (tool === STEP_TRANSPORT_TOOL) {\n if (!successful || originalRequestCalls !== 1 || stepRequestCalls !== 0) {\n throw new CodexDispatchError(`agent '${step.role}' violated the step request transport contract`);\n }\n stepRequestCalls += 1;\n } else {\n throw new CodexDispatchError(`agent '${step.role}' used an unknown request transport tool`);\n }\n continue;\n }\n if (server !== this.prepared.mcp.name || !step.enabledTools.includes(tool)) {\n throw new CodexDispatchError(`agent '${step.role}' used a non-allowlisted MCP tool`);\n }\n businessToolSeen = true;\n const reference: CodexAskArtifactReference = {\n version: SESSION_REFERENCE_VERSION,\n kind: \"mcp_tool_result\",\n parentThreadId: active.threadId,\n parentTurnId: active.turnId,\n agentThreadId: spawn.agentThreadId,\n step: step.name,\n agentRole: step.role,\n itemId: string(item, \"id\", \"child MCP item\"),\n server,\n tool,\n ok: status === \"completed\" && (item[\"error\"] === null || item[\"error\"] === undefined),\n };\n artifacts.push(reference);\n this.emit({ t: \"artifact\", reference });\n } else if (!new Set([\"reasoning\", \"plan\"]).has(type)) {\n throw new CodexDispatchError(`agent '${step.role}' emitted forbidden '${type}'`);\n }\n }\n if (answerText === null) {\n throw new CodexDispatchError(`agent '${step.role}' lacks a final answer`);\n }\n if (originalRequestCalls !== 1) {\n throw new CodexDispatchError(`agent '${step.role}' did not load the authoritative original request`);\n }\n if (stepRequestCalls !== 1) {\n throw new CodexDispatchError(`agent '${step.role}' did not load the authoritative step request`);\n }\n // Codex 0.146 direct collaboration persists the encrypted NEW_TASK\n // delivery outside the child turn, so thread/read no longer exposes a\n // child userMessage and the parent spawn item redacts its prompt. The\n // dedicated step transport is host-authored and its successful call is\n // the authoritative copy. Any visible compatibility copy must agree.\n const requestTexts = [spawn.stepRequest, inputText, spawn.prompt].filter(\n (value): value is string => value !== null,\n );\n const requests = requestTexts.map((text) => parseStepRequest(text, step));\n if (requests.some((request) => canonical(request) !== canonical(requests[0]))) {\n throw new CodexDispatchError(`agent '${step.role}' has conflicting step inputs`);\n }\n const request = requests[0]!;\n const inputs = request[\"inputs\"] as JsonRecord;\n if (Object.keys(inputs).sort().join(\",\") !== [...step.consumes].sort().join(\",\")) {\n throw new CodexDispatchError(`agent '${step.role}' received the wrong input slots`);\n }\n for (const consumed of step.consumes) {\n if (canonical(inputs[consumed]) !== canonical(slots[consumed])) {\n throw new CodexDispatchError(`agent '${step.role}' input '${consumed}' was not marshalled exactly`);\n }\n }\n const envelope = parseEnvelope(answerText, step);\n // Family-agnostic per-step business rule: a step with no designated\n // repairer is required and must succeed; a step with a designated repairer must trigger\n // that repairer exactly when it fails, and must not spawn it when it succeeds. Derived\n // purely from IR adjacency (repairersByTarget), not from executionKind.\n const repairer = repairers.get(step.name);\n if (repairer === undefined) {\n if (!envelope.ok) {\n throw new CodexDispatchError(\n step.conditional\n ? \"bounded repair attempt did not recover generation\"\n : `required step '${step.name}' failed`,\n );\n }\n } else {\n const repairerSpawned = active.spawns.length > index + 1;\n if (!envelope.ok && !repairerSpawned) {\n throw new CodexDispatchError(\n `step '${step.name}' failure did not trigger repair step '${repairer.name}'`,\n );\n }\n if (envelope.ok && repairerSpawned) {\n throw new CodexDispatchError(\n `repair step '${repairer.name}' ran even though '${step.name}' succeeded`,\n );\n }\n }\n if (step.requireSuccessfulTool && artifacts.length === 0) {\n throw new CodexDispatchError(`agent '${step.role}' completed without its required MCP tool attempt`);\n }\n if (envelope.ok && step.requireSuccessfulTool && !artifacts.some((artifact) => artifact.ok)) {\n throw new CodexDispatchError(`agent '${step.role}' claimed success without a successful MCP tool`);\n }\n slots[step.produces] = envelope.value;\n const result: CodexAskStepResult = {\n step: step.name,\n agentRole: step.role,\n agentThreadId: spawn.agentThreadId,\n model: step.model,\n produced: step.produces,\n ok: envelope.ok,\n value: envelope.value,\n artifacts,\n };\n results.push(result);\n this.emit({\n t: \"step_finished\",\n parentThreadId: active.threadId,\n parentTurnId: active.turnId,\n step: step.name,\n agentRole: step.role,\n agentThreadId: spawn.agentThreadId,\n ok: envelope.ok,\n });\n }\n return results;\n }\n\n private async stopTurn(\n turn: CodexTurnReference,\n reason: \"turn_timeout\" | \"turn_cancelled\",\n ): Promise<void> {\n if (this.active?.turnId !== turn.turnId || this.active.stopReason !== null) return;\n this.active.stopReason = reason;\n const transport = this.transport;\n let resolveStopped!: () => void;\n const stopped = new Promise<void>((resolve) => {\n resolveStopped = resolve;\n });\n this.active.stopCompleted = resolveStopped;\n try {\n await transport.request(\"turn/interrupt\", {\n threadId: turn.threadId,\n turnId: turn.turnId,\n });\n } catch {\n // Closing the process tree below is the hard stop.\n }\n let graceTimer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n stopped,\n new Promise<void>((resolve) => {\n graceTimer = setTimeout(resolve, this.options.terminationGraceMs ?? 1_000);\n }),\n ]);\n if (graceTimer !== undefined) clearTimeout(graceTimer);\n await transport.close();\n if (this.active?.turnId !== turn.turnId) return;\n const error = new CodexDispatchError(\n reason === \"turn_timeout\"\n ? `Ask turn '${turn.turnId}' timed out`\n : `Ask turn '${turn.turnId}' was cancelled`,\n );\n this.active.reject(error);\n this.onDisconnect(undefined, reason);\n }\n\n private onDisconnect(\n protocolError?: CodexDispatchError,\n reasonOverride?: \"turn_timeout\" | \"turn_cancelled\",\n ): void {\n if (this.disconnected) return;\n this.disconnected = true;\n if (protocolError) {\n this.emit({ t: \"session_failed\", threadId: this.session?.threadId ?? null, reason: \"protocol_violation\" });\n this.active?.reject(protocolError);\n } else {\n this.emit({\n t: \"session_recoverable\",\n threadId: this.session?.threadId ?? null,\n reason: reasonOverride ?? (this.active ? \"app_server_crash\" : \"transport_disconnect\"),\n });\n this.active?.reject(new CodexDispatchError(\"app-server disconnected during an Ask turn\"));\n }\n }\n\n private ensureConnected(): void {\n if (this.disconnected) throw new CodexDispatchError(\"app-server transport disconnected; resume required\");\n }\n\n private emit(event: CodexAskEvent): void {\n this.options.onAskEvent?.(event);\n }\n}\n","import { isAbsolute } from \"node:path\";\n\nimport { CodexDispatchError } from \"./error.js\";\nimport { assertDispatchableComponentIdentity } from \"./dispatch_registry.js\";\nimport {\n parseIr,\n SUPPORTED_IR_VERSION,\n TARGET,\n type ComponentNode,\n type WarbleIr,\n} from \"./ir.js\";\nimport type { CapabilityResolution } from \"./prepare.js\";\nimport { resolveStepModel, validateStepTopology, type OnFailureGuard } from \"./step_engine.js\";\nimport {\n ENRICH_ALLOWED_CAPABILITIES,\n guardrailMatches,\n hasExactCapabilities,\n isEnrichDomainCapability,\n resolveCapabilities,\n type EnrichDomainCapability,\n} from \"./target_profile.js\";\n\nexport type { EnrichDomainCapability };\n\nexport interface EnrichMcpServerConfig {\n name: string;\n command: string;\n args?: string[];\n toolsByCapability: Record<EnrichDomainCapability, string[]>;\n}\n\nexport interface PreparedEnrichStep {\n name: string;\n tier: string;\n model: string;\n prompt: string;\n consumes: string[];\n produces: string;\n when: OnFailureGuard | null;\n}\n\nexport interface PreparedEnrichComponent {\n target: typeof TARGET;\n profile: string;\n node: ComponentNode;\n componentId: string;\n domainCapabilities: EnrichDomainCapability[];\n steps: PreparedEnrichStep[];\n capabilities: CapabilityResolution[];\n enabledTools: string[];\n mcp: EnrichMcpServerConfig;\n}\n\nexport interface PrepareEnrichInput {\n ir: string | WarbleIr;\n component: string;\n /**\n * A single string binds every step in the component to that one model. A per-tier map is\n * required once a component declares steps at more than one tier — see `resolveStepModel`.\n */\n model: string | Record<string, string>;\n mcp: EnrichMcpServerConfig;\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction validateEnrichShape(node: ComponentNode): EnrichDomainCapability[] {\n assertDispatchableComponentIdentity(node);\n // Checked first, and by capability name rather than by shape: a component whose\n // required_capabilities include anything outside this target's honestly-guaranteed set for\n // Enrich (e.g. a gated-tool component's context_write_authz/context_validate/context_build/\n // version_control/human_approval) can never be legalized here, no matter what its other IR shape\n // looks like. This keeps the wall-hit deterministic and named, and it must never be relaxed to\n // make a gated-tool component dispatchable. It also keeps Enrich's tier allowlist ({cheap,\n // strong}, no `llm:per_step_tier` widening) intact regardless of step count.\n for (const capability of node.required_capabilities) {\n if (!ENRICH_ALLOWED_CAPABILITIES.has(capability)) {\n throw new CodexDispatchError(\n `component '${node.id}' cannot be dispatched by codex:local: ` +\n `required capability '${capability}' has no honest realization on this target`,\n );\n }\n }\n if (\n node.type !== \"analytical\" ||\n node.realization_kind !== \"skill\" ||\n node.trigger.kind !== \"one_shot\" ||\n node.effect.outcome.kind !== \"none\"\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: requires analytical/skill/one_shot/none`,\n );\n }\n if (node.context_binding.binding_mode !== \"pinned\") {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: requires a pinned context binding`,\n );\n }\n if (node.llm_calls.length === 0) {\n throw new CodexDispatchError(`component '${node.id}' wall-hit: at least one llm_call is required`);\n }\n // Validates the full step sequence: unique names, produces-slot discipline, consumes→produces\n // marshalling closure, and on_failure guard placement. This is where the three phase-A\n // wall-hits now live, generalized to n steps rather than hardcoded to one.\n validateStepTopology(node);\n if (\n node.guardrails.length !== 1 ||\n !guardrailMatches(node.guardrails[0], \"read_only_execution\", { requireScopeAbsent: true })\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: exactly one locked read_only_execution guardrail with no scope is required`,\n );\n }\n const domainCapabilities = node.required_capabilities.filter(isEnrichDomainCapability);\n if (domainCapabilities.length === 0) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: at least one of semantic_introspection/raw_material_read is required`,\n );\n }\n // Unlike Setup (which spawns a brand-new one-shot `codex exec` process per step and can pass\n // `--model` fresh each time — see `resolveStepModel`/`buildCodexArgs`), Enrich's session-based\n // transport (`CodexSessionRuntime`) binds one model to the whole persistent thread for its\n // entire lifetime: `thread/start` takes a single `model`, and there is no per-turn override.\n // Ask's own architecture confirms this is a real transport limit, not an arbitrary one: Ask\n // realizes multi-tier steps by spawning a *separate* sub-agent thread per tier\n // (`ask_runtime.ts`'s `spawnAgent`), a capability Enrich does not have. So an Enrich component\n // may now have more than one step, but it must still declare exactly one tier — the single-\n // `llm_call` shape this replaced only ever had one, and this keeps that one true as steps grow.\n const tiers = unique(node.llm_calls.map((step) => step.tier));\n if (tiers.length !== 1) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: this transport's persistent session supports exactly one ` +\n `tier per component; found '${tiers.join(\"', '\")}'`,\n );\n }\n const expectedLlm = `llm:${tiers[0]}`;\n if (!node.required_capabilities.includes(expectedLlm)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: required capability '${expectedLlm}' is missing`,\n );\n }\n const expectedCapabilities = new Set<string>([...domainCapabilities, expectedLlm]);\n if (!hasExactCapabilities(node.required_capabilities, expectedCapabilities)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: supports exactly ` +\n `'${domainCapabilities.join(\"', '\")}' and '${expectedLlm}' capabilities`,\n );\n }\n return domainCapabilities;\n}\n\nexport function matchesEnrichContractShape(node: ComponentNode): boolean {\n try {\n validateEnrichShape(node);\n return true;\n } catch (error) {\n if (error instanceof CodexDispatchError) return false;\n throw error;\n }\n}\n\n/**\n * The specific reason a component's IR shape does not match the Enrich contract, or null when it\n * does match. Mirrors `matchesEnrichContractShape`'s try/catch but preserves the validator's own\n * wall-hit message so a caller classifying across all three families can surface precisely which\n * structural expectation failed.\n */\nexport function enrichContractMismatchReason(node: ComponentNode): string | null {\n try {\n validateEnrichShape(node);\n return null;\n } catch (error) {\n if (error instanceof CodexDispatchError) return error.message;\n throw error;\n }\n}\n\nexport function prepareEnrich(input: PrepareEnrichInput): PreparedEnrichComponent {\n const ir = typeof input.ir === \"string\" ? parseIr(input.ir) : input.ir;\n if (ir.warble_ir_version !== SUPPORTED_IR_VERSION) {\n throw new CodexDispatchError(\n `unsupported warble_ir_version '${ir.warble_ir_version}' (supported: ${SUPPORTED_IR_VERSION})`,\n );\n }\n const node = ir.components.find((candidate) => candidate.id === input.component);\n if (!node) {\n throw new CodexDispatchError(\n `component '${input.component}' was not found in profile '${ir.profile}'`,\n );\n }\n const domainCapabilities = validateEnrichShape(node);\n const componentId = node.id;\n if (!/^[A-Za-z0-9_-]+$/.test(input.mcp.name)) {\n throw new CodexDispatchError(\n `MCP server name '${input.mcp.name}' must contain only letters, digits, '_' or '-'`,\n );\n }\n if (!isAbsolute(input.mcp.command)) {\n throw new CodexDispatchError(\n `MCP server command must be absolute when shell_environment_policy.inherit=none`,\n );\n }\n const enabledTools = unique(\n domainCapabilities.flatMap((capability) => input.mcp.toolsByCapability[capability] ?? []),\n );\n if (enabledTools.length === 0) {\n throw new CodexDispatchError(\n `component '${componentId}' has no allowlisted MCP tools for '${domainCapabilities.join(\"', '\")}'`,\n );\n }\n const topology = validateStepTopology(node);\n const steps: PreparedEnrichStep[] = node.llm_calls.map((call, index) => ({\n name: call.name,\n tier: call.tier,\n model: resolveStepModel(input.model, call.tier, componentId),\n prompt: call.prompt,\n consumes: call.consumes,\n produces: call.produces!,\n when: topology[index]!.when,\n }));\n return {\n target: TARGET,\n profile: ir.profile,\n node,\n componentId,\n domainCapabilities,\n steps,\n capabilities: resolveCapabilities(node.required_capabilities, input.mcp.name),\n enabledTools,\n mcp: input.mcp,\n };\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport type { ComponentNode, LlmCall } from \"./ir.js\";\n\n/**\n * The only `when` dialect this transport (and the Ask path) evaluates: a step runs only when an\n * earlier step in the same component failed. `target` names that earlier step.\n */\nexport interface OnFailureGuard {\n guard: \"on_failure\";\n target: string;\n}\n\n/**\n * Parses a step's `conditional`/`when` pair the same way Ask's `parseWhen` does: unconditional\n * steps must carry no guard, conditional steps must carry exactly `{guard: \"on_failure\", target}`.\n * Kept transport-neutral (no Ask import) so Setup/Enrich stay separate engines from Ask while\n * reading identically to it, without merging the three families.\n */\nexport function parseStepWhen(step: LlmCall): OnFailureGuard | null {\n if (!step.conditional) {\n if (step.when !== null) {\n throw new CodexDispatchError(`step '${step.name}' is unconditional but has a when guard`);\n }\n return null;\n }\n if (\n typeof step.when !== \"object\" ||\n step.when === null ||\n Array.isArray(step.when) ||\n (step.when as Record<string, unknown>)[\"guard\"] !== \"on_failure\" ||\n typeof (step.when as Record<string, unknown>)[\"target\"] !== \"string\"\n ) {\n throw new CodexDispatchError(`step '${step.name}' wall-hit: repair requires on_failure(target)`);\n }\n return {\n guard: \"on_failure\",\n target: (step.when as Record<string, string>)[\"target\"]!,\n };\n}\n\nexport interface StepTopology {\n when: OnFailureGuard | null;\n}\n\n/**\n * Validates the full step sequence's shape once every step has been individually accepted:\n *\n * - step names are unique (addressing by name, for both marshalling and on_failure targets,\n * requires this — it is also what turns the old \"grows a second step by cloning the same step\"\n * fixture into a genuine reject rather than an accidental accept);\n * - every step has a produced slot (the per-step generalization of the old single-step\n * \"requires a produced slot\" wall-hit — each step's completion is judged by whether it produced\n * what it declared, so every step needs that signal, not only the last one);\n * - every `consumes` name is satisfiable by some strictly earlier step's `produces` (unchanged\n * general rule from the single-step transport, now with more than one possible producer);\n * - an on_failure guard's target is the name of a strictly earlier step (no forward/self\n * reference — a target must already have run, or been skipped, by the time the guard is\n * evaluated);\n * - a conditional (on_failure-guarded) step must be the LAST step in the component. This is not\n * a hardcoded Setup/Enrich shape rule; it mirrors the one thing that keeps Ask's repair step\n * safe to skip — nothing downstream ever consumes a step that might not run. Without this rule\n * a validator could bless a component whose executor cannot honestly know what to feed a later\n * consumer when its producer was skipped, which is exactly the defect the validator's\n * accept-set-equals-execute-set invariant exists to prevent.\n */\nexport function validateStepTopology(node: ComponentNode): StepTopology[] {\n const names = new Set<string>();\n for (const step of node.llm_calls) {\n if (names.has(step.name)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step name '${step.name}' is declared more than once`,\n );\n }\n names.add(step.name);\n }\n const topology: StepTopology[] = [];\n const produced = new Set<string>();\n for (let index = 0; index < node.llm_calls.length; index += 1) {\n const step = node.llm_calls[index]!;\n for (const consumed of step.consumes) {\n if (!produced.has(consumed)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${step.name}' consumes '${consumed}' but no earlier step produces it`,\n );\n }\n }\n if (step.produces === null) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: this transport requires a produced slot; step '${step.name}' produces none`,\n );\n }\n produced.add(step.produces);\n const when = parseStepWhen(step);\n if (when !== null) {\n if (index !== node.llm_calls.length - 1) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: conditional step '${step.name}' must be the last step; a step nothing downstream can safely consume from must not have output others rely on`,\n );\n }\n if (!names.has(when.target) || !node.llm_calls.slice(0, index).some((earlier) => earlier.name === when.target)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${step.name}' on_failure target '${when.target}' is not an earlier step`,\n );\n }\n }\n topology.push({ when });\n }\n return topology;\n}\n\n/**\n * Parses a step's terminal text the way both Setup and Enrich judge whether a step \"succeeded\":\n * valid JSON, a single-key object whose key is exactly the step's declared `produces` name, with\n * a non-null value. Shared so Setup gains the same produces-field discipline Enrich already had,\n * and so a step's on_failure guard (see `validateStepTopology`) and a step's marshalled output\n * are judged by the identical rule.\n */\nexport function parseStepTerminal(text: string, produces: string): Record<string, unknown> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new CodexDispatchError(\"step terminal is not JSON\");\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CodexDispatchError(\"step terminal must be a JSON object\");\n }\n const record = parsed as Record<string, unknown>;\n const keys = Object.keys(record);\n if (keys.length !== 1 || keys[0] !== produces || record[produces] === null) {\n throw new CodexDispatchError(`step terminal requires exactly the produced field '${produces}'`);\n }\n return record;\n}\n\n/** A step's outcome after this dispatch has attempted (or skipped) it. */\nexport type StepOutcome =\n | { ran: true; ok: true; value: unknown }\n | { ran: true; ok: false }\n | { ran: false };\n\n/**\n * Decides, from the prior steps' recorded outcomes, whether a step with the given guard should\n * run this dispatch. `null` (unconditional) always runs. An on_failure guard runs only when its\n * target step ran and did not succeed — mirroring Ask's on_failure(target) direction (skip on\n * success, run on failure) while judging \"failure\" in terms this transport can honestly observe\n * (produces-field match) rather than borrowing Ask's structured-envelope `ok` field, which this\n * transport's steps have no contract to emit.\n */\nexport function shouldRunStep(when: OnFailureGuard | null, outcomes: ReadonlyMap<string, StepOutcome>): boolean {\n if (when === null) return true;\n const target = outcomes.get(when.target);\n return target !== undefined && target.ran && !target.ok;\n}\n\n/**\n * Resolves the model bound to a step's tier from a `PrepareInput.model` value that may be either\n * a single string (every step in the component runs at that one tier/model — the shape every\n * existing single-step fixture already uses) or a per-tier map (needed once a component declares\n * steps at more than one tier). Kept generic on the tier string itself: the validator already\n * deleted the tier whitelist, so this must not reintroduce one.\n */\nexport function resolveStepModel(model: string | Record<string, string>, tier: string, componentId: string): string {\n const resolved = typeof model === \"string\" ? model : model[tier];\n if (resolved === undefined || resolved.trim().length === 0) {\n throw new CodexDispatchError(\n `component '${componentId}' wall-hit: no model binding for tier '${tier}'`,\n );\n }\n return resolved;\n}\n","import { isAbsolute } from \"node:path\";\n\nimport { CodexDispatchError } from \"./error.js\";\nimport { assertDispatchableComponentIdentity } from \"./dispatch_registry.js\";\nimport {\n parseIr,\n SUPPORTED_IR_VERSION,\n TARGET,\n type ComponentNode,\n type WarbleIr,\n} from \"./ir.js\";\nimport { resolveStepModel, validateStepTopology, type OnFailureGuard } from \"./step_engine.js\";\nimport {\n guardrailMatches,\n hasExactCapabilities,\n isSetupDomainCapability,\n resolveCapabilities,\n type SetupDomainCapability,\n} from \"./target_profile.js\";\n\nexport type { SetupDomainCapability };\nexport type { OnFailureGuard };\n\nexport interface McpServerConfig {\n name: string;\n command: string;\n args?: string[];\n toolsByCapability: Record<SetupDomainCapability, string[]>;\n}\n\nexport interface CapabilityResolution {\n capability: string;\n outcome: \"native\" | \"realize-via\";\n via: string | null;\n}\n\nexport interface PreparedSetupStep {\n name: string;\n tier: string;\n model: string;\n prompt: string;\n consumes: string[];\n produces: string;\n when: OnFailureGuard | null;\n}\n\nexport interface PreparedSetupComponent {\n target: typeof TARGET;\n profile: string;\n node: ComponentNode;\n componentId: string;\n domainCapability: SetupDomainCapability;\n steps: PreparedSetupStep[];\n capabilities: CapabilityResolution[];\n enabledTools: string[];\n mcp: McpServerConfig;\n}\n\nexport interface PrepareInput {\n ir: string | WarbleIr;\n component: string;\n /**\n * A single string binds every step in the component to that one model (the shape every\n * existing single-step fixture already uses, and still all that's required when a component\n * declares only one tier). A per-tier map is required once a component declares steps at more\n * than one tier — see `resolveStepModel`.\n */\n model: string | Record<string, string>;\n mcp: McpServerConfig;\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction validateSetupShape(node: ComponentNode): SetupDomainCapability {\n if (\n node.type !== \"analytical\" ||\n node.realization_kind !== \"skill\" ||\n node.trigger.kind !== \"one_shot\" ||\n node.effect.outcome.kind !== \"none\" ||\n node.effect.render_blocks.length !== 0\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: requires analytical/skill/one_shot/none with no render blocks`,\n );\n }\n if (node.llm_calls.length === 0) {\n throw new CodexDispatchError(`component '${node.id}' wall-hit: at least one llm_call is required`);\n }\n // Validates the full step sequence: unique names, produces-slot discipline, consumes→produces\n // marshalling closure, and on_failure guard placement. This is where the three phase-A\n // wall-hits (\"exactly one llm_call\", \"does not evaluate step conditions\", \"requires a produced\n // slot\") now live, generalized to n steps rather than hardcoded to one.\n validateStepTopology(node);\n if (node.guardrails.length !== 1 || !guardrailMatches(node.guardrails[0], \"setup_execution\")) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: exactly one locked setup_execution guardrail with scope '.' is required`,\n );\n }\n const domainCapabilities = node.required_capabilities.filter(isSetupDomainCapability);\n if (domainCapabilities.length !== 1) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: exactly one of source_connect/context_build is required`,\n );\n }\n const tiers = unique(node.llm_calls.map((step) => step.tier));\n const expectedLlm = tiers.length === 1 ? `llm:${tiers[0]}` : \"llm:per_step_tier\";\n if (!node.required_capabilities.includes(expectedLlm)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: required capability '${expectedLlm}' is missing`,\n );\n }\n const expectedCapabilities = new Set<string>([domainCapabilities[0]!, expectedLlm]);\n if (!hasExactCapabilities(node.required_capabilities, expectedCapabilities)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: supports exactly '${domainCapabilities[0]}' and '${expectedLlm}' capabilities`,\n );\n }\n return domainCapabilities[0]!;\n}\n\nexport function matchesSetupContractShape(node: ComponentNode): boolean {\n try {\n validateSetupShape(node);\n return true;\n } catch (error) {\n if (error instanceof CodexDispatchError) return false;\n throw error;\n }\n}\n\n/**\n * The specific reason a component's IR shape does not match the Setup contract, or null when it\n * does match. This mirrors `matchesSetupContractShape`'s try/catch but preserves the validator's\n * own wall-hit message instead of collapsing it to a boolean, so a caller classifying across all\n * three families can surface precisely which structural expectation failed.\n */\nexport function setupContractMismatchReason(node: ComponentNode): string | null {\n try {\n validateSetupShape(node);\n return null;\n } catch (error) {\n if (error instanceof CodexDispatchError) return error.message;\n throw error;\n }\n}\n\nexport function prepareSetup(input: PrepareInput): PreparedSetupComponent {\n const ir = typeof input.ir === \"string\" ? parseIr(input.ir) : input.ir;\n if (ir.warble_ir_version !== SUPPORTED_IR_VERSION) {\n throw new CodexDispatchError(\n `unsupported warble_ir_version '${ir.warble_ir_version}' (supported: ${SUPPORTED_IR_VERSION})`,\n );\n }\n const node = ir.components.find((candidate) => candidate.id === input.component);\n if (!node) {\n throw new CodexDispatchError(`component '${input.component}' was not found in profile '${ir.profile}'`);\n }\n assertDispatchableComponentIdentity(node);\n const domainCapability = validateSetupShape(node);\n const componentId = node.id;\n if (!/^[A-Za-z0-9_-]+$/.test(input.mcp.name)) {\n throw new CodexDispatchError(\n `MCP server name '${input.mcp.name}' must contain only letters, digits, '_' or '-'`,\n );\n }\n if (!isAbsolute(input.mcp.command)) {\n throw new CodexDispatchError(\n `MCP server command must be absolute when shell_environment_policy.inherit=none`,\n );\n }\n const enabledTools = unique(input.mcp.toolsByCapability[domainCapability]);\n if (enabledTools.length === 0) {\n throw new CodexDispatchError(\n `component '${componentId}' has no allowlisted MCP tools for '${domainCapability}'`,\n );\n }\n const topology = validateStepTopology(node);\n const steps: PreparedSetupStep[] = node.llm_calls.map((call, index) => ({\n name: call.name,\n tier: call.tier,\n model: resolveStepModel(input.model, call.tier, componentId),\n prompt: call.prompt,\n consumes: call.consumes,\n produces: call.produces!,\n when: topology[index]!.when,\n }));\n return {\n target: TARGET,\n profile: ir.profile,\n node,\n componentId,\n domainCapability,\n steps,\n capabilities: resolveCapabilities(node.required_capabilities, input.mcp.name),\n enabledTools,\n mcp: input.mcp,\n };\n}\n\nexport function prepareAllSetup(\n raw: string,\n config: Omit<PrepareInput, \"ir\" | \"component\">,\n): PreparedSetupComponent[] {\n const ir = parseIr(raw);\n // Aggregate preparation must reject a reserved host-only identity before preparing any\n // component, so a direct caller cannot receive a partial array preceding the wall-hit.\n for (const node of ir.components) assertDispatchableComponentIdentity(node);\n return ir.components.map((node) =>\n prepareSetup({ ...config, ir, component: node.id }),\n );\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport type { ComponentNode, WarbleIr } from \"./ir.js\";\nimport { askContractMismatchReason, matchesAskContractShape } from \"./ask_prepare.js\";\nimport { assertDispatchableComponentIdentity } from \"./dispatch_registry.js\";\nimport { enrichContractMismatchReason, matchesEnrichContractShape } from \"./enrich_prepare.js\";\nimport { setupContractMismatchReason, matchesSetupContractShape } from \"./prepare.js\";\n\n/**\n * The public CLI is intentionally profile-agnostic. These are implementation contracts selected\n * from a parsed component's declared IR shape, never from a command spelling, profile name, or\n * component identity.\n */\nexport type DispatchContract = \"setup\" | \"ask\" | \"enrich\";\n\nfunction selectedComponent(ir: WarbleIr, component: string): ComponentNode {\n const node = ir.components.find((candidate) => candidate.id === component);\n if (!node) {\n throw new CodexDispatchError(`component '${component}' was not found in profile '${ir.profile}'`);\n }\n return node;\n}\n\n/**\n * Select the native execution contract only when exactly one complete structural contract matches.\n * This check runs before configuration, preparation, or a runtime launch.\n */\nexport function classifyDispatchContract(ir: WarbleIr, component: string): DispatchContract {\n const node = selectedComponent(ir, component);\n assertDispatchableComponentIdentity(node);\n const matches = [\n ...(matchesSetupContractShape(node) ? ([\"setup\"] as const) : []),\n ...(matchesAskContractShape(node) ? ([\"ask\"] as const) : []),\n ...(matchesEnrichContractShape(node) ? ([\"enrich\"] as const) : []),\n ];\n if (matches.length === 1) return matches[0]!;\n if (matches.length === 0) {\n // No single family shape matched. Rather than collapse to one generic sentence, surface each\n // family validator's own specific wall-hit reason so the diagnostic still names the concrete\n // structural expectation that failed (e.g. a guardrail contract mismatch), not just the fact\n // that nothing matched.\n const reasons = [\n setupContractMismatchReason(node),\n askContractMismatchReason(node),\n enrichContractMismatchReason(node),\n ].filter((reason): reason is string => reason !== null);\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: no supported codex:local execution contract matches its complete IR shape` +\n (reasons.length > 0 ? ` (${reasons.join(\" | \")})` : \"\"),\n );\n }\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: ambiguous codex:local execution contracts (${matches.join(\", \")})`,\n );\n}\n\n/**\n * Setup is the sole whole-profile manifest/describe contract. Other shapes are scoped dispatches\n * and therefore require an explicit --component selection.\n */\nexport function supportsSetupAggregate(ir: WarbleIr): boolean {\n // Scan the complete profile for host-only identities before testing whether it is an aggregate.\n // Otherwise a preceding non-Setup node could short-circuit `.every()` and leave a forged\n // reserved identity unchecked on the generic manifest/describe path.\n for (const node of ir.components) assertDispatchableComponentIdentity(node);\n return ir.components.length > 0 && ir.components.every(matchesSetupContractShape);\n}\n","import { SUPPORTED_IR_VERSION, TARGET } from \"./ir.js\";\nimport type { PreparedSetupComponent } from \"./prepare.js\";\nimport type { PreparedAskComponent } from \"./ask_prepare.js\";\nimport type { PreparedEnrichComponent } from \"./enrich_prepare.js\";\n\nexport interface StepManifest {\n name: string;\n tier: string;\n model: string;\n consumes: string[];\n produces: string | null;\n agent_role?: string;\n conditional?: boolean;\n when?: { guard: string; target: string } | null;\n tools?: string[];\n}\n\nexport interface AgentManifest {\n id: string;\n verb: string;\n component_type: string;\n realization_kind: string;\n trigger: string;\n outcome: string;\n steps: StepManifest[];\n capabilities: PreparedSetupComponent[\"capabilities\"];\n tools: Array<{ name: string; source: string; agents?: string[] }>;\n guardrails: Record<string, unknown>;\n artifact_output?: {\n kind: \"render_envelope\";\n persistence: \"consumer\";\n block_types: string[];\n };\n}\n\nexport interface Manifest {\n manifest_version: \"0.1\";\n compat: {\n min_ir_version: typeof SUPPORTED_IR_VERSION;\n max_ir_version: typeof SUPPORTED_IR_VERSION;\n };\n profile: string;\n target: typeof TARGET;\n session: SessionManifest;\n agents: AgentManifest[];\n}\n\nexport const SESSION_LIFECYCLE_OPERATIONS = [\n \"start\",\n \"resume\",\n \"read\",\n \"turn\",\n \"steer\",\n \"interrupt\",\n \"fork\",\n] as const;\n\nexport interface SessionManifest {\n persistence: \"codex_thread_history\";\n lifecycle_operations: Array<(typeof SESSION_LIFECYCLE_OPERATIONS)[number]>;\n artifact_reference:\n | \"allowlisted_mcp_tool_result\"\n | \"allowlisted_mcp_tool_result_or_render_envelope\";\n isolation: \"dedicated_persistent_codex_home\";\n authentication: \"externally_provisioned\";\n}\n\nexport interface TargetDescription {\n target: typeof TARGET;\n phase:\n | \"setup-only\"\n | \"setup-and-ask-parity\"\n | \"setup-ask-and-dashboard-parity\"\n | \"enrich-parity\";\n execution_modes: Array<\"one_shot\" | \"persistent_session\">;\n session_persistence: SessionManifest[\"persistence\"];\n lifecycle_operations: SessionManifest[\"lifecycle_operations\"];\n supported_components: string[];\n tiers: string[];\n capabilities: string[];\n tools: string[];\n guardrails: string[];\n}\n\nexport function buildAskAgentManifest(prepared: PreparedAskComponent): AgentManifest {\n const toolAgents = new Map<string, string[]>();\n for (const step of prepared.steps) {\n for (const tool of step.enabledTools) {\n const agents = toolAgents.get(tool) ?? [];\n if (!agents.includes(step.role)) agents.push(step.role);\n toolAgents.set(tool, agents);\n }\n }\n const dashboard = prepared.executionKind === \"generate_dashboard\";\n return {\n id: prepared.node.id,\n verb: prepared.node.verb,\n component_type: prepared.node.type,\n realization_kind: prepared.node.realization_kind,\n trigger: prepared.node.trigger.kind,\n outcome: prepared.node.effect.outcome.kind,\n steps: prepared.steps.map((step) => ({\n name: step.name,\n tier: step.tier,\n model: step.model,\n consumes: [...step.consumes],\n produces: step.produces,\n agent_role: step.role,\n conditional: step.conditional,\n when: step.when,\n tools: [...step.enabledTools],\n })),\n capabilities: prepared.capabilities,\n tools: [...toolAgents].map(([name, agents]) => ({\n name,\n source: `mcp:${prepared.mcp.name}`,\n agents,\n })),\n guardrails: {\n read_only_execution: { enforcement: \"per_agent_mcp_only_read_only_sandbox\", locked: true },\n ...(dashboard\n ? {\n artifact_write: {\n enforcement: \"consumer_persisted_render_envelope\",\n locked: true,\n scope: \".\",\n },\n render_contract: {\n enforcement: \"validated_ir_declared_render_envelope\",\n on_failure: \"degrade\",\n },\n }\n : {\n deterministic_gate: {\n enforcement: \"child_result_envelope_and_event_attribution\",\n locked: true,\n },\n row_limit: { threshold: 1000 },\n statement_timeout: { threshold: 30 },\n }),\n ordered_delegation: {\n enforcement: \"named_child_threads_in_ir_order\",\n flattening: \"forbidden\",\n },\n ...(dashboard\n ? {}\n : {\n conditional_repair: {\n guard: prepared.steps[2]!.when,\n max_attempts: prepared.maxRepairAttempts,\n exhaustion: \"loud_fail\",\n },\n }),\n isolated_codex_config: {\n parent_tools: \"multi_agent_only\",\n child_tools: \"per_step_exact_mcp_allowlist\",\n approval_policy: \"never\",\n sandbox: \"read-only\",\n api_key_environment: \"removed\",\n },\n },\n ...(dashboard\n ? {\n artifact_output: {\n kind: \"render_envelope\" as const,\n persistence: \"consumer\" as const,\n block_types: prepared.node.effect.render_blocks.map((block) =>\n typeof block === \"object\" && block !== null && \"type\" in block\n ? String((block as { type: unknown }).type)\n : \"unknown\",\n ),\n },\n }\n : {}),\n };\n}\n\nexport function buildAskManifest(prepared: PreparedAskComponent): Manifest {\n return {\n manifest_version: \"0.1\",\n compat: {\n min_ir_version: SUPPORTED_IR_VERSION,\n max_ir_version: SUPPORTED_IR_VERSION,\n },\n profile: prepared.profile,\n target: TARGET,\n session: {\n persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n artifact_reference:\n prepared.executionKind === \"generate_dashboard\"\n ? \"allowlisted_mcp_tool_result_or_render_envelope\"\n : \"allowlisted_mcp_tool_result\",\n isolation: \"dedicated_persistent_codex_home\",\n authentication: \"externally_provisioned\",\n },\n agents: [buildAskAgentManifest(prepared)],\n };\n}\n\nexport function describeAskTarget(prepared: PreparedAskComponent): TargetDescription {\n return {\n target: TARGET,\n phase:\n prepared.executionKind === \"generate_dashboard\"\n ? \"setup-ask-and-dashboard-parity\"\n : \"setup-and-ask-parity\",\n execution_modes: [\"persistent_session\"],\n session_persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n supported_components: [prepared.componentId],\n tiers: [...new Set(prepared.steps.map((step) => step.tier))],\n capabilities: prepared.capabilities.map((entry) => entry.capability),\n tools: [...new Set(prepared.steps.flatMap((step) => step.enabledTools))],\n guardrails:\n prepared.executionKind === \"generate_dashboard\"\n ? [\n \"read_only_execution\",\n \"artifact_write\",\n \"render_contract\",\n \"ordered_delegation\",\n \"isolated_codex_config\",\n ]\n : [\n \"read_only_execution\",\n \"deterministic_gate\",\n \"row_limit\",\n \"statement_timeout\",\n \"ordered_delegation\",\n \"conditional_repair\",\n \"isolated_codex_config\",\n ],\n };\n}\n\nexport function buildAgentManifest(prepared: PreparedSetupComponent): AgentManifest {\n return {\n id: prepared.node.id,\n verb: prepared.node.verb,\n component_type: prepared.node.type,\n realization_kind: prepared.node.realization_kind,\n trigger: prepared.node.trigger.kind,\n outcome: prepared.node.effect.outcome.kind,\n steps: prepared.steps.map((step) => ({\n name: step.name,\n tier: step.tier,\n model: step.model,\n consumes: step.consumes,\n produces: step.produces,\n })),\n capabilities: prepared.capabilities,\n tools: prepared.enabledTools.map((name) => ({\n name,\n source: `mcp:${prepared.mcp.name}`,\n })),\n guardrails: {\n setup_execution: {\n enforcement: \"mcp_only_read_only_sandbox\",\n locked: true,\n scope: \".\",\n },\n isolated_codex_config: {\n ignore_user_config: true,\n ephemeral: true,\n approval_policy: \"never\",\n sandbox: \"read-only\",\n api_key_environment: \"removed\",\n },\n },\n };\n}\n\nexport function buildManifest(prepared: readonly PreparedSetupComponent[]): Manifest {\n const first = prepared[0];\n if (!first) {\n throw new Error(\"cannot build a manifest without prepared components\");\n }\n return {\n manifest_version: \"0.1\",\n compat: {\n min_ir_version: SUPPORTED_IR_VERSION,\n max_ir_version: SUPPORTED_IR_VERSION,\n },\n profile: first.profile,\n target: TARGET,\n session: {\n persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n artifact_reference: \"allowlisted_mcp_tool_result\",\n isolation: \"dedicated_persistent_codex_home\",\n authentication: \"externally_provisioned\",\n },\n agents: prepared.map(buildAgentManifest),\n };\n}\n\nexport function describeTarget(prepared: readonly PreparedSetupComponent[]): TargetDescription {\n return {\n target: TARGET,\n phase: \"setup-only\",\n execution_modes: [\"one_shot\", \"persistent_session\"],\n session_persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n supported_components: prepared.map((component) => component.componentId),\n tiers: [...new Set(prepared.flatMap((component) => component.steps.map((step) => step.tier)))],\n capabilities: [\n ...new Set(prepared.flatMap((component) => component.capabilities.map((entry) => entry.capability))),\n ],\n tools: [...new Set(prepared.flatMap((component) => component.enabledTools))],\n guardrails: [\"setup_execution\", \"isolated_codex_config\"],\n };\n}\n\n// Enrich is scoped-only (no whole-profile aggregator), mirroring Ask rather than Setup: the profile\n// deliberately mixes two dispatchable read-only skills with a gated-tool component (non-`skill`\n// realization_kind, host-owned capabilities) that no headless target can ever legalize, so a\n// `.map()`-style aggregator across the whole profile would always throw and would not describe\n// anything real. Each enrichment component is dispatched with its own `dispatch --component <id>`\n// turn, exactly like the two existing families' per-component calls.\nexport function buildEnrichAgentManifest(prepared: PreparedEnrichComponent): AgentManifest {\n return {\n id: prepared.node.id,\n verb: prepared.node.verb,\n component_type: prepared.node.type,\n realization_kind: prepared.node.realization_kind,\n trigger: prepared.node.trigger.kind,\n outcome: prepared.node.effect.outcome.kind,\n steps: prepared.steps.map((step) => ({\n name: step.name,\n tier: step.tier,\n model: step.model,\n consumes: step.consumes,\n produces: step.produces,\n })),\n capabilities: prepared.capabilities,\n tools: prepared.enabledTools.map((name) => ({\n name,\n source: `mcp:${prepared.mcp.name}`,\n })),\n guardrails: {\n read_only_execution: {\n enforcement: \"mcp_only_read_only_sandbox\",\n locked: true,\n },\n isolated_codex_config: {\n ignore_user_config: true,\n ephemeral: true,\n approval_policy: \"never\",\n sandbox: \"read-only\",\n api_key_environment: \"removed\",\n },\n },\n };\n}\n\nexport function buildEnrichManifest(prepared: PreparedEnrichComponent): Manifest {\n return {\n manifest_version: \"0.1\",\n compat: {\n min_ir_version: SUPPORTED_IR_VERSION,\n max_ir_version: SUPPORTED_IR_VERSION,\n },\n profile: prepared.profile,\n target: TARGET,\n session: {\n persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n artifact_reference: \"allowlisted_mcp_tool_result\",\n isolation: \"dedicated_persistent_codex_home\",\n authentication: \"externally_provisioned\",\n },\n agents: [buildEnrichAgentManifest(prepared)],\n };\n}\n\nexport function describeEnrichTarget(prepared: PreparedEnrichComponent): TargetDescription {\n return {\n target: TARGET,\n phase: \"enrich-parity\",\n execution_modes: [\"one_shot\", \"persistent_session\"],\n session_persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n supported_components: [prepared.componentId],\n tiers: [...new Set(prepared.steps.map((step) => step.tier))],\n capabilities: prepared.capabilities.map((entry) => entry.capability),\n tools: [...prepared.enabledTools],\n guardrails: [\"read_only_execution\", \"isolated_codex_config\"],\n };\n}\n","import { resolve } from \"node:path\";\n\nimport { CodexAppServerTransport, type CatalogTransportOptions } from \"./app_server_transport.js\";\n\n/** The deliberately small host-facing contract for provider-owned model discovery. */\nexport const MODEL_CATALOG_VERSION = 1 as const;\n\nexport interface ModelCatalogModel {\n model: string;\n displayName: string;\n description?: string;\n isDefault?: boolean;\n reasoningEfforts?: Array<{ value: string; displayName: string; description?: string }>;\n}\n\nexport type ModelCatalogUnavailableCode =\n | \"not_authenticated\"\n | \"runtime_unavailable\"\n | \"timeout\"\n | \"protocol_error\";\n\nexport type ModelCatalogResult =\n | {\n version: typeof MODEL_CATALOG_VERSION;\n status: \"ready\";\n provider: \"codex\";\n models: ModelCatalogModel[];\n }\n | {\n version: typeof MODEL_CATALOG_VERSION;\n status: \"unavailable\";\n provider: \"codex\";\n code: ModelCatalogUnavailableCode;\n retryable: boolean;\n };\n\nexport interface DiscoverCodexModelsOptions {\n cwd?: string;\n codexHome?: string;\n codexBin?: string;\n timeoutMs?: number;\n env?: NodeJS.ProcessEnv;\n}\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\nconst PAGE_LIMIT = 100;\nconst MAX_PAGES = 100;\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction unavailable(code: ModelCatalogUnavailableCode, retryable: boolean): ModelCatalogResult {\n return { version: MODEL_CATALOG_VERSION, status: \"unavailable\", provider: \"codex\", code, retryable };\n}\n\nfunction classify(error: unknown): ModelCatalogResult {\n const message = error instanceof Error ? error.message.toLowerCase() : \"\";\n if (message.includes(\"timed out\")) return unavailable(\"timeout\", true);\n if (/(not authenticated|unauthenticated|authentication|login required|sign in)/.test(message)) {\n return unavailable(\"not_authenticated\", false);\n }\n if (/(enoent|failed to start|not found|transport is not available|disconnected)/.test(message)) {\n return unavailable(\"runtime_unavailable\", true);\n }\n // Never reflect raw JSON-RPC/provider errors: their payload is outside the public contract.\n return unavailable(\"protocol_error\", false);\n}\n\nfunction text(record: JsonRecord, field: string, required = false): string | undefined {\n const value = record[field];\n if (value === undefined && !required) return undefined;\n if (typeof value !== \"string\") throw new Error(\"malformed model catalog response\");\n return value;\n}\n\nfunction mapModel(raw: unknown): ModelCatalogModel | null {\n if (!isRecord(raw)) throw new Error(\"malformed model catalog response\");\n // Defense in depth: the request has includeHidden=false and an unexpected hidden model still\n // never reaches a host picker.\n if (raw[\"hidden\"] === true) return null;\n const model = text(raw, \"model\", true)!;\n const displayName = text(raw, \"displayName\", true)!;\n const description = text(raw, \"description\");\n const isDefault = raw[\"isDefault\"];\n if (isDefault !== undefined && typeof isDefault !== \"boolean\") {\n throw new Error(\"malformed model catalog response\");\n }\n const effortsRaw = raw[\"supportedReasoningEfforts\"];\n let reasoningEfforts: ModelCatalogModel[\"reasoningEfforts\"];\n if (effortsRaw !== undefined) {\n if (!Array.isArray(effortsRaw)) throw new Error(\"malformed model catalog response\");\n reasoningEfforts = effortsRaw.map((effort) => {\n if (!isRecord(effort)) throw new Error(\"malformed model catalog response\");\n const value = text(effort, \"reasoningEffort\", true)!;\n const effortDescription = text(effort, \"description\");\n return {\n value,\n // The app-server protocol exposes an effort value, not a separate label.\n displayName: value,\n ...(effortDescription === undefined ? {} : { description: effortDescription }),\n };\n });\n }\n return {\n model,\n displayName,\n ...(description === undefined ? {} : { description }),\n ...(isDefault === undefined ? {} : { isDefault }),\n ...(reasoningEfforts === undefined ? {} : { reasoningEfforts }),\n };\n}\n\nfunction pageResponse(value: unknown): { data: unknown[]; nextCursor: string | null } {\n if (!isRecord(value) || !Array.isArray(value[\"data\"])) {\n throw new Error(\"malformed model catalog response\");\n }\n const nextCursor = value[\"nextCursor\"];\n if (nextCursor !== null && nextCursor !== undefined && typeof nextCursor !== \"string\") {\n throw new Error(\"malformed model catalog response\");\n }\n return { data: value[\"data\"], nextCursor: (nextCursor ?? null) as string | null };\n}\n\n/**\n * List authenticated Codex models over app-server without creating a thread or a turn.\n * Only explicitly mapped model-picker fields ever leave this module.\n */\nexport async function discoverCodexModels(\n options: DiscoverCodexModelsOptions = {},\n): Promise<ModelCatalogResult> {\n const timeoutMs = options.timeoutMs ?? 10_000;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return unavailable(\"protocol_error\", false);\n let transport: CodexAppServerTransport | undefined;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const transportOptions: CatalogTransportOptions = {\n cwd: resolve(options.cwd ?? process.cwd()),\n timeoutMs,\n ...(options.codexHome ? { codexHome: resolve(options.codexHome) } : {}),\n ...(options.codexBin ? { codexBin: resolve(options.codexBin) } : {}),\n ...(options.env ? { env: options.env } : {}),\n };\n const deadline = new Promise<never>((_, reject) => {\n timeout = setTimeout(() => {\n void transport?.close();\n reject(new Error(\"model catalog timed out\"));\n }, timeoutMs);\n });\n const list = (async (): Promise<ModelCatalogResult> => {\n transport = await CodexAppServerTransport.startCatalog(transportOptions);\n const models: ModelCatalogModel[] = [];\n let cursor: string | null = null;\n for (let page = 0; page < MAX_PAGES; page += 1) {\n const response = pageResponse(await transport.request(\"model/list\", {\n cursor,\n limit: PAGE_LIMIT,\n includeHidden: false,\n }));\n for (const raw of response.data) {\n const model = mapModel(raw);\n if (model !== null) models.push(model);\n }\n if (response.nextCursor === null) {\n return { version: MODEL_CATALOG_VERSION, status: \"ready\", provider: \"codex\", models };\n }\n cursor = response.nextCursor;\n }\n throw new Error(\"model catalog pagination limit exceeded\");\n })();\n return await Promise.race([list, deadline]);\n } catch (error) {\n return classify(error);\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n await transport?.close();\n }\n}\n","import { buildIsolationConfig, buildPrompt, type PreparedStepLike } from \"./config.js\";\nimport { CodexDispatchError } from \"./error.js\";\nimport { CodexAppServerTransport } from \"./app_server_transport.js\";\nimport type { PreparedSetupComponent } from \"./prepare.js\";\nimport type { PreparedEnrichComponent } from \"./enrich_prepare.js\";\nimport {\n SESSION_REFERENCE_VERSION,\n type CodexArtifactReference,\n type CodexHistoryItem,\n type CodexHistoryTurn,\n type CodexSessionEvent,\n type CodexSessionHistory,\n type CodexSessionReference,\n type CodexTurnReference,\n type SessionIsolationOptions,\n type SessionTurnStatus,\n} from \"./session_types.js\";\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\ninterface ActiveTurn {\n started: boolean;\n pendingTools: Set<string>;\n successfulTools: number;\n hasAnswer: boolean;\n}\n\ninterface TurnWaiter {\n resolve: (turn: CodexTurnReference) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\nconst FORBIDDEN_ITEM_TYPES = new Set([\n \"commandExecution\",\n \"fileChange\",\n \"webSearch\",\n \"imageGeneration\",\n \"collabAgentToolCall\",\n \"subAgentActivity\",\n \"dynamicToolCall\",\n \"imageView\",\n \"sleep\",\n \"enteredReviewMode\",\n \"exitedReviewMode\",\n]);\n\nconst PASSIVE_ITEM_TYPES = new Set([\n \"userMessage\",\n \"agentMessage\",\n \"reasoning\",\n \"plan\",\n \"compacted\",\n \"contextCompaction\",\n]);\n\nconst IGNORED_NOTIFICATIONS = new Set([\n \"skills/changed\",\n \"thread/name/updated\",\n \"thread/goal/updated\",\n \"thread/goal/cleared\",\n \"thread/settings/updated\",\n \"thread/status/changed\",\n \"thread/tokenUsage/updated\",\n \"thread/compacted\",\n \"turn/diff/updated\",\n \"turn/plan/updated\",\n \"item/agentMessage/delta\",\n \"item/plan/delta\",\n \"item/mcpToolCall/progress\",\n \"item/reasoning/summaryTextDelta\",\n \"item/reasoning/summaryPartAdded\",\n \"item/reasoning/textDelta\",\n \"mcpServer/startupStatus/updated\",\n \"account/updated\",\n \"account/rateLimits/updated\",\n \"app/list/updated\",\n \"remoteControl/status/changed\",\n \"fs/changed\",\n \"model/rerouted\",\n \"model/verification\",\n \"model/safetyBuffering/updated\",\n \"turn/moderationMetadata\",\n \"warning\",\n \"guardianWarning\",\n \"deprecationNotice\",\n]);\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requiredRecord(value: unknown, context: string): JsonRecord {\n if (!isRecord(value)) throw new CodexDispatchError(`${context} requires an object`);\n return value;\n}\n\nfunction requiredString(record: JsonRecord, key: string, context: string): string {\n const value = record[key];\n if (typeof value !== \"string\" || value.length === 0) {\n throw new CodexDispatchError(`${context} requires string ${key}`);\n }\n return value;\n}\n\nfunction sessionReference(thread: JsonRecord): CodexSessionReference {\n return {\n version: SESSION_REFERENCE_VERSION,\n target: \"codex:local\",\n threadId: requiredString(thread, \"id\", \"thread\"),\n forkedFromThreadId:\n typeof thread[\"forkedFromId\"] === \"string\" ? thread[\"forkedFromId\"] : null,\n };\n}\n\nfunction turnStatus(value: unknown): SessionTurnStatus {\n switch (value) {\n case \"inProgress\":\n return \"in_progress\";\n case \"completed\":\n case \"interrupted\":\n case \"failed\":\n return value;\n default:\n throw new CodexDispatchError(\"turn requires a recognized status\");\n }\n}\n\nfunction turnReference(threadId: string, turn: JsonRecord): CodexTurnReference {\n return {\n threadId,\n turnId: requiredString(turn, \"id\", \"turn\"),\n status: turnStatus(turn[\"status\"]),\n };\n}\n\nfunction validateReference(reference: CodexSessionReference): void {\n if (\n reference.version !== SESSION_REFERENCE_VERSION ||\n reference.target !== \"codex:local\" ||\n reference.threadId.length === 0\n ) {\n throw new CodexDispatchError(\"invalid codex session reference\");\n }\n}\n\nexport class CodexSessionRuntime {\n private transport!: CodexAppServerTransport;\n private session: CodexSessionReference | null = null;\n private readonly activeTurns = new Map<string, ActiveTurn>();\n private readonly waiters = new Map<string, TurnWaiter[]>();\n private readonly stepNameByTurn = new Map<string, string>();\n private disconnected = false;\n\n private constructor(\n private readonly prepared: PreparedSetupComponent | PreparedEnrichComponent,\n private readonly options: SessionIsolationOptions,\n ) {}\n\n /**\n * The model bound to this persistent thread for its whole lifetime. `thread/start` takes a\n * single `model` with no per-turn override, so unlike Setup's one-shot-process-per-step\n * transport, every step dispatched through one session must resolve to the same model — see\n * `enrich_prepare.ts`'s single-tier-per-component requirement, which is what makes this true by\n * construction rather than by convention.\n */\n private get model(): string {\n return this.prepared.steps[0]!.model;\n }\n\n static async connect(\n prepared: PreparedSetupComponent | PreparedEnrichComponent,\n options: SessionIsolationOptions,\n ): Promise<CodexSessionRuntime> {\n if (prepared.steps.length === 0) {\n throw new CodexDispatchError(\"cannot connect a session runtime without at least one prepared step\");\n }\n const sessionModel = prepared.steps[0]!.model;\n for (const step of prepared.steps) {\n if (step.model !== sessionModel) {\n throw new CodexDispatchError(\n \"this transport's persistent session is bound to one model per thread; \" +\n `step '${step.name}' requires a different model than the session's first step`,\n );\n }\n }\n const runtime = new CodexSessionRuntime(prepared, options);\n runtime.transport = await CodexAppServerTransport.start(\n prepared,\n options,\n (method, params) => runtime.onNotification(method, params),\n (error) => runtime.onDisconnect(error),\n );\n return runtime;\n }\n\n async start(): Promise<CodexSessionReference> {\n this.ensureConnected();\n if (this.session !== null) {\n throw new CodexDispatchError(\"a session is already loaded; use a new runtime to start another\");\n }\n const result = requiredRecord(\n await this.transport.request(\"thread/start\", {\n model: this.model,\n cwd: this.options.cwd,\n approvalPolicy: \"never\",\n sandbox: \"read-only\",\n config: buildIsolationConfig(this.prepared),\n ephemeral: false,\n historyMode: \"legacy\",\n environments: [],\n runtimeWorkspaceRoots: [],\n selectedCapabilityRoots: [],\n dynamicTools: [],\n experimentalRawEvents: false,\n }),\n \"thread/start response\",\n );\n const reference = sessionReference(requiredRecord(result[\"thread\"], \"thread/start thread\"));\n this.session = reference;\n this.emit({ t: \"session_started\", session: reference });\n return reference;\n }\n\n async resume(reference: CodexSessionReference): Promise<CodexSessionReference> {\n validateReference(reference);\n this.ensureConnected();\n this.requireNoActiveTurns(\"resume\");\n if (this.session !== null && this.session.threadId !== reference.threadId) {\n throw new CodexDispatchError(\n \"a different session is already loaded; use a new runtime to resume another\",\n );\n }\n const result = requiredRecord(\n await this.transport.request(\"thread/resume\", {\n threadId: reference.threadId,\n model: this.model,\n cwd: this.options.cwd,\n approvalPolicy: \"never\",\n sandbox: \"read-only\",\n config: buildIsolationConfig(this.prepared),\n runtimeWorkspaceRoots: [],\n }),\n \"thread/resume response\",\n );\n const resumed = sessionReference(requiredRecord(result[\"thread\"], \"thread/resume thread\"));\n if (resumed.threadId !== reference.threadId) {\n throw new CodexDispatchError(\"thread/resume returned a different thread id\");\n }\n this.session = resumed;\n this.emit({ t: \"session_resumed\", session: resumed });\n return resumed;\n }\n\n async read(reference: CodexSessionReference): Promise<CodexSessionHistory> {\n validateReference(reference);\n this.ensureConnected();\n const result = requiredRecord(\n await this.transport.request(\"thread/read\", { threadId: reference.threadId, includeTurns: true }),\n \"thread/read response\",\n );\n const thread = requiredRecord(result[\"thread\"], \"thread/read thread\");\n const readReference = sessionReference(thread);\n if (readReference.threadId !== reference.threadId) {\n throw new CodexDispatchError(\"thread/read returned a different thread id\");\n }\n const turns = Array.isArray(thread[\"turns\"])\n ? thread[\"turns\"].map((turn) => this.projectHistoryTurn(reference.threadId, turn))\n : [];\n return { session: readReference, turns };\n }\n\n /**\n * `step`/`inputs` default to this component's first (and, for every existing single-step\n * fixture, only) step with no marshalled inputs — so every pre-existing caller that never named\n * a step keeps building the exact same prompt as before. A multi-step caller (the n-step Enrich\n * executor) passes the step actually being dispatched this turn, plus that step's marshalled\n * `consumes` values, and this records which step owns the resulting turn id so the\n * `step_start`/`step_finish` events this turn emits are attributed correctly rather than always\n * naming the component's first step.\n */\n async turn(\n reference: CodexSessionReference,\n input: string,\n step: PreparedStepLike = this.prepared.steps[0]!,\n inputs: Record<string, unknown> = {},\n ): Promise<CodexTurnReference> {\n this.requireCurrent(reference);\n if (input.length === 0) throw new CodexDispatchError(\"turn input must not be empty\");\n const result = requiredRecord(\n await this.transport.request(\"turn/start\", {\n threadId: reference.threadId,\n input: [\n { type: \"text\", text: buildPrompt(this.prepared, step, input, inputs), text_elements: [] },\n ],\n approvalPolicy: \"never\",\n environments: [],\n runtimeWorkspaceRoots: [],\n }),\n \"turn/start response\",\n );\n const turn = turnReference(reference.threadId, requiredRecord(result[\"turn\"], \"turn/start turn\"));\n if (turn.status !== \"in_progress\") {\n throw new CodexDispatchError(\"turn/start did not return an in-progress turn\");\n }\n this.ensureActiveTurn(turn.turnId);\n this.stepNameByTurn.set(turn.turnId, step.name);\n return turn;\n }\n\n async steer(\n reference: CodexSessionReference,\n turnId: string,\n input: string,\n ): Promise<CodexTurnReference> {\n this.requireCurrent(reference);\n const result = requiredRecord(\n await this.transport.request(\"turn/steer\", {\n threadId: reference.threadId,\n expectedTurnId: turnId,\n input: [{ type: \"text\", text: input, text_elements: [] }],\n }),\n \"turn/steer response\",\n );\n if (requiredString(result, \"turnId\", \"turn/steer response\") !== turnId) {\n throw new CodexDispatchError(\"turn/steer returned a different turn id\");\n }\n return { threadId: reference.threadId, turnId, status: \"in_progress\" };\n }\n\n async interrupt(reference: CodexSessionReference, turnId: string): Promise<void> {\n this.requireCurrent(reference);\n await this.transport.request(\"turn/interrupt\", { threadId: reference.threadId, turnId });\n }\n\n async fork(\n reference: CodexSessionReference,\n lastTurnId?: string,\n ): Promise<CodexSessionReference> {\n validateReference(reference);\n this.ensureConnected();\n this.requireNoActiveTurns(\"fork\");\n const result = requiredRecord(\n await this.transport.request(\"thread/fork\", {\n threadId: reference.threadId,\n ...(lastTurnId === undefined ? {} : { lastTurnId }),\n model: this.model,\n cwd: this.options.cwd,\n approvalPolicy: \"never\",\n sandbox: \"read-only\",\n config: buildIsolationConfig(this.prepared),\n ephemeral: false,\n runtimeWorkspaceRoots: [],\n }),\n \"thread/fork response\",\n );\n const forked = sessionReference(requiredRecord(result[\"thread\"], \"thread/fork thread\"));\n if (forked.threadId === reference.threadId || forked.forkedFromThreadId !== reference.threadId) {\n throw new CodexDispatchError(\"thread/fork returned an invalid lineage\");\n }\n this.emit({ t: \"session_forked\", session: forked });\n return forked;\n }\n\n waitForTurn(turn: CodexTurnReference, timeoutMs = this.options.timeoutMs ?? 120_000): Promise<CodexTurnReference> {\n if (turn.status !== \"in_progress\") return Promise.resolve(turn);\n if (this.disconnected || !this.activeTurns.has(turn.turnId)) {\n return Promise.reject(new CodexDispatchError(\"turn is no longer active; resume required\"));\n }\n return new Promise((resolveWaiter, rejectWaiter) => {\n const timer = setTimeout(() => {\n this.removeWaiter(turn.turnId, waiter);\n const error = new CodexDispatchError(`turn '${turn.turnId}' timed out`);\n void (async () => {\n try {\n await this.interrupt(\n { version: SESSION_REFERENCE_VERSION, target: \"codex:local\", threadId: turn.threadId, forkedFromThreadId: null },\n turn.turnId,\n );\n } catch {\n // The transport is closed below even when best-effort interrupt fails.\n }\n this.onDisconnect(error, \"turn_timeout\");\n await this.transport.close();\n rejectWaiter(error);\n })();\n }, timeoutMs);\n const waiter: TurnWaiter = { resolve: resolveWaiter, reject: rejectWaiter, timer };\n const list = this.waiters.get(turn.turnId) ?? [];\n list.push(waiter);\n this.waiters.set(turn.turnId, list);\n });\n }\n\n async restartAndResume(reference: CodexSessionReference): Promise<CodexSessionReference> {\n if (!this.disconnected && this.activeTurns.size > 0) {\n throw new CodexDispatchError(\"cannot restart while a turn is active; interrupt it first\");\n }\n await this.transport.close();\n const transport = await CodexAppServerTransport.start(\n this.prepared,\n this.options,\n (method, params) => this.onNotification(method, params),\n (error) => this.onDisconnect(error),\n );\n this.transport = transport;\n this.disconnected = false;\n try {\n return await this.resume(reference);\n } catch (error) {\n this.disconnected = true;\n await this.transport.close();\n throw error;\n }\n }\n\n async close(): Promise<void> {\n this.disconnected = true;\n const error = new CodexDispatchError(\"session runtime closed during an active turn\");\n for (const [turnId] of this.activeTurns) {\n this.settleWaiters(\n { threadId: this.session?.threadId ?? \"unknown\", turnId, status: \"failed\" },\n error,\n );\n }\n this.activeTurns.clear();\n this.stepNameByTurn.clear();\n await this.transport.close();\n }\n\n private onNotification(method: string, paramsValue: unknown): void {\n const params = requiredRecord(paramsValue, `${method} notification`);\n if (method === \"thread/started\" || IGNORED_NOTIFICATIONS.has(method)) return;\n if (method === \"error\") {\n const threadId = requiredString(params, \"threadId\", method);\n this.requireNotificationThread(threadId);\n const turnId = requiredString(params, \"turnId\", method);\n requiredRecord(params[\"error\"], \"error notification error\");\n const active = this.activeTurns.get(turnId);\n if (!active?.started) {\n throw new CodexDispatchError(\"app-server error notification has no active turn\");\n }\n if (params[\"willRetry\"] === true) return;\n if (params[\"willRetry\"] !== false) {\n throw new CodexDispatchError(\"app-server error notification requires willRetry\");\n }\n throw new CodexDispatchError(\"app-server reported a terminal turn error\");\n }\n if (method === \"turn/started\") {\n const threadId = requiredString(params, \"threadId\", method);\n this.requireNotificationThread(threadId);\n const turn = turnReference(threadId, requiredRecord(params[\"turn\"], `${method} turn`));\n const active = this.ensureActiveTurn(turn.turnId);\n if (active.started) throw new CodexDispatchError(\"duplicate turn start notification\");\n active.started = true;\n this.emit({ t: \"turn_started\", turn });\n const stepName = this.stepNameByTurn.get(turn.turnId) ?? this.prepared.steps[0]!.name;\n this.emit({ threadId, turnId: turn.turnId, t: \"step_start\", id: stepName, name: stepName });\n return;\n }\n if (method === \"item/started\" || method === \"item/completed\") {\n this.onItem(method, params);\n return;\n }\n if (method === \"turn/completed\") {\n this.onTurnCompleted(params);\n return;\n }\n throw new CodexDispatchError(`unsupported app-server notification '${method}'`);\n }\n\n private onItem(method: \"item/started\" | \"item/completed\", params: JsonRecord): void {\n const threadId = requiredString(params, \"threadId\", method);\n this.requireNotificationThread(threadId);\n const turnId = requiredString(params, \"turnId\", method);\n const item = requiredRecord(params[\"item\"], `${method} item`);\n const type = requiredString(item, \"type\", `${method} item`);\n if (FORBIDDEN_ITEM_TYPES.has(type)) {\n throw new CodexDispatchError(`isolation violation: app-server emitted forbidden '${type}'`);\n }\n const active = this.ensureActiveTurn(turnId);\n if (!active.started) throw new CodexDispatchError(\"item emitted before turn started\");\n if (type === \"mcpToolCall\") {\n const itemId = requiredString(item, \"id\", type);\n const server = requiredString(item, \"server\", type);\n const tool = requiredString(item, \"tool\", type);\n if (server !== this.prepared.mcp.name || !this.prepared.enabledTools.includes(tool)) {\n throw new CodexDispatchError(`isolation violation: non-allowlisted MCP tool '${server}.${tool}'`);\n }\n if (method === \"item/started\") {\n if (item[\"status\"] !== \"inProgress\") {\n throw new CodexDispatchError(\"MCP item start requires in-progress status\");\n }\n if (active.pendingTools.has(itemId)) throw new CodexDispatchError(\"duplicate MCP item start\");\n active.pendingTools.add(itemId);\n this.emit({ threadId, turnId, t: \"tool_call\", id: itemId, name: `${server}.${tool}` });\n return;\n }\n if (!active.pendingTools.delete(itemId)) throw new CodexDispatchError(\"MCP item completed without start\");\n const status = requiredString(item, \"status\", type);\n if (status !== \"completed\" && status !== \"failed\") {\n throw new CodexDispatchError(\"MCP item completed with an invalid status\");\n }\n const ok = status === \"completed\" && (item[\"error\"] === null || item[\"error\"] === undefined);\n if (ok) active.successfulTools += 1;\n const reference: CodexArtifactReference = {\n version: SESSION_REFERENCE_VERSION,\n kind: \"mcp_tool_result\",\n threadId,\n turnId,\n itemId,\n server,\n tool,\n ok,\n };\n this.emit({ t: \"artifact\", reference });\n this.emit({ threadId, turnId, t: \"tool_result\", id: itemId, ok, ...(ok ? {} : { error: \"allowlisted MCP tool failed\" }) });\n return;\n }\n if (!PASSIVE_ITEM_TYPES.has(type)) {\n throw new CodexDispatchError(`unsupported app-server item type '${type}'`);\n }\n if (method === \"item/completed\" && type === \"agentMessage\") {\n const text = requiredString(item, \"text\", type);\n active.hasAnswer = true;\n this.emit({ threadId, turnId, t: \"answer\", text });\n }\n }\n\n private onTurnCompleted(params: JsonRecord): void {\n const threadId = requiredString(params, \"threadId\", \"turn/completed\");\n this.requireNotificationThread(threadId);\n const turn = turnReference(threadId, requiredRecord(params[\"turn\"], \"turn/completed turn\"));\n const active = this.activeTurns.get(turn.turnId);\n if (!active) throw new CodexDispatchError(\"turn completed without starting\");\n if (!active.started) throw new CodexDispatchError(\"turn completed before start notification\");\n if (active.pendingTools.size > 0) throw new CodexDispatchError(\"turn completed with pending MCP tools\");\n if (turn.status === \"completed\" && (active.successfulTools === 0 || !active.hasAnswer)) {\n throw new CodexDispatchError(\"completed turn lacks a successful allowlisted tool or answer\");\n }\n this.activeTurns.delete(turn.turnId);\n const ok = turn.status === \"completed\";\n const stepName = this.stepNameByTurn.get(turn.turnId) ?? this.prepared.steps[0]!.name;\n this.stepNameByTurn.delete(turn.turnId);\n this.emit({ threadId, turnId: turn.turnId, t: \"step_finish\", id: stepName, ok });\n this.emit({ t: \"turn_completed\", turn });\n const error = turn.status === \"failed\" ? new CodexDispatchError(`turn '${turn.turnId}' failed`) : null;\n this.settleWaiters(turn, error);\n }\n\n private projectHistoryTurn(threadId: string, value: unknown): CodexHistoryTurn {\n const turn = requiredRecord(value, \"history turn\");\n const reference = turnReference(threadId, turn);\n const items: CodexHistoryItem[] = [];\n if (Array.isArray(turn[\"items\"])) {\n for (const itemValue of turn[\"items\"]) {\n const item = requiredRecord(itemValue, \"history item\");\n const type = requiredString(item, \"type\", \"history item\");\n if (type === \"agentMessage\") {\n items.push({ type: \"assistant\", itemId: requiredString(item, \"id\", type) });\n } else if (type === \"userMessage\") {\n items.push({ type: \"user\", itemId: requiredString(item, \"id\", type) });\n } else if (type === \"mcpToolCall\") {\n const server = requiredString(item, \"server\", type);\n const tool = requiredString(item, \"tool\", type);\n if (server !== this.prepared.mcp.name || !this.prepared.enabledTools.includes(tool)) {\n throw new CodexDispatchError(\"history contains a non-allowlisted MCP tool\");\n }\n const status = requiredString(item, \"status\", type);\n if (status !== \"completed\" && status !== \"failed\") {\n throw new CodexDispatchError(\"history MCP item has an invalid status\");\n }\n items.push({\n type: \"artifact\",\n reference: {\n version: SESSION_REFERENCE_VERSION,\n kind: \"mcp_tool_result\",\n threadId,\n turnId: reference.turnId,\n itemId: requiredString(item, \"id\", type),\n server,\n tool,\n ok: status === \"completed\" && (item[\"error\"] === null || item[\"error\"] === undefined),\n },\n });\n } else if (FORBIDDEN_ITEM_TYPES.has(type)) {\n throw new CodexDispatchError(`history contains forbidden '${type}' item`);\n } else if (!PASSIVE_ITEM_TYPES.has(type)) {\n throw new CodexDispatchError(`history contains unsupported '${type}' item`);\n }\n }\n }\n return { id: reference.turnId, status: reference.status, items };\n }\n\n private ensureActiveTurn(turnId: string): ActiveTurn {\n let active = this.activeTurns.get(turnId);\n if (!active) {\n active = { started: false, pendingTools: new Set(), successfulTools: 0, hasAnswer: false };\n this.activeTurns.set(turnId, active);\n }\n return active;\n }\n\n private requireCurrent(reference: CodexSessionReference): void {\n validateReference(reference);\n this.ensureConnected();\n if (this.session?.threadId !== reference.threadId) {\n throw new CodexDispatchError(\"session reference is not loaded; resume it first\");\n }\n }\n\n private requireNotificationThread(threadId: string): void {\n if (this.session?.threadId !== threadId) {\n throw new CodexDispatchError(\"app-server notification belongs to a different thread\");\n }\n }\n\n private requireNoActiveTurns(operation: string): void {\n if (this.activeTurns.size > 0) {\n throw new CodexDispatchError(\n `cannot ${operation} while a turn is active; interrupt it first`,\n );\n }\n }\n\n private ensureConnected(): void {\n if (this.disconnected) throw new CodexDispatchError(\"app-server transport disconnected; resume required\");\n }\n\n private onDisconnect(\n protocolError?: CodexDispatchError,\n reasonOverride?: \"turn_timeout\",\n ): void {\n if (this.disconnected) return;\n this.disconnected = true;\n if (protocolError && reasonOverride === undefined) {\n this.emit({\n t: \"session_failed\",\n threadId: this.session?.threadId ?? null,\n reason: \"protocol_violation\",\n });\n } else {\n const reason = reasonOverride ?? (this.activeTurns.size > 0 ? \"app_server_crash\" : \"transport_disconnect\");\n this.emit({ t: \"session_recoverable\", threadId: this.session?.threadId ?? null, reason });\n }\n for (const [turnId] of this.activeTurns) {\n this.settleWaiters(\n { threadId: this.session?.threadId ?? \"unknown\", turnId, status: \"failed\" },\n protocolError ?? new CodexDispatchError(\"app-server disconnected during an active turn\"),\n );\n }\n this.activeTurns.clear();\n this.stepNameByTurn.clear();\n }\n\n private settleWaiters(turn: CodexTurnReference, error: Error | null): void {\n const waiters = this.waiters.get(turn.turnId) ?? [];\n this.waiters.delete(turn.turnId);\n for (const waiter of waiters) {\n clearTimeout(waiter.timer);\n if (error) waiter.reject(error);\n else waiter.resolve(turn);\n }\n }\n\n private removeWaiter(turnId: string, waiter: TurnWaiter): void {\n const remaining = (this.waiters.get(turnId) ?? []).filter((candidate) => candidate !== waiter);\n if (remaining.length === 0) this.waiters.delete(turnId);\n else this.waiters.set(turnId, remaining);\n }\n\n private emit(event: CodexSessionEvent): void {\n this.options.onEvent?.(event);\n }\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport type { PreparedEnrichComponent } from \"./enrich_prepare.js\";\nimport { CodexSessionRuntime } from \"./session.js\";\nimport type { CodexSessionEvent, SessionIsolationOptions } from \"./session_types.js\";\nimport { parseStepTerminal, shouldRunStep, type StepOutcome } from \"./step_engine.js\";\n\n/** One step's dispatch-time evidence: whether it ran (an on_failure guard may skip it) and, if it\n * ran, whether its terminal matched its declared `produces` slot. Mirrors `run.ts`'s\n * `SetupStepRunOutcome` — kept as a separate type (not imported from `run.ts`) so Setup and Enrich\n * stay two independent engines, by design. */\nexport interface EnrichStepRunOutcome {\n name: string;\n ran: boolean;\n ok: boolean;\n value?: unknown;\n}\n\nexport interface EnrichRunResult {\n target: \"codex:local\";\n component: string;\n /** The last step that actually ran's raw terminal text — unchanged for every existing\n * single-step component, since there the last step run is the only step run. */\n finalText: string;\n /** The parsed terminal object of the last step that actually ran. */\n value: unknown;\n events: CodexSessionEvent[];\n steps: EnrichStepRunOutcome[];\n}\n\n/**\n * Execute a read-only enrichment component's steps, in order, through one persistent Codex\n * app-server session. The Codex thread is created before the first model turn begins; this\n * preserves durable session history before any metered work can occur, while the host remains\n * owner of enrichment run bookkeeping. Every step of one dispatch shares the same thread — see\n * `session.ts`'s `CodexSessionRuntime.turn`, which now takes the current step and its marshalled\n * `consumes` inputs — with produces/consumes marshalled between turns exactly as `run.ts`'s\n * `runSetup` marshals them between one-shot processes, and the same recoverable-vs-fatal\n * on_failure evaluation (`shouldRunStep`/`parseStepTerminal`).\n */\nexport async function runEnrich(\n prepared: PreparedEnrichComponent,\n request: string,\n options: SessionIsolationOptions,\n): Promise<EnrichRunResult> {\n if (request.trim().length === 0) throw new CodexDispatchError(\"enrichment request must not be empty\");\n const events: CodexSessionEvent[] = [];\n // `CodexSessionRuntime` fans every event for the whole session's lifetime out through one\n // `onEvent` callback fixed at `connect()` time — there is no per-turn subscription. So each\n // step's answer is captured into this one mutable slot, reset immediately before that step's\n // turn starts, and read immediately after that turn completes; the loop below never has two\n // turns in flight at once, so there is no risk of one step reading another's answer.\n let currentAnswer: string | null = null;\n const onEvent = (event: CodexSessionEvent): void => {\n events.push(event);\n if (event.t === \"answer\") currentAnswer = event.text;\n options.onEvent?.(event);\n };\n const runtime = await CodexSessionRuntime.connect(prepared, { ...options, onEvent });\n try {\n const session = await runtime.start();\n const slots: Record<string, unknown> = {};\n const outcomes = new Map<string, StepOutcome>();\n const steps: EnrichStepRunOutcome[] = [];\n let lastFinalText: string | null = null;\n let lastValue: unknown;\n\n for (const step of prepared.steps) {\n if (!shouldRunStep(step.when, outcomes)) {\n outcomes.set(step.name, { ran: false });\n steps.push({ name: step.name, ran: false, ok: false });\n continue;\n }\n const inputs = Object.fromEntries(step.consumes.map((name) => [name, slots[name]]));\n currentAnswer = null;\n const turn = await runtime.turn(session, request, step, inputs);\n const completed = await runtime.waitForTurn(turn, options.timeoutMs ?? 120_000);\n if (completed.status !== \"completed\" || currentAnswer === null) {\n throw new CodexDispatchError(`enrichment step '${step.name}' did not complete with a terminal answer`);\n }\n const finalText: string = currentAnswer;\n // Same recoverable-vs-fatal rule as `run.ts`'s `runSetup`: a step's produces-mismatch is\n // only survivable when some later step's on_failure guard actually names it; otherwise it\n // fails the whole dispatch exactly as the original single-turn transport always did.\n const hasGuardedConsumer = prepared.steps.some((candidate) => candidate.when?.target === step.name);\n let record: Record<string, unknown>;\n try {\n record = parseStepTerminal(finalText, step.produces);\n } catch (error) {\n if (hasGuardedConsumer && error instanceof CodexDispatchError) {\n outcomes.set(step.name, { ran: true, ok: false });\n steps.push({ name: step.name, ran: true, ok: false });\n lastFinalText = finalText;\n continue;\n }\n throw error;\n }\n const value = record[step.produces];\n slots[step.produces] = value;\n outcomes.set(step.name, { ran: true, ok: true, value });\n steps.push({ name: step.name, ran: true, ok: true, value });\n lastFinalText = finalText;\n lastValue = record;\n }\n\n if (lastFinalText === null) {\n // Unreachable for any component `validateStepTopology` accepts — see `run.ts`'s identical\n // backstop for why: the only conditional step allowed is the last one, targeting a strictly\n // earlier step, so a component can only be conditional-only when it has zero steps, which\n // `prepareEnrich` already rejects.\n throw new CodexDispatchError(\"enrichment dispatch completed without running any step\");\n }\n return {\n target: prepared.target,\n component: prepared.componentId,\n finalText: lastFinalText,\n value: lastValue,\n events,\n steps,\n };\n } finally {\n await runtime.close();\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\n\nimport { buildCodexArgs, buildPrompt, sanitizeCodexEnvironment } from \"./config.js\";\nimport { CodexDispatchError } from \"./error.js\";\nimport { CodexJsonlMapper, type WarbleCodexEvent } from \"./events.js\";\nimport type { PreparedSetupComponent, PreparedSetupStep } from \"./prepare.js\";\nimport { parseStepTerminal, shouldRunStep, type StepOutcome } from \"./step_engine.js\";\n\nexport interface RunOptions {\n cwd: string;\n request: string;\n codexBin?: string;\n codexArgsPrefix?: string[];\n timeoutMs?: number;\n terminationGraceMs?: number;\n signal?: AbortSignal;\n env?: NodeJS.ProcessEnv;\n onEvent?: (event: WarbleCodexEvent) => void;\n}\n\n/** One step's dispatch-time evidence: whether it ran (an on_failure guard may skip it) and, if\n * it ran, whether its terminal matched its declared `produces` slot. */\nexport interface SetupStepRunOutcome {\n name: string;\n ran: boolean;\n ok: boolean;\n value?: unknown;\n}\n\nexport interface RunResult {\n target: \"codex:local\";\n component: string;\n /** The last step that actually ran's raw terminal text — unchanged for every existing\n * single-step component, since there the last step run is the only step run. */\n finalText: string;\n events: WarbleCodexEvent[];\n steps: SetupStepRunOutcome[];\n}\n\n/** Spawns exactly one Codex process for exactly one step, mirroring the transport's original\n * one-shot design per step rather than per dispatch — Setup has no persistent session to reuse\n * across steps, so each step gets its own child process. */\nasync function runOneStep(\n prepared: PreparedSetupComponent,\n step: PreparedSetupStep,\n inputs: Record<string, unknown>,\n options: RunOptions,\n events: WarbleCodexEvent[],\n): Promise<string> {\n const mapper = new CodexJsonlMapper(step.name, prepared.mcp.name, prepared.enabledTools);\n const args = buildCodexArgs(prepared, step, {\n cwd: options.cwd,\n ...(options.codexArgsPrefix ? { codexArgsPrefix: options.codexArgsPrefix } : {}),\n });\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn(options.codexBin ?? \"codex\", args, {\n cwd: options.cwd,\n env: sanitizeCodexEnvironment(options.env),\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n } catch (error) {\n throw new CodexDispatchError(`failed to start codex: ${String(error)}`);\n }\n if (child.stdin === null || child.stdout === null || child.stderr === null) {\n child.kill(\"SIGTERM\");\n throw new CodexDispatchError(\"failed to start codex with piped stdio\");\n }\n const childStdin = child.stdin;\n const childStdout = child.stdout;\n const childStderr = child.stderr;\n const exitPromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(\n (resolve, reject) => {\n child.once(\"error\", (error) =>\n reject(new CodexDispatchError(`failed to start codex: ${error.message}`)),\n );\n child.once(\"close\", (code, signal) => resolve({ code, signal }));\n },\n );\n childStderr.resume();\n\n let terminalError: Error | null = null;\n let terminationRequested = false;\n let killTimer: ReturnType<typeof setTimeout> | undefined;\n const terminationGraceMs = options.terminationGraceMs ?? 1_000;\n const signalProcessTree = (signal: NodeJS.Signals) => {\n if (child.pid === undefined) return;\n if (process.platform !== \"win32\") {\n try {\n process.kill(-child.pid, signal);\n return;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ESRCH\") return;\n }\n }\n child.kill(signal);\n };\n const terminateProcessTree = () => {\n if (terminationRequested) return;\n terminationRequested = true;\n signalProcessTree(\"SIGTERM\");\n killTimer = setTimeout(() => signalProcessTree(\"SIGKILL\"), terminationGraceMs);\n };\n const lines = createInterface({ input: childStdout });\n lines.on(\"line\", (line) => {\n if (line.trim().length === 0 || terminalError) return;\n try {\n for (const event of mapper.nextLine(line)) {\n events.push(event);\n options.onEvent?.(event);\n }\n } catch (error) {\n terminalError = error instanceof Error ? error : new Error(String(error));\n terminateProcessTree();\n }\n });\n\n const prompt = buildPrompt(prepared, step, options.request, inputs, { producedValue: \"string\" });\n childStdin.end(prompt);\n\n let aborted = false;\n const abort = () => {\n aborted = true;\n terminateProcessTree();\n };\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n const timeoutMs = options.timeoutMs ?? 120_000;\n const timer = setTimeout(abort, timeoutMs);\n\n const exit = await exitPromise.finally(() => {\n clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", abort);\n lines.close();\n if (terminationRequested) signalProcessTree(\"SIGKILL\");\n if (killTimer !== undefined) clearTimeout(killTimer);\n });\n\n if (terminalError) throw terminalError;\n if (aborted) {\n const reason = options.signal?.aborted ? \"cancelled\" : `timed out after ${timeoutMs}ms`;\n throw new CodexDispatchError(`codex dispatch ${reason}`);\n }\n if (exit.code !== 0) {\n throw new CodexDispatchError(\n `codex exited with ${exit.code ?? exit.signal ?? \"unknown\"}`,\n );\n }\n return mapper.result().finalText;\n}\n\nexport async function runSetup(\n prepared: PreparedSetupComponent,\n options: RunOptions,\n): Promise<RunResult> {\n if (options.signal?.aborted) {\n throw new CodexDispatchError(\"codex dispatch cancelled before start\");\n }\n const events: WarbleCodexEvent[] = [];\n const slots: Record<string, unknown> = {};\n const outcomes = new Map<string, StepOutcome>();\n const steps: SetupStepRunOutcome[] = [];\n let lastFinalText: string | null = null;\n\n for (const step of prepared.steps) {\n if (!shouldRunStep(step.when, outcomes)) {\n outcomes.set(step.name, { ran: false });\n steps.push({ name: step.name, ran: false, ok: false });\n continue;\n }\n const inputs = Object.fromEntries(step.consumes.map((name) => [name, slots[name]]));\n const finalText = await runOneStep(prepared, step, inputs, options, events);\n // Whether a step's produces-mismatch is fatal or recoverable depends on whether any later\n // step in this component actually guards on it — the accept-set-equals-execute-set invariant\n // applied the other way round: a step that no on_failure guard ever names must fail the whole\n // dispatch exactly as it always has, since nothing downstream is prepared to observe it fail.\n const hasGuardedConsumer = prepared.steps.some((candidate) => candidate.when?.target === step.name);\n let record: Record<string, unknown>;\n try {\n record = parseStepTerminal(finalText, step.produces);\n } catch (error) {\n if (hasGuardedConsumer && error instanceof CodexDispatchError) {\n outcomes.set(step.name, { ran: true, ok: false });\n steps.push({ name: step.name, ran: true, ok: false });\n lastFinalText = finalText;\n continue;\n }\n throw error;\n }\n const value = record[step.produces];\n slots[step.produces] = value;\n outcomes.set(step.name, { ran: true, ok: true, value });\n steps.push({ name: step.name, ran: true, ok: true, value });\n lastFinalText = finalText;\n }\n\n if (lastFinalText === null) {\n // Unreachable for any component `validateStepTopology` accepts: the only conditional step\n // allowed is the last one, and it must target a strictly earlier step, so a component can\n // only be conditional-only when it has zero steps, which prepare already rejects. Kept as a\n // defensive backstop, not a reachable branch.\n throw new CodexDispatchError(\"codex dispatch completed without running any step\");\n }\n return {\n target: prepared.target,\n component: prepared.componentId,\n finalText: lastFinalText,\n events,\n steps,\n };\n}\n","import { CodexDispatchError } from \"./error.js\";\n\nexport type WarbleCodexEvent =\n | { t: \"step_start\"; id: string; name: string }\n | { t: \"tool_call\"; id: string; name: string }\n | { t: \"tool_result\"; id: string; ok: boolean; error?: string }\n | { t: \"answer\"; text: string }\n | { t: \"step_finish\"; id: string; ok: boolean; detail?: string };\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction itemOf(event: JsonRecord): JsonRecord | null {\n return isRecord(event[\"item\"]) ? event[\"item\"] : null;\n}\n\nfunction itemType(item: JsonRecord): string {\n return typeof item[\"type\"] === \"string\" ? item[\"type\"] : \"\";\n}\n\nfunction toolIdentity(item: JsonRecord): { server: string; tool: string; name: string } {\n const server = typeof item[\"server\"] === \"string\" ? item[\"server\"] : \"\";\n const tool = typeof item[\"tool\"] === \"string\" ? item[\"tool\"] : \"\";\n if (server.length === 0 || tool.length === 0) {\n throw new CodexDispatchError(\"mcp_tool_call requires string server and tool fields\");\n }\n return { server, tool, name: `${server}.${tool}` };\n}\n\nconst FORBIDDEN_ITEM_TYPES = new Set([\n \"command_execution\",\n \"file_change\",\n \"web_search\",\n \"image_generation\",\n \"collab_agent_tool_call\",\n]);\n\nexport class CodexJsonlMapper {\n private started = false;\n private finished = false;\n private threadStarted = false;\n private finalText: string | null = null;\n private failureDetail: string | null = null;\n private toolFailureDetail: string | null = null;\n private readonly pendingTools = new Map<string, string>();\n private successfulToolCount = 0;\n private readonly enabledTools: ReadonlySet<string>;\n\n constructor(\n private readonly stepId: string,\n private readonly expectedMcpServer: string,\n enabledTools: readonly string[],\n ) {\n this.enabledTools = new Set(enabledTools);\n }\n\n nextLine(line: string): WarbleCodexEvent[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch (error) {\n throw new CodexDispatchError(`codex stdout contained non-JSONL data: ${String(error)}`);\n }\n if (!isRecord(parsed) || typeof parsed[\"type\"] !== \"string\") {\n throw new CodexDispatchError(\"codex JSONL event requires a string type\");\n }\n const type = parsed[\"type\"];\n if (this.finished) {\n throw new CodexDispatchError(`codex emitted '${type}' after the terminal turn event`);\n }\n if (type === \"thread.started\") {\n if (this.threadStarted || this.started) {\n throw new CodexDispatchError(\"codex emitted duplicate or out-of-order thread.started\");\n }\n this.threadStarted = true;\n return [];\n }\n if (type === \"turn.started\") {\n if (!this.threadStarted) {\n throw new CodexDispatchError(\"codex emitted turn.started before thread.started\");\n }\n if (this.started) throw new CodexDispatchError(\"codex emitted duplicate turn.started\");\n this.started = true;\n return [{ t: \"step_start\", id: this.stepId, name: this.stepId }];\n }\n if (type === \"item.started\" || type === \"item.completed\") {\n if (!this.started) {\n throw new CodexDispatchError(`codex emitted ${type} before turn.started`);\n }\n return this.onItem(type, parsed);\n }\n if (type === \"turn.failed\" || type === \"error\") {\n return this.finish(false, type === \"turn.failed\" ? \"codex turn failed\" : \"codex runtime error\");\n }\n if (type === \"turn.completed\") {\n return this.finish(true);\n }\n return [];\n }\n\n result(): { finalText: string; threadStarted: boolean; turnCompleted: boolean } {\n if (!this.threadStarted) throw new CodexDispatchError(\"codex JSONL ended without thread.started\");\n if (!this.finished) throw new CodexDispatchError(\"codex JSONL ended without turn.completed\");\n if (this.failureDetail !== null) {\n throw new CodexDispatchError(`codex turn failed: ${this.failureDetail}`);\n }\n if (this.successfulToolCount === 0) {\n if (this.toolFailureDetail !== null) {\n throw new CodexDispatchError(`required MCP tool failed: ${this.toolFailureDetail}`);\n }\n throw new CodexDispatchError(\"codex turn completed without a successful allowlisted MCP tool call\");\n }\n if (this.finalText === null) throw new CodexDispatchError(\"codex JSONL ended without an agent message\");\n return {\n finalText: this.finalText,\n threadStarted: this.threadStarted,\n turnCompleted: this.finished,\n };\n }\n\n private onItem(\n eventType: \"item.started\" | \"item.completed\",\n event: JsonRecord,\n ): WarbleCodexEvent[] {\n const item = itemOf(event);\n if (!item) throw new CodexDispatchError(`${eventType} requires an item object`);\n const type = itemType(item);\n if (FORBIDDEN_ITEM_TYPES.has(type)) {\n throw new CodexDispatchError(\n `isolation violation: codex emitted forbidden '${type}' item`,\n );\n }\n if (type === \"mcp_tool_call\") {\n const id = typeof item[\"id\"] === \"string\" ? item[\"id\"] : \"\";\n if (id.length === 0) throw new CodexDispatchError(\"mcp_tool_call requires an id\");\n const identity = toolIdentity(item);\n if (\n identity.server !== this.expectedMcpServer ||\n !this.enabledTools.has(identity.tool)\n ) {\n throw new CodexDispatchError(\n `isolation violation: codex emitted non-allowlisted MCP tool '${identity.name}'`,\n );\n }\n if (eventType === \"item.started\") {\n if (this.pendingTools.has(id)) {\n throw new CodexDispatchError(`mcp_tool_call '${id}' started more than once`);\n }\n this.pendingTools.set(id, identity.name);\n return [\n {\n t: \"tool_call\",\n id,\n name: identity.name,\n },\n ];\n }\n const name = this.pendingTools.get(id);\n if (name === undefined) {\n throw new CodexDispatchError(`mcp_tool_call '${id}' completed without starting`);\n }\n if (name !== identity.name) {\n throw new CodexDispatchError(\n `mcp_tool_call '${id}' completed as '${identity.name}' after starting as '${name}'`,\n );\n }\n this.pendingTools.delete(id);\n const status = item[\"status\"];\n if (status !== \"completed\" && status !== \"failed\") {\n throw new CodexDispatchError(\n `completed mcp_tool_call '${id}' requires completed or failed status`,\n );\n }\n const failed =\n status === \"failed\" || (item[\"error\"] !== undefined && item[\"error\"] !== null);\n if (failed) this.toolFailureDetail = name;\n else this.successfulToolCount += 1;\n return [\n {\n t: \"tool_result\",\n id,\n ok: !failed,\n ...(failed ? { error: \"allowlisted MCP tool failed\" } : {}),\n },\n ];\n }\n if (eventType === \"item.completed\" && type === \"agent_message\") {\n const text = item[\"text\"];\n if (typeof text !== \"string\") {\n throw new CodexDispatchError(\"completed agent_message requires text\");\n }\n this.finalText = text;\n return [{ t: \"answer\", text }];\n }\n return [];\n }\n\n private finish(ok: boolean, detail?: string): WarbleCodexEvent[] {\n if (!this.started) {\n throw new CodexDispatchError(\"codex turn finished before turn.started\");\n }\n if (this.finished) throw new CodexDispatchError(\"codex emitted duplicate terminal turn event\");\n if (this.pendingTools.size > 0) {\n throw new CodexDispatchError(\n `codex turn finished with pending MCP tool calls: ${[...this.pendingTools.keys()].join(\", \")}`,\n );\n }\n if (ok && this.successfulToolCount === 0) {\n if (this.toolFailureDetail !== null) {\n throw new CodexDispatchError(`required MCP tool failed: ${this.toolFailureDetail}`);\n }\n throw new CodexDispatchError(\"codex turn completed without a successful allowlisted MCP tool call\");\n }\n if (ok && this.finalText === null) {\n throw new CodexDispatchError(\"codex JSONL ended without an agent message\");\n }\n this.finished = true;\n if (!ok) this.failureDetail = detail ?? \"unknown failure\";\n return [\n {\n t: \"step_finish\",\n id: this.stepId,\n ok,\n ...(detail !== undefined ? { detail } : {}),\n },\n ];\n }\n}\n"],"mappings":";;;AACA,SAAS,cAAc,iBAAAA,sBAAqB;AAC5C,S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AAiB,QAAQ,MAAM,SAAS,MAAM,UAAU,OAAO,KAAK,CAAC;AAC5E,CAAC;","names":["writeFileSync","resolve","isRecord","itemType","isAbsolute","isRecord","isAbsolute","existsSync","join","existsSync","join","isRecord","text","resolve","spawn","request","isAbsolute","text","record","unique","isAbsolute","isAbsolute","unique","isAbsolute","resolve","isRecord","record","resolve","IGNORED_NOTIFICATIONS","isRecord","record","sessionReference","turnStatus","turnReference","validateReference","text","record","spawn","createInterface","isRecord","FORBIDDEN_ITEM_TYPES","text","spawn","resolve","createInterface","record","resolve","mcp","prepared","text","writeFileSync","result"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/ask_prepare.ts","../src/error.ts","../src/dispatch_registry.ts","../src/ir.ts","../src/render_contract.ts","../src/request_transport.ts","../src/target_profile.ts","../src/app_server_transport.ts","../src/config.ts","../src/ask_config.ts","../src/session_types.ts","../src/ask_runtime.ts","../src/enrich_prepare.ts","../src/step_engine.ts","../src/prepare.ts","../src/dispatch_contract.ts","../src/manifest.ts","../src/model_catalog.ts","../src/session.ts","../src/enrich_run.ts","../src/run.ts","../src/events.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { parseArgs } from \"node:util\";\n\nimport { prepareAsk, type AskMcpServerConfig } from \"./ask_prepare.js\";\nimport { CodexAskRuntime } from \"./ask_runtime.js\";\nimport { classifyDispatchContract, supportsSetupAggregate } from \"./dispatch_contract.js\";\nimport { CodexDispatchError } from \"./error.js\";\nimport {\n buildAskManifest,\n buildEnrichManifest,\n buildManifest,\n describeAskTarget,\n describeEnrichTarget,\n describeTarget,\n} from \"./manifest.js\";\nimport { discoverCodexModels } from \"./model_catalog.js\";\nimport { prepareEnrich, type EnrichMcpServerConfig } from \"./enrich_prepare.js\";\nimport { parseIr } from \"./ir.js\";\nimport { prepareAllSetup, prepareSetup, type McpServerConfig } from \"./prepare.js\";\nimport { runEnrich } from \"./enrich_run.js\";\nimport { runSetup } from \"./run.js\";\n\nconst USAGE =\n \"usage: warble-codex-local <dispatch|manifest|describe> <ir.json> [request] \" +\n \"--component <id> --server-command <absolute-path> [options]\\n\" +\n \" warble-codex-local list-models [--project <dir>] [--codex-home <dir>] [--codex-bin <path>] [--timeout <ms>]\";\n\nfunction fail(message: string): never {\n process.stderr.write(`error: ${message}\\n`);\n process.exit(1);\n}\n\nfunction valuesList(value: string[] | string | undefined): string[] {\n if (value === undefined) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nasync function main(): Promise<void> {\n const { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n component: { type: \"string\" },\n model: { type: \"string\" },\n project: { type: \"string\" },\n out: { type: \"string\" },\n timeout: { type: \"string\" },\n \"codex-bin\": { type: \"string\" },\n server: { type: \"string\" },\n \"server-command\": { type: \"string\" },\n \"server-arg\": { type: \"string\", multiple: true },\n \"source-tool\": { type: \"string\", multiple: true },\n \"context-tool\": { type: \"string\", multiple: true },\n \"inspect-tool\": { type: \"string\", multiple: true },\n \"query-tool\": { type: \"string\", multiple: true },\n \"semantic-tool\": { type: \"string\", multiple: true },\n \"raw-material-tool\": { type: \"string\", multiple: true },\n \"orchestrator-model\": { type: \"string\" },\n \"cheap-model\": { type: \"string\" },\n \"strong-model\": { type: \"string\" },\n \"codex-home\": { type: \"string\" },\n \"stream-json\": { type: \"boolean\" },\n },\n });\n const [subcommand, irPathArg, request] = positionals;\n if (subcommand === \"list-models\") {\n if (irPathArg !== undefined || request !== undefined) fail(\"list-models does not take an <ir.json> or request\");\n const timeout = values.timeout === undefined ? undefined : Number(values.timeout);\n if (timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0)) fail(\"--timeout must be a positive number\");\n const catalog = await discoverCodexModels({\n ...(values.project ? { cwd: values.project } : {}),\n ...(values[\"codex-home\"] ? { codexHome: values[\"codex-home\"] } : {}),\n ...(values[\"codex-bin\"] ? { codexBin: values[\"codex-bin\"] } : {}),\n ...(timeout !== undefined ? { timeoutMs: timeout } : {}),\n });\n process.stdout.write(`${JSON.stringify(catalog)}\\n`);\n return;\n }\n if (![\"dispatch\", \"manifest\", \"describe\"].includes(subcommand ?? \"\")) fail(USAGE);\n if (!irPathArg) fail(\"missing <ir.json>\");\n if (!values[\"server-command\"]) fail(\"missing --server-command\");\n const raw = readFileSync(resolve(irPathArg), \"utf8\");\n const ir = parseIr(raw);\n const model = values.model ?? \"gpt-5.4\";\n\n if (!values.component && subcommand !== \"dispatch\" && supportsSetupAggregate(ir)) {\n const mcp: McpServerConfig = {\n name: values.server ?? \"setup\",\n command: resolve(values[\"server-command\"]),\n args: valuesList(values[\"server-arg\"]),\n toolsByCapability: {\n source_connect: valuesList(values[\"source-tool\"]),\n context_build: valuesList(values[\"context-tool\"]),\n },\n };\n const prepared = prepareAllSetup(raw, { model, mcp });\n const output = subcommand === \"manifest\" ? buildManifest(prepared) : describeTarget(prepared);\n const text = `${JSON.stringify(output, null, 2)}\\n`;\n if (values.out) writeFileSync(resolve(values.out), text);\n else process.stdout.write(text);\n return;\n }\n\n const component = values.component;\n if (!component) fail(`${subcommand} requires --component for the selected component execution contract`);\n const contract = classifyDispatchContract(ir, component);\n\n if (contract === \"enrich\") {\n const enrichMcp: EnrichMcpServerConfig = {\n name: values.server ?? \"enrich\",\n command: resolve(values[\"server-command\"]),\n args: valuesList(values[\"server-arg\"]),\n toolsByCapability: {\n semantic_introspection: valuesList(values[\"semantic-tool\"]),\n raw_material_read: valuesList(values[\"raw-material-tool\"]),\n },\n };\n const preparedEnrich = prepareEnrich({ ir: raw, component, model, mcp: enrichMcp });\n if (subcommand === \"manifest\" || subcommand === \"describe\") {\n const output =\n subcommand === \"manifest\"\n ? buildEnrichManifest(preparedEnrich)\n : describeEnrichTarget(preparedEnrich);\n const text = `${JSON.stringify(output, null, 2)}\\n`;\n if (values.out) writeFileSync(resolve(values.out), text);\n else process.stdout.write(text);\n return;\n }\n if (!request) fail(\"dispatch requires a request\");\n if (!values[\"codex-home\"]) fail(\"selected component requires --codex-home\");\n const result = await runEnrich(preparedEnrich, request, {\n codexHome: resolve(values[\"codex-home\"]),\n cwd: resolve(values.project ?? \".\"),\n externalAuthentication: \"provisioned\",\n ...(values[\"codex-bin\"] ? { codexBin: resolve(values[\"codex-bin\"]) } : {}),\n ...(values.timeout ? { timeoutMs: Number(values.timeout) } : {}),\n ...(values[\"stream-json\"]\n ? { onEvent: (event) => process.stdout.write(`${JSON.stringify(event)}\\n`) }\n : {}),\n });\n if (!values[\"stream-json\"]) process.stdout.write(`${result.finalText}\\n`);\n return;\n }\n\n if (contract === \"ask\") {\n for (const option of [\"orchestrator-model\", \"cheap-model\", \"strong-model\"] as const) {\n if (!values[option]) fail(`selected component requires --${option}`);\n }\n const askMcp: AskMcpServerConfig = {\n name: values.server ?? \"wren\",\n command: resolve(values[\"server-command\"]),\n args: valuesList(values[\"server-arg\"]),\n toolsByStep: {\n resolve_intent: valuesList(values[\"inspect-tool\"]),\n generate_sql: valuesList(values[\"query-tool\"]),\n repair_sql: valuesList(values[\"query-tool\"]),\n plan_dashboard: valuesList(values[\"inspect-tool\"]),\n compose_layout: valuesList(values[\"query-tool\"]),\n },\n };\n const preparedAsk = prepareAsk({\n ir: raw,\n component,\n models: {\n orchestrator: values[\"orchestrator-model\"]!,\n cheap: values[\"cheap-model\"]!,\n strong: values[\"strong-model\"]!,\n },\n mcp: askMcp,\n });\n if (subcommand === \"manifest\" || subcommand === \"describe\") {\n const output =\n subcommand === \"manifest\"\n ? buildAskManifest(preparedAsk)\n : describeAskTarget(preparedAsk);\n const text = `${JSON.stringify(output, null, 2)}\\n`;\n if (values.out) writeFileSync(resolve(values.out), text);\n else process.stdout.write(text);\n return;\n }\n if (!request) fail(\"dispatch requires a request\");\n if (!values[\"codex-home\"]) fail(\"selected component requires --codex-home\");\n const runtime = await CodexAskRuntime.connect(preparedAsk, {\n codexHome: resolve(values[\"codex-home\"]),\n cwd: resolve(values.project ?? \".\"),\n externalAuthentication: \"provisioned\",\n ...(values[\"codex-bin\"] ? { codexBin: resolve(values[\"codex-bin\"]) } : {}),\n ...(values.timeout ? { turnTimeoutMs: Number(values.timeout) } : {}),\n ...(values[\"stream-json\"]\n ? { onAskEvent: (event) => process.stdout.write(`${JSON.stringify(event)}\\n`) }\n : {}),\n });\n try {\n const session = await runtime.start();\n const result = await runtime.run(session, request);\n if (values[\"stream-json\"]) {\n process.stdout.write(`${JSON.stringify({ t: \"answer\", text: result.finalText })}\\n`);\n } else {\n process.stdout.write(`${result.finalText}\\n`);\n }\n } finally {\n await runtime.close();\n }\n return;\n }\n\n const mcp: McpServerConfig = {\n name: values.server ?? \"setup\",\n command: resolve(values[\"server-command\"]),\n args: valuesList(values[\"server-arg\"]),\n toolsByCapability: {\n source_connect: valuesList(values[\"source-tool\"]),\n context_build: valuesList(values[\"context-tool\"]),\n },\n };\n const prepared = prepareSetup({ ir: raw, component, model, mcp });\n if (subcommand === \"manifest\" || subcommand === \"describe\") {\n const output = subcommand === \"manifest\" ? buildManifest([prepared]) : describeTarget([prepared]);\n const text = `${JSON.stringify(output, null, 2)}\\n`;\n if (values.out) writeFileSync(resolve(values.out), text);\n else process.stdout.write(text);\n return;\n }\n\n if (!request) fail(\"dispatch requires a request\");\n const result = await runSetup(prepared, {\n cwd: resolve(values.project ?? \".\"),\n request,\n ...(values[\"codex-bin\"] ? { codexBin: resolve(values[\"codex-bin\"]) } : {}),\n ...(values.timeout ? { timeoutMs: Number(values.timeout) } : {}),\n ...(values[\"stream-json\"]\n ? {\n onEvent: (event) => process.stdout.write(`${JSON.stringify(event)}\\n`),\n }\n : {}),\n });\n if (!values[\"stream-json\"]) process.stdout.write(`${result.finalText}\\n`);\n}\n\nmain().catch((error: unknown) => {\n if (error instanceof CodexDispatchError) fail(error.message);\n fail(error instanceof Error ? error.stack ?? error.message : String(error));\n});\n","import { isAbsolute } from \"node:path\";\n\nimport { CodexDispatchError } from \"./error.js\";\nimport { assertDispatchableComponentIdentity } from \"./dispatch_registry.js\";\nimport {\n parseIr,\n SUPPORTED_IR_VERSION,\n TARGET,\n type ComponentNode,\n type LlmCall,\n type WarbleIr,\n} from \"./ir.js\";\nimport type { CapabilityResolution } from \"./prepare.js\";\nimport { parseDashboardRenderBlockContracts } from \"./render_contract.js\";\nimport { REQUEST_TRANSPORT_SERVER } from \"./request_transport.js\";\nimport {\n ASK_ANSWER_CAPABILITIES,\n ASK_DASHBOARD_CAPABILITIES,\n guardrailMatches,\n hasExactCapabilities,\n resolveCapabilities,\n} from \"./target_profile.js\";\n\nexport interface AskMcpServerConfig {\n name: string;\n command: string;\n args?: string[];\n toolsByStep: Record<string, string[]>;\n}\n\nexport interface AskTierModels {\n orchestrator: string;\n cheap: string;\n strong: string;\n}\n\nexport interface AskWhenGuard {\n guard: \"on_failure\";\n target: string;\n}\n\nexport interface PreparedAskStep {\n name: string;\n role: string;\n tier: \"cheap\" | \"strong\";\n model: string;\n prompt: string;\n consumes: string[];\n produces: string;\n conditional: boolean;\n when: AskWhenGuard | null;\n enabledTools: string[];\n requireSuccessfulTool: boolean;\n}\n\nexport type AnalyticalExecutionKind = \"answer_query\" | \"generate_dashboard\";\n\nexport interface PreparedAskComponent {\n target: typeof TARGET;\n profile: string;\n node: ComponentNode;\n componentId: string;\n steps: PreparedAskStep[];\n capabilities: CapabilityResolution[];\n mcp: AskMcpServerConfig;\n models: AskTierModels;\n executionKind: AnalyticalExecutionKind;\n maxRepairAttempts: number;\n}\n\nexport interface PrepareAskInput {\n ir: string | WarbleIr;\n component: string;\n models: AskTierModels;\n mcp: AskMcpServerConfig;\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n\nconst TOOLS_BY_EXECUTION_KIND = {\n answer_query: [[\"get_context\"], [\"run_sql\"], [\"run_sql\"]],\n generate_dashboard: [[\"get_context\"], [\"run_sql\"]],\n} as const;\n\nfunction requireNonEmpty(value: string, field: string): void {\n if (value.trim().length === 0) throw new CodexDispatchError(`${field} must not be empty`);\n}\n\nfunction parseWhen(step: LlmCall): AskWhenGuard | null {\n if (!step.conditional) {\n if (step.when !== null) {\n throw new CodexDispatchError(`step '${step.name}' is unconditional but has a when guard`);\n }\n return null;\n }\n if (\n typeof step.when !== \"object\" ||\n step.when === null ||\n Array.isArray(step.when) ||\n (step.when as Record<string, unknown>)[\"guard\"] !== \"on_failure\" ||\n typeof (step.when as Record<string, unknown>)[\"target\"] !== \"string\"\n ) {\n throw new CodexDispatchError(\n `step '${step.name}' wall-hit: Ask repair requires on_failure(target)`,\n );\n }\n return {\n guard: \"on_failure\",\n target: (step.when as Record<string, string>)[\"target\"]!,\n };\n}\n\nfunction validateCommonAnalyticalShape(node: ComponentNode): void {\n if (\n node.type !== \"analytical\" ||\n node.realization_kind !== \"skill\" ||\n node.trigger.kind !== \"one_shot\" ||\n node.effect.outcome.kind !== \"none\"\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: Codex analytical execution requires analytical/skill/one_shot/none`,\n );\n }\n if (node.context_binding.binding_mode !== \"runtime_selected\") {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: Codex analytical execution requires runtime_selected context binding`,\n );\n }\n}\n\n/**\n * Generic IR-driven chain validator shared by both Ask shapes (answer_query, generate_dashboard).\n * Enforces the topology the runtime can honestly execute: any step count, any\n * tier per step (cheap|strong, not position-bound), each non-first unconditional step consumes\n * exactly its immediately-preceding step's output, each conditional step is an on_failure repair\n * targeting its immediately-preceding step and consumes that step's output, and — because the\n * runtime aligns `active.spawns[i]` to `steps[i]` with no gap-skipping support, and because an\n * always-run step cannot honestly depend on a conditionally-produced value — no unconditional\n * step may follow a conditional one (repairs form a maximal trailing suffix).\n */\nfunction validateStepChain(node: ComponentNode): void {\n const calls = node.llm_calls;\n if (calls.length === 0) {\n throw new CodexDispatchError(`component '${node.id}' wall-hit: Ask requires at least one llm_call`);\n }\n let sawConditional = false;\n calls.forEach((call, index) => {\n if (call.tier !== \"cheap\" && call.tier !== \"strong\") {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${call.name}' has unsupported tier '${call.tier}'`,\n );\n }\n if (call.produces === null) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${call.name}' must produce a named output`,\n );\n }\n const when = parseWhen(call);\n if (index === 0) {\n if (call.conditional || call.consumes.length !== 0) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: first Ask step must be unconditional with no consumes and one output`,\n );\n }\n return;\n }\n const previous = calls[index - 1]!;\n if (call.conditional) {\n if (\n when?.target !== previous.name ||\n call.consumes.length !== 1 ||\n call.consumes[0] !== previous.produces\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${call.name}' must be an on_failure repair of the immediately preceding step '${previous.name}'`,\n );\n }\n sawConditional = true;\n return;\n }\n if (sawConditional) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: an unconditional step cannot follow a repair step`,\n );\n }\n if (call.consumes.length !== 1 || call.consumes[0] !== previous.produces) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${call.name}' must consume exactly the preceding step's output`,\n );\n }\n });\n}\n\nfunction validateAnswerShape(node: ComponentNode): void {\n validateCommonAnalyticalShape(node);\n validateStepChain(node);\n\n if (!hasExactCapabilities(node.required_capabilities, ASK_ANSWER_CAPABILITIES)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: Ask capability set must be read-only SQL plus cheap/strong per-step tiering`,\n );\n }\n const guards = new Map(node.guardrails.map((guard) => [guard.name, guard]));\n if (\n guards.size !== 4 ||\n !guardrailMatches(guards.get(\"read_only_execution\"), \"read_only_execution\") ||\n !guardrailMatches(guards.get(\"deterministic_gate\"), \"deterministic_gate\") ||\n !guardrailMatches(guards.get(\"row_limit\"), \"row_limit\") ||\n !guardrailMatches(guards.get(\"statement_timeout\"), \"statement_timeout\")\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: Ask guardrails must match the locked read-only/deterministic and bounded row/timeout contract`,\n );\n }\n}\n\nfunction validateDashboardShape(node: ComponentNode): void {\n validateCommonAnalyticalShape(node);\n validateStepChain(node);\n\n if (!hasExactCapabilities(node.required_capabilities, ASK_DASHBOARD_CAPABILITIES)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: dashboard capability set must match read-only SQL, build, render, artifact, and cheap/strong per-step tiering`,\n );\n }\n const guards = new Map(node.guardrails.map((guard) => [guard.name, guard]));\n if (\n guards.size !== 2 ||\n !guardrailMatches(guards.get(\"read_only_execution\"), \"read_only_execution\") ||\n !guardrailMatches(guards.get(\"artifact_write\"), \"artifact_write\")\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: dashboard guardrails must be locked read-only execution plus scoped artifact_write`,\n );\n }\n if (node.effect.render_blocks.length === 0) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: dashboard render contract must declare at least one render block type`,\n );\n }\n // Wall-hits early on a structurally malformed render-block declaration using the\n // same parse that later validates the terminal envelope (render_contract.ts) — never\n // a second, independent check of the declared contract's *content*.\n parseDashboardRenderBlockContracts(node.effect.render_blocks);\n}\n\nfunction executionKind(node: ComponentNode): AnalyticalExecutionKind {\n const capabilities = new Set(node.required_capabilities);\n if (capabilities.has(\"render_contract\") || capabilities.has(\"artifact_write\")) {\n validateDashboardShape(node);\n return \"generate_dashboard\";\n }\n validateAnswerShape(node);\n return \"answer_query\";\n}\n\nexport function matchesAskContractShape(node: ComponentNode): boolean {\n try {\n executionKind(node);\n return true;\n } catch (error) {\n if (error instanceof CodexDispatchError) return false;\n throw error;\n }\n}\n\n/**\n * The specific reason a component's IR shape does not match either Ask contract (answer_query or\n * generate_dashboard), or null when it matches one of them. Mirrors `matchesAskContractShape`'s\n * try/catch but preserves the validator's own wall-hit message so a caller classifying across all\n * three families can surface precisely which structural expectation failed.\n */\nexport function askContractMismatchReason(node: ComponentNode): string | null {\n try {\n executionKind(node);\n return null;\n } catch (error) {\n if (error instanceof CodexDispatchError) return error.message;\n throw error;\n }\n}\n\nfunction roleName(stepName: string): string {\n const value = `warble_${stepName}`.replace(/[^A-Za-z0-9_-]/g, \"_\");\n if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(value)) {\n throw new CodexDispatchError(`step '${stepName}' cannot be mapped to a Codex agent role`);\n }\n return value;\n}\n\nexport function prepareAsk(input: PrepareAskInput): PreparedAskComponent {\n const ir = typeof input.ir === \"string\" ? parseIr(input.ir) : input.ir;\n if (ir.warble_ir_version !== SUPPORTED_IR_VERSION) {\n throw new CodexDispatchError(\n `unsupported warble_ir_version '${ir.warble_ir_version}' (supported: ${SUPPORTED_IR_VERSION})`,\n );\n }\n const node = ir.components.find((candidate) => candidate.id === input.component);\n if (!node) {\n throw new CodexDispatchError(\n `component '${input.component}' was not found in profile '${ir.profile}'`,\n );\n }\n assertDispatchableComponentIdentity(node);\n const kind = executionKind(node);\n if (!/^[A-Za-z0-9_-]+$/.test(input.mcp.name)) {\n throw new CodexDispatchError(\n `MCP server name '${input.mcp.name}' must contain only letters, digits, '_' or '-'`,\n );\n }\n if (input.mcp.name === REQUEST_TRANSPORT_SERVER) {\n throw new CodexDispatchError(`MCP server name '${input.mcp.name}' is reserved by the Ask request transport`);\n }\n if (!isAbsolute(input.mcp.command)) {\n throw new CodexDispatchError(\"Ask MCP server command must be absolute\");\n }\n requireNonEmpty(input.models.orchestrator, \"orchestrator model binding\");\n requireNonEmpty(input.models.cheap, \"cheap-tier model binding\");\n requireNonEmpty(input.models.strong, \"strong-tier model binding\");\n\n const steps = node.llm_calls.map((step, index): PreparedAskStep => {\n const tier = step.tier;\n if (tier !== \"cheap\" && tier !== \"strong\") {\n throw new CodexDispatchError(`step '${step.name}' has unsupported tier '${tier}'`);\n }\n const enabledTools = unique(input.mcp.toolsByStep[step.name] ?? []);\n const expectedTools = TOOLS_BY_EXECUTION_KIND[kind][index];\n if (expectedTools === undefined) {\n throw new CodexDispatchError(\n `step '${step.name}' has no declared MCP tool allowlist for target index ${index}`,\n );\n }\n if (\n enabledTools.length !== expectedTools.length ||\n enabledTools.some((tool, toolIndex) => tool !== expectedTools[toolIndex])\n ) {\n throw new CodexDispatchError(\n `step '${step.name}' requires exact MCP tools: ${expectedTools.join(\", \")}`,\n );\n }\n if (step.produces === null) {\n throw new CodexDispatchError(`step '${step.name}' must produce a named slot`);\n }\n return {\n name: step.name,\n role: roleName(step.name),\n tier,\n model: input.models[tier],\n prompt: step.prompt,\n consumes: [...step.consumes],\n produces: step.produces,\n conditional: step.conditional,\n when: parseWhen(step),\n enabledTools,\n requireSuccessfulTool: kind === \"generate_dashboard\" || index > 0,\n };\n });\n\n return {\n target: TARGET,\n profile: ir.profile,\n node,\n componentId: node.id,\n steps,\n capabilities: resolveCapabilities(node.required_capabilities, input.mcp.name),\n mcp: input.mcp,\n models: input.models,\n executionKind: kind,\n maxRepairAttempts: steps.filter((step) => step.conditional).length,\n };\n}\n","export class CodexDispatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodexDispatchError\";\n }\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport type { ComponentNode } from \"./ir.js\";\n\n/**\n * Refuses a component on IR grounds alone, before any family-specific shape check runs: this\n * target only ever executes `skill`-realized components (`realization_kind: skill | tool |\n * gated-tool` — every family's own shape validator already requires exactly `skill` too, so this\n * mirrors that, just earlier and uniformly). A `tool`/`gated-tool` component is host-owned by\n * definition — it names a lifecycle contract this target has no approval channel or write\n * authority to run, regardless of what required_capabilities it happens to declare.\n *\n * A component's id/verb carries no dispatch meaning (invariant #1): a genuinely host-owned\n * component wall-hits under any name, and a `skill`-realized component that declares only\n * capabilities a family here can honestly realize is dispatchable under any name — including one\n * that collides with a host-owned component's. Rejecting on capability content beyond\n * `realization_kind` is left to each family's own shape validator, which already enforces its\n * exact allowed capability set and reports which specific capability/shape expectation failed;\n * duplicating that check here would only replace those precise, family-scoped diagnostics with a\n * generic message.\n */\nexport function assertDispatchableComponentIdentity(node: ComponentNode): void {\n if (node.realization_kind !== \"skill\") {\n throw new CodexDispatchError(\n `component '${node.id}' is host-executed and cannot be dispatched by codex:local: ` +\n `realization_kind '${node.realization_kind}' is not 'skill'`,\n );\n }\n}\n","import { CodexDispatchError } from \"./error.js\";\n\nexport const TARGET = \"codex:local\" as const;\nexport const SUPPORTED_IR_VERSION = \"0.7\" as const;\n\nexport interface LlmCall {\n name: string;\n tier: string;\n prompt: string;\n consumes: string[];\n produces: string | null;\n conditional: boolean;\n when: unknown;\n}\n\nexport interface Guardrail {\n name: string;\n locked: boolean;\n scope?: string;\n threshold?: number;\n}\n\nexport interface ComponentNode {\n id: string;\n verb: string;\n type: string;\n realization_kind: string;\n llm_calls: LlmCall[];\n required_capabilities: string[];\n guardrails: Guardrail[];\n trigger: { kind: string };\n effect: {\n outcome: { kind: string };\n render_blocks: unknown[];\n };\n context_binding: {\n binding_mode: string;\n project: string;\n };\n}\n\nexport interface WarbleIr {\n warble_ir_version: string;\n profile: string;\n components: ComponentNode[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringArray(value: unknown, field: string): string[] {\n if (!Array.isArray(value) || !value.every((entry) => typeof entry === \"string\")) {\n throw new CodexDispatchError(`${field} must be an array of strings`);\n }\n return value;\n}\n\nfunction parseCall(value: unknown, componentId: string): LlmCall {\n if (!isRecord(value)) {\n throw new CodexDispatchError(`component '${componentId}' has a malformed llm_call`);\n }\n const { name, tier, prompt } = value;\n if (\n typeof name !== \"string\" ||\n typeof tier !== \"string\" ||\n typeof prompt !== \"string\" ||\n typeof value[\"conditional\"] !== \"boolean\" ||\n (value[\"produces\"] !== null && typeof value[\"produces\"] !== \"string\")\n ) {\n throw new CodexDispatchError(\n `component '${componentId}' llm_call has malformed name/tier/prompt/conditional/produces`,\n );\n }\n return {\n name,\n tier,\n prompt,\n consumes: stringArray(value[\"consumes\"] ?? [], `${componentId}.${name}.consumes`),\n produces: value[\"produces\"],\n conditional: value[\"conditional\"],\n when: value[\"when\"] ?? null,\n };\n}\n\nfunction parseGuardrail(value: unknown, componentId: string): Guardrail {\n if (\n !isRecord(value) ||\n typeof value[\"name\"] !== \"string\" ||\n typeof value[\"locked\"] !== \"boolean\"\n ) {\n throw new CodexDispatchError(`component '${componentId}' has a malformed guardrail`);\n }\n return {\n name: value[\"name\"],\n locked: value[\"locked\"],\n ...(typeof value[\"scope\"] === \"string\" ? { scope: value[\"scope\"] } : {}),\n ...(typeof value[\"threshold\"] === \"number\" ? { threshold: value[\"threshold\"] } : {}),\n };\n}\n\nfunction parseComponent(value: unknown): ComponentNode {\n if (!isRecord(value) || typeof value[\"id\"] !== \"string\") {\n throw new CodexDispatchError(\"IR component must be an object with a string id\");\n }\n const id = value[\"id\"];\n const trigger = value[\"trigger\"];\n const effect = value[\"effect\"];\n const outcome = isRecord(effect) ? effect[\"outcome\"] : null;\n const context = value[\"context_binding\"];\n if (\n typeof value[\"verb\"] !== \"string\" ||\n typeof value[\"type\"] !== \"string\" ||\n typeof value[\"realization_kind\"] !== \"string\" ||\n !Array.isArray(value[\"llm_calls\"]) ||\n !Array.isArray(value[\"guardrails\"]) ||\n !isRecord(trigger) ||\n typeof trigger[\"kind\"] !== \"string\" ||\n !isRecord(effect) ||\n !isRecord(outcome) ||\n typeof outcome[\"kind\"] !== \"string\" ||\n !Array.isArray(effect[\"render_blocks\"]) ||\n !isRecord(context) ||\n typeof context[\"binding_mode\"] !== \"string\" ||\n typeof context[\"project\"] !== \"string\"\n ) {\n throw new CodexDispatchError(`component '${id}' is missing required IR fields`);\n }\n return {\n id,\n verb: value[\"verb\"],\n type: value[\"type\"],\n realization_kind: value[\"realization_kind\"],\n llm_calls: value[\"llm_calls\"].map((call) => parseCall(call, id)),\n required_capabilities: stringArray(\n value[\"required_capabilities\"] ?? [],\n `${id}.required_capabilities`,\n ),\n guardrails: value[\"guardrails\"].map((guard) => parseGuardrail(guard, id)),\n trigger: { kind: trigger[\"kind\"] },\n effect: {\n outcome: { kind: outcome[\"kind\"] },\n render_blocks: effect[\"render_blocks\"],\n },\n context_binding: {\n binding_mode: context[\"binding_mode\"],\n project: context[\"project\"],\n },\n };\n}\n\nexport function parseIr(raw: string): WarbleIr {\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch (error) {\n throw new CodexDispatchError(`invalid IR JSON: ${String(error)}`);\n }\n if (\n !isRecord(value) ||\n typeof value[\"warble_ir_version\"] !== \"string\" ||\n typeof value[\"profile\"] !== \"string\" ||\n !Array.isArray(value[\"components\"])\n ) {\n throw new CodexDispatchError(\"IR requires warble_ir_version, profile, and components\");\n }\n if (value[\"warble_ir_version\"] !== SUPPORTED_IR_VERSION) {\n throw new CodexDispatchError(\n `unsupported warble_ir_version '${value[\"warble_ir_version\"]}' (supported: ${SUPPORTED_IR_VERSION})`,\n );\n }\n return {\n warble_ir_version: value[\"warble_ir_version\"],\n profile: value[\"profile\"],\n components: value[\"components\"].map(parseComponent),\n };\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport type { ComponentNode } from \"./ir.js\";\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\nexport interface DashboardRenderEnvelope {\n blocks: JsonRecord[];\n summary?: string;\n verified: boolean;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Parses an IR-declared dashboard render-block contract (`effect.render_blocks`)\n * into a type -> field-type map, loud-failing on any structurally malformed\n * declaration. This is the single source of truth for the render contract's\n * shape: Ask prepare time calls it to wall-hit early on a malformed IR, and\n * envelope validation below calls the same function against the same IR to\n * validate the actual terminal value — never a second, independent\n * implementation of this parse.\n */\nexport function parseDashboardRenderBlockContracts(\n renderBlocks: readonly unknown[],\n): Map<string, Record<string, string>> {\n const contracts = new Map<string, Record<string, string>>();\n for (const entry of renderBlocks) {\n if (!isRecord(entry) || typeof entry[\"type\"] !== \"string\" || !isRecord(entry[\"fields\"])) {\n throw new CodexDispatchError(\"dashboard IR contains a malformed render block contract\");\n }\n const fields = entry[\"fields\"];\n if (!Object.values(fields).every((field) => typeof field === \"string\")) {\n throw new CodexDispatchError(\"dashboard IR contains a malformed render field contract\");\n }\n contracts.set(entry[\"type\"], fields as Record<string, string>);\n }\n return contracts;\n}\n\nfunction validatePrimitive(value: unknown, type: string, context: string): void {\n if (type.endsWith(\"?\")) {\n if (value === undefined || value === null) return;\n validatePrimitive(value, type.slice(0, -1), context);\n return;\n }\n if (type.endsWith(\"[]\")) {\n if (!Array.isArray(value)) throw new CodexDispatchError(`${context} must be an array`);\n const itemType = type.slice(0, -2);\n for (const [index, item] of value.entries()) {\n validatePrimitive(item, itemType, `${context}[${index}]`);\n }\n return;\n }\n if (type.includes(\"|\")) {\n const alternatives = type.split(\"|\");\n if (alternatives.includes(\"string\") && typeof value === \"string\") return;\n if (alternatives.includes(\"number\") && typeof value === \"number\" && Number.isFinite(value)) return;\n if (typeof value === \"string\" && alternatives.includes(value)) return;\n throw new CodexDispatchError(`${context} does not match '${type}'`);\n }\n if (type === \"string\" && typeof value === \"string\") return;\n if (type === \"number\" && typeof value === \"number\" && Number.isFinite(value)) return;\n if (type === \"boolean\" && typeof value === \"boolean\") return;\n if (type === \"row\" && isRecord(value)) return;\n throw new CodexDispatchError(`${context} does not match '${type}'`);\n}\n\nexport function validateDashboardRenderEnvelope(\n value: unknown,\n node: ComponentNode,\n): DashboardRenderEnvelope {\n if (!isRecord(value)) throw new CodexDispatchError(\"dashboard output must be a JSON object\");\n const keys = Object.keys(value);\n if (\n keys.some((key) => !new Set([\"blocks\", \"summary\", \"verified\"]).has(key)) ||\n !Array.isArray(value[\"blocks\"]) ||\n value[\"blocks\"].length === 0 ||\n typeof value[\"verified\"] !== \"boolean\" ||\n (value[\"summary\"] !== undefined && typeof value[\"summary\"] !== \"string\")\n ) {\n throw new CodexDispatchError(\n \"dashboard output requires only non-empty blocks, optional summary, and boolean verified\",\n );\n }\n\n const contracts = parseDashboardRenderBlockContracts(node.effect.render_blocks);\n\n const blocks = value[\"blocks\"].map((entry, index): JsonRecord => {\n if (!isRecord(entry) || typeof entry[\"type\"] !== \"string\") {\n throw new CodexDispatchError(`dashboard block[${index}] requires a string type`);\n }\n const fields = contracts.get(entry[\"type\"]);\n if (!fields) {\n throw new CodexDispatchError(`dashboard block[${index}] uses undeclared type '${entry[\"type\"]}'`);\n }\n const allowed = new Set([\"type\", ...Object.keys(fields)]);\n if (Object.keys(entry).some((key) => !allowed.has(key))) {\n throw new CodexDispatchError(`dashboard block[${index}] contains undeclared fields`);\n }\n const normalized = { ...entry };\n for (const [field, type] of Object.entries(fields)) {\n validatePrimitive(normalized[field], type, `dashboard block[${index}].${field}`);\n // JSON producers commonly spell an absent optional value as null. The\n // consumer wire contract represents absence by omitting the field, so\n // canonicalize both accepted forms before emitting the terminal value.\n if (type.endsWith(\"?\") && normalized[field] === null) delete normalized[field];\n }\n return normalized;\n });\n return {\n blocks,\n ...(typeof value[\"summary\"] === \"string\" ? { summary: value[\"summary\"] } : {}),\n verified: value[\"verified\"],\n };\n}\n","export const REQUEST_TRANSPORT_SERVER = \"warble_request_transport\";\nexport const REQUEST_TRANSPORT_TOOL = \"get_original_request\";\nexport const STEP_TRANSPORT_TOOL = \"get_step_request\";\n","import { CodexDispatchError } from \"./error.js\";\nimport type { Guardrail } from \"./ir.js\";\n\n// This module is codex:local's single answer to two questions every family validator used to\n// answer separately: \"what can this target honestly realize, and how\" (capability →\n// realization) and \"what does a guardrail occurrence have to look like to count as enforced\"\n// (guardrail → enforcement). Setup, Ask, and Enrich preparers all read from here instead of\n// each carrying its own literal capability sets and scattered guardrail assertions.\n//\n// codex:local's honesty posture is deliberate and non-negotiable: no capability that would\n// require a cwd-scoped native read or write primitive is ever claimed native here. Codex\n// child agents get only a per-step MCP allowlist and this target has no native read\n// primitive — unlike claude-agent-sdk's SDK-level Read tool — so every data/context/\n// introspection capability (source_connect, context_build, semantic_introspection,\n// raw_material_read, sql_execution:read_only) resolves `realize-via` an allowlisted MCP\n// tool, no matter how tempting a single shared table makes native alignment look. This is\n// narrower than \"only llm:* is native\": genbi_build and render_contract are also native,\n// because the target validates the render envelope itself and borrows nothing from an MCP\n// tool to do it; artifact_write stays realize-via because the consumer persists the\n// artifact, never this target.\n\nexport type CapabilityOutcome = \"native\" | \"realize-via\";\n\nexport interface CapabilityResolution {\n capability: string;\n outcome: CapabilityOutcome;\n via: string | null;\n}\n\ninterface CapabilityRealizationEntry {\n outcome: CapabilityOutcome;\n /** A fixed native `via`, or a function of the invocation's configured MCP server name. */\n via: string | null | ((mcpName: string) => string);\n}\n\nconst mcpVia = (mcpName: string): string => `mcp:${mcpName}`;\n\n/** The target-level table: every capability codex:local can honestly resolve, and how. */\nexport const CAPABILITY_REALIZATION: Readonly<Record<string, CapabilityRealizationEntry>> = {\n \"llm:strong\": { outcome: \"native\", via: null },\n \"llm:cheap\": { outcome: \"native\", via: null },\n \"llm:per_step_tier\": { outcome: \"native\", via: null },\n source_connect: { outcome: \"realize-via\", via: mcpVia },\n context_build: { outcome: \"realize-via\", via: mcpVia },\n semantic_introspection: { outcome: \"realize-via\", via: mcpVia },\n raw_material_read: { outcome: \"realize-via\", via: mcpVia },\n \"sql_execution:read_only\": { outcome: \"realize-via\", via: mcpVia },\n genbi_build: { outcome: \"native\", via: \"validated-render-envelope\" },\n render_contract: { outcome: \"native\", via: \"validated-render-envelope\" },\n artifact_write: { outcome: \"realize-via\", via: \"consumer-persisted-render-envelope\" },\n};\n\n/**\n * Resolves a component's required capabilities against the target-level table, in the order\n * they were declared. Throws if a capability has no entry — this is a defensive backstop only:\n * every caller validates the exact capability set before reaching this point, so an unresolved\n * capability here means a family's shape check let something through it shouldn't have.\n */\nexport function resolveCapabilities(\n requiredCapabilities: readonly string[],\n mcpName: string,\n): CapabilityResolution[] {\n return requiredCapabilities.map((capability) => {\n const entry = CAPABILITY_REALIZATION[capability];\n if (!entry) {\n throw new CodexDispatchError(`capability '${capability}' has no realization on codex:local`);\n }\n return {\n capability,\n outcome: entry.outcome,\n via: typeof entry.via === \"function\" ? entry.via(mcpName) : entry.via,\n };\n });\n}\n\n/** True iff `requiredCapabilities` is exactly `expected` (same size, same members). */\nexport function hasExactCapabilities(\n requiredCapabilities: readonly string[],\n expected: ReadonlySet<string>,\n): boolean {\n return (\n requiredCapabilities.length === expected.size &&\n requiredCapabilities.every((capability) => expected.has(capability))\n );\n}\n\n// --- Setup family capability grouping ---\n\nexport const SETUP_DOMAIN_CAPABILITIES = [\"source_connect\", \"context_build\"] as const;\nexport type SetupDomainCapability = (typeof SETUP_DOMAIN_CAPABILITIES)[number];\n\nconst SETUP_DOMAIN_CAPABILITY_SET: ReadonlySet<string> = new Set(SETUP_DOMAIN_CAPABILITIES);\n\nexport function isSetupDomainCapability(value: string): value is SetupDomainCapability {\n return SETUP_DOMAIN_CAPABILITY_SET.has(value);\n}\n\n// --- Ask family capability sets (fixed per execution kind — not derived from the IR) ---\n\nexport const ASK_ANSWER_CAPABILITIES: ReadonlySet<string> = new Set([\n \"sql_execution:read_only\",\n \"llm:per_step_tier\",\n \"llm:strong\",\n \"llm:cheap\",\n]);\n\nexport const ASK_DASHBOARD_CAPABILITIES: ReadonlySet<string> = new Set([\n \"sql_execution:read_only\",\n \"genbi_build\",\n \"render_contract\",\n \"artifact_write\",\n \"llm:per_step_tier\",\n \"llm:strong\",\n \"llm:cheap\",\n]);\n\n// --- Enrich family capability grouping ---\n\nexport const ENRICH_DOMAIN_CAPABILITIES = [\"semantic_introspection\", \"raw_material_read\"] as const;\nexport type EnrichDomainCapability = (typeof ENRICH_DOMAIN_CAPABILITIES)[number];\n\nconst ENRICH_DOMAIN_CAPABILITY_SET: ReadonlySet<string> = new Set(ENRICH_DOMAIN_CAPABILITIES);\n\nexport function isEnrichDomainCapability(value: string): value is EnrichDomainCapability {\n return ENRICH_DOMAIN_CAPABILITY_SET.has(value);\n}\n\n// Deliberately narrower than CAPABILITY_REALIZATION's full key set: some capabilities this\n// target can honestly realize for OTHER families (e.g. `context_build`, for Setup) are not\n// legal for Enrich's own components. The allowlist must name only what Enrich itself may\n// require, so a foreign-but-realizable capability still fails Enrich's by-name check (and does\n// so before any shape error can mask which capability was illegal) rather than silently passing\n// the name check and only failing later with a message that doesn't name it.\nexport const ENRICH_ALLOWED_CAPABILITIES: ReadonlySet<string> = new Set<string>([\n ...ENRICH_DOMAIN_CAPABILITIES,\n \"llm:cheap\",\n \"llm:strong\",\n]);\n\n// --- Guardrail enforcement ---\n\nexport interface GuardrailRequirement {\n locked: boolean;\n scope?: string;\n threshold?: number;\n}\n\n/** The target-level table: the canonical locked/scope/threshold values for each guardrail name. */\nexport const GUARDRAIL_ENFORCEMENT: Readonly<Record<string, GuardrailRequirement>> = {\n setup_execution: { locked: true, scope: \".\" },\n read_only_execution: { locked: true },\n deterministic_gate: { locked: true },\n row_limit: { locked: false, threshold: 1000 },\n statement_timeout: { locked: false, threshold: 30 },\n artifact_write: { locked: true, scope: \".\" },\n};\n\n/**\n * True iff `guard` is present, named `name`, and matches every value `GUARDRAIL_ENFORCEMENT`\n * defines for that name (locked-state always; scope/threshold only when the table defines\n * them for this guardrail — callers that need a stricter check, such as Enrich's requirement\n * that `read_only_execution` carry no scope at all, pass `requireScopeAbsent`).\n */\nexport function guardrailMatches(\n guard: Guardrail | undefined,\n name: string,\n options?: { requireScopeAbsent?: boolean },\n): boolean {\n const requirement = GUARDRAIL_ENFORCEMENT[name];\n if (!requirement || !guard || guard.name !== name || guard.locked !== requirement.locked) {\n return false;\n }\n if (requirement.scope !== undefined && guard.scope !== requirement.scope) {\n return false;\n }\n if (requirement.threshold !== undefined && guard.threshold !== requirement.threshold) {\n return false;\n }\n if (options?.requireScopeAbsent && guard.scope !== undefined) {\n return false;\n }\n return true;\n}\n","import { spawn, type ChildProcess } from \"node:child_process\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, relative, resolve } from \"node:path\";\nimport { createInterface, type Interface } from \"node:readline\";\n\nimport { buildIsolationArgs, sanitizeCodexEnvironment } from \"./config.js\";\nimport { CodexDispatchError } from \"./error.js\";\nimport type { PreparedSetupComponent } from \"./prepare.js\";\nimport type { PreparedEnrichComponent } from \"./enrich_prepare.js\";\nimport type { SessionIsolationOptions } from \"./session_types.js\";\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\ninterface PendingRequest {\n method: string;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isWithin(parent: string, candidate: string): boolean {\n const path = relative(parent, candidate);\n return path === \"\" || (!path.startsWith(\"..\") && !isAbsolute(path));\n}\n\nexport function validateSessionIsolation(options: SessionIsolationOptions): {\n codexHome: string;\n cwd: string;\n} {\n if (options.externalAuthentication !== \"provisioned\") {\n throw new CodexDispatchError(\n \"persistent session authentication must be provisioned externally\",\n );\n }\n if (!isAbsolute(options.codexHome) || !isAbsolute(options.cwd)) {\n throw new CodexDispatchError(\"session codexHome and cwd must be absolute\");\n }\n if (!existsSync(options.codexHome)) {\n throw new CodexDispatchError(\"dedicated session codexHome must be provisioned before start\");\n }\n if (existsSync(join(options.codexHome, \"config.toml\"))) {\n throw new CodexDispatchError(\"dedicated session codexHome must not contain config.toml\");\n }\n const codexHome = realpathSync(options.codexHome);\n const cwd = realpathSync(options.cwd);\n const inheritedCodexHome =\n options.env === undefined ? process.env[\"CODEX_HOME\"] : options.env[\"CODEX_HOME\"];\n const defaultHome = resolve(inheritedCodexHome ?? join(homedir(), \".codex\"));\n const comparableDefault = existsSync(defaultHome) ? realpathSync(defaultHome) : defaultHome;\n if (codexHome === comparableDefault) {\n throw new CodexDispatchError(\"persistent sessions require a dedicated non-default codexHome\");\n }\n if (isWithin(cwd, codexHome) || isWithin(codexHome, cwd)) {\n throw new CodexDispatchError(\n \"dedicated session codexHome and project cwd must not overlap\",\n );\n }\n return { codexHome, cwd };\n}\n\nexport function buildAppServerArgs(\n prepared: PreparedSetupComponent | PreparedEnrichComponent,\n options: SessionIsolationOptions,\n): string[] {\n return [\n ...(options.codexArgsPrefix ?? []),\n \"app-server\",\n \"--stdio\",\n \"--strict-config\",\n ...buildIsolationArgs(prepared),\n ];\n}\n\n/** Read-only app-server startup for model discovery. It deliberately has no thread/session config. */\nexport interface CatalogTransportOptions {\n cwd: string;\n codexHome?: string;\n codexBin?: string;\n codexArgsPrefix?: string[];\n timeoutMs?: number;\n terminationGraceMs?: number;\n env?: NodeJS.ProcessEnv;\n}\n\nfunction validateCatalogTransport(options: CatalogTransportOptions): {\n cwd: string;\n codexHome: string | undefined;\n} {\n if (!isAbsolute(options.cwd) || !existsSync(options.cwd)) {\n throw new CodexDispatchError(\"model catalog cwd must be an existing absolute path\");\n }\n if (options.codexHome !== undefined && (!isAbsolute(options.codexHome) || !existsSync(options.codexHome))) {\n throw new CodexDispatchError(\"model catalog codexHome must be an existing absolute path\");\n }\n return {\n cwd: realpathSync(options.cwd),\n codexHome: options.codexHome === undefined ? undefined : realpathSync(options.codexHome),\n };\n}\n\nexport class CodexAppServerTransport {\n private nextId = 1;\n private readonly pending = new Map<number, PendingRequest>();\n private readonly lines: Interface;\n private readonly child: ChildProcess;\n private closing = false;\n private closed = false;\n private killTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly closePromise: Promise<void>;\n\n private constructor(\n child: ChildProcess,\n private readonly timeoutMs: number,\n private readonly terminationGraceMs: number,\n private readonly onNotification: (method: string, params: unknown) => void,\n private readonly onDisconnect: (error?: CodexDispatchError) => void,\n ) {\n this.child = child;\n if (child.stdout === null || child.stdin === null || child.stderr === null) {\n throw new CodexDispatchError(\"app-server requires piped stdio\");\n }\n child.stderr.resume();\n this.lines = createInterface({ input: child.stdout });\n this.lines.on(\"line\", (line) => this.onLine(line));\n this.closePromise = new Promise((resolveClose) => {\n child.once(\"close\", (code, signal) => {\n this.closed = true;\n this.lines.close();\n const detail = signal !== null ? `signal ${signal}` : `exit ${code ?? \"unknown\"}`;\n this.rejectPending(`app-server transport disconnected (${detail})`);\n if (!this.closing) this.onDisconnect();\n resolveClose();\n });\n child.once(\"error\", () => {\n this.rejectPending(\"failed to start app-server\");\n });\n });\n }\n\n static async start(\n prepared: PreparedSetupComponent | PreparedEnrichComponent,\n options: SessionIsolationOptions,\n onNotification: (method: string, params: unknown) => void,\n onDisconnect: (error?: CodexDispatchError) => void,\n ): Promise<CodexAppServerTransport> {\n return CodexAppServerTransport.startWithArgs(\n buildAppServerArgs(prepared, options),\n options,\n onNotification,\n onDisconnect,\n );\n }\n\n static async startWithArgs(\n args: string[],\n options: SessionIsolationOptions,\n onNotification: (method: string, params: unknown) => void,\n onDisconnect: (error?: CodexDispatchError) => void,\n ): Promise<CodexAppServerTransport> {\n const isolated = validateSessionIsolation(options);\n const child = spawn(options.codexBin ?? \"codex\", args, {\n cwd: isolated.cwd,\n env: {\n ...sanitizeCodexEnvironment(options.env),\n CODEX_HOME: isolated.codexHome,\n },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n const transport = new CodexAppServerTransport(\n child,\n options.timeoutMs ?? 10_000,\n options.terminationGraceMs ?? 1_000,\n onNotification,\n onDisconnect,\n );\n try {\n const initialized = await transport.request(\"initialize\", {\n clientInfo: { name: \"warble_codex_local\", title: \"Warble Codex Local\", version: \"0.1.0\" },\n capabilities: { experimentalApi: true, requestAttestation: false },\n });\n if (!isRecord(initialized) || resolve(String(initialized[\"codexHome\"] ?? \"\")) !== isolated.codexHome) {\n throw new CodexDispatchError(\"app-server initialize returned an unexpected codexHome\");\n }\n transport.notify(\"initialized\");\n return transport;\n } catch (error) {\n await transport.close();\n throw error;\n }\n }\n\n /**\n * Start a narrowly read-only app-server transport for `model/list`. Unlike persistent sessions,\n * catalog discovery may use the caller's normal logged-in Codex identity, but it never starts a\n * thread or applies the session's MCP/tool isolation configuration.\n */\n static async startCatalog(options: CatalogTransportOptions): Promise<CodexAppServerTransport> {\n const catalog = validateCatalogTransport(options);\n const child = spawn(options.codexBin ?? \"codex\", [\n ...(options.codexArgsPrefix ?? []),\n \"app-server\",\n \"--stdio\",\n ], {\n cwd: catalog.cwd,\n env: {\n ...sanitizeCodexEnvironment(options.env),\n ...(catalog.codexHome === undefined ? {} : { CODEX_HOME: catalog.codexHome }),\n },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n const transport = new CodexAppServerTransport(\n child,\n options.timeoutMs ?? 10_000,\n options.terminationGraceMs ?? 1_000,\n () => undefined,\n () => undefined,\n );\n try {\n const initialized = await transport.request(\"initialize\", {\n clientInfo: { name: \"warble_codex_local_catalog\", title: \"Warble Codex Model Catalog\", version: \"0.1.0\" },\n capabilities: { experimentalApi: true, requestAttestation: false },\n });\n const returnedCodexHome = isRecord(initialized) ? initialized[\"codexHome\"] : undefined;\n if (\n typeof returnedCodexHome !== \"string\" ||\n !isAbsolute(returnedCodexHome) ||\n (catalog.codexHome !== undefined && resolve(returnedCodexHome) !== catalog.codexHome)\n ) {\n throw new CodexDispatchError(\"app-server initialize returned an invalid catalog response\");\n }\n transport.notify(\"initialized\");\n return transport;\n } catch (error) {\n await transport.close();\n throw error;\n }\n }\n\n request(method: string, params: unknown = {}): Promise<unknown> {\n if (this.closed || this.closing || this.child.stdin === null) {\n return Promise.reject(new CodexDispatchError(\"app-server transport is not available\"));\n }\n const id = this.nextId++;\n return new Promise((resolveRequest, rejectRequest) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n rejectRequest(new CodexDispatchError(`app-server request '${method}' timed out`));\n void this.close();\n }, this.timeoutMs);\n this.pending.set(id, { method, resolve: resolveRequest, reject: rejectRequest, timer });\n this.write({ jsonrpc: \"2.0\", id, method, params });\n });\n }\n\n notify(method: string, params?: unknown): void {\n this.write({ jsonrpc: \"2.0\", method, ...(params === undefined ? {} : { params }) });\n }\n\n async close(): Promise<void> {\n if (this.closing || this.closed) return this.closePromise;\n this.closing = true;\n this.signalTree(\"SIGTERM\");\n this.killTimer = setTimeout(() => {\n if (!this.closed) this.signalTree(\"SIGKILL\");\n }, this.terminationGraceMs);\n await this.closePromise;\n if (this.killTimer !== undefined) clearTimeout(this.killTimer);\n }\n\n private write(message: JsonRecord): void {\n if (this.child.stdin === null || this.child.stdin.destroyed) {\n throw new CodexDispatchError(\"app-server stdin is closed\");\n }\n this.child.stdin.write(`${JSON.stringify(message)}\\n`);\n }\n\n private onLine(line: string): void {\n let message: unknown;\n try {\n message = JSON.parse(line);\n } catch {\n this.protocolFailure(\"app-server emitted non-JSON output\");\n return;\n }\n if (!isRecord(message)) {\n this.protocolFailure(\"app-server emitted a non-object message\");\n return;\n }\n if (typeof message[\"id\"] === \"number\" && (\"result\" in message || \"error\" in message)) {\n const pending = this.pending.get(message[\"id\"]);\n if (!pending) {\n this.protocolFailure(\"app-server emitted a response for an unknown request\");\n return;\n }\n this.pending.delete(message[\"id\"]);\n clearTimeout(pending.timer);\n if (message[\"error\"] !== undefined) {\n // `model/list` needs one user-actionable classification, but must not expose raw RPC\n // messages (which can contain provider/account details) to the catalog caller.\n if (\n pending.method === \"model/list\" &&\n isRecord(message[\"error\"]) &&\n typeof message[\"error\"][\"message\"] === \"string\" &&\n /not authenticated|unauthenticated|authentication|login required|sign in/i.test(message[\"error\"][\"message\"])\n ) {\n pending.reject(new CodexDispatchError(\"app-server model catalog is not authenticated\"));\n } else {\n pending.reject(new CodexDispatchError(`app-server request '${pending.method}' failed`));\n }\n } else {\n pending.resolve(message[\"result\"]);\n }\n return;\n }\n if (typeof message[\"method\"] === \"string\" && message[\"id\"] === undefined) {\n try {\n this.onNotification(message[\"method\"], message[\"params\"]);\n } catch {\n this.protocolFailure(\"app-server notification violated the session contract\");\n }\n return;\n }\n if (typeof message[\"method\"] === \"string\" && message[\"id\"] !== undefined) {\n this.write({\n jsonrpc: \"2.0\",\n id: message[\"id\"],\n error: { code: -32601, message: \"client request not supported\" },\n });\n return;\n }\n this.protocolFailure(\"app-server emitted an invalid JSON-RPC message\");\n }\n\n private protocolFailure(message: string): void {\n this.rejectPending(message);\n this.onDisconnect(new CodexDispatchError(message));\n void this.close();\n }\n\n private rejectPending(message: string): void {\n for (const pending of this.pending.values()) {\n clearTimeout(pending.timer);\n pending.reject(new CodexDispatchError(message));\n }\n this.pending.clear();\n }\n\n private signalTree(signal: NodeJS.Signals): void {\n if (this.closed || this.child.pid === undefined) return;\n if (process.platform !== \"win32\") {\n try {\n process.kill(-this.child.pid, signal);\n return;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ESRCH\") return;\n }\n }\n this.child.kill(signal);\n }\n}\n","import type { PreparedSetupComponent } from \"./prepare.js\";\nimport type { PreparedEnrichComponent } from \"./enrich_prepare.js\";\n\ntype PreparedOneShotComponent = PreparedSetupComponent | PreparedEnrichComponent;\n\n/** Structurally matches both `PreparedSetupStep` and `PreparedEnrichStep` — the two engines stay\n * separate types, but a single prepared step is enough to build this target's args/prompt for\n * either one. */\nexport interface PreparedStepLike {\n name: string;\n model: string;\n prompt: string;\n consumes: string[];\n produces: string;\n}\n\nexport interface BuildPromptOptions {\n /** Setup's host consumes the produced slot as terminal text; Enrich may marshal structured JSON. */\n producedValue?: \"string\" | \"json\";\n}\n\nconst API_BILLING_ENV_KEYS = new Set([\n \"OPENAI_API_KEY\",\n \"CODEX_API_KEY\",\n \"AZURE_OPENAI_API_KEY\",\n \"OPENAI_ORGANIZATION\",\n \"OPENAI_ORG_ID\",\n \"OPENAI_PROJECT\",\n \"OPENAI_PROJECT_ID\",\n]);\n\nexport const DISABLED_FEATURES = [\n \"shell_tool\",\n \"unified_exec\",\n \"shell_zsh_fork\",\n \"unified_exec_zsh_fork\",\n \"standalone_web_search\",\n \"apps\",\n \"plugins\",\n \"in_app_browser\",\n \"browser_use\",\n \"computer_use\",\n \"image_generation\",\n \"skill_search\",\n \"multi_agent\",\n] as const;\n\nexport function tomlString(value: string): string {\n return JSON.stringify(value);\n}\n\nexport function tomlStringArray(values: readonly string[]): string {\n return `[${values.map(tomlString).join(\",\")}]`;\n}\n\nfunction sanitizeCodexToolName(value: string): string {\n return value.replace(/[^A-Za-z0-9_]/g, \"_\");\n}\n\nexport function codexMcpCallableNamespace(server: string): string {\n return `mcp__${sanitizeCodexToolName(server)}`;\n}\n\nexport function codexMcpCallableName(server: string, tool: string): string {\n return `${codexMcpCallableNamespace(server)}__${sanitizeCodexToolName(tool)}`;\n}\n\nexport function sanitizeCodexEnvironment(\n source: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n const clean: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(source)) {\n if (!API_BILLING_ENV_KEYS.has(key.toUpperCase()) && value !== undefined) clean[key] = value;\n }\n return clean;\n}\n\nexport interface InvocationArgsOptions {\n cwd: string;\n codexArgsPrefix?: string[];\n}\n\nexport function buildIsolationArgs(prepared: PreparedOneShotComponent): string[] {\n const serverKey = `mcp_servers.${prepared.mcp.name}`;\n const args = [\n \"-c\",\n \"shell_environment_policy.inherit=none\",\n \"-c\",\n \"project_doc_max_bytes=0\",\n \"-c\",\n \"project_root_markers=[]\",\n \"-c\",\n `web_search=${tomlString(\"disabled\")}`,\n \"-c\",\n \"features.code_mode.enabled=false\",\n \"-c\",\n `features.code_mode.direct_only_tool_namespaces=${tomlStringArray([codexMcpCallableNamespace(prepared.mcp.name)])}`,\n \"-c\",\n `${serverKey}.command=${tomlString(prepared.mcp.command)}`,\n \"-c\",\n `${serverKey}.args=${tomlStringArray(prepared.mcp.args ?? [])}`,\n \"-c\",\n `${serverKey}.enabled_tools=${tomlStringArray(prepared.enabledTools)}`,\n \"-c\",\n `${serverKey}.default_tools_approval_mode=${tomlString(\"approve\")}`,\n \"-c\",\n `${serverKey}.required=true`,\n ];\n for (const feature of DISABLED_FEATURES) args.push(\"--disable\", feature);\n return args;\n}\n\nexport function buildIsolationConfig(prepared: PreparedOneShotComponent): Record<string, unknown> {\n const serverKey = `mcp_servers.${prepared.mcp.name}`;\n return {\n \"shell_environment_policy.inherit\": \"none\",\n project_doc_max_bytes: 0,\n project_root_markers: [],\n web_search: \"disabled\",\n \"features.code_mode.enabled\": false,\n \"features.code_mode.direct_only_tool_namespaces\": [\n codexMcpCallableNamespace(prepared.mcp.name),\n ],\n [`${serverKey}.command`]: prepared.mcp.command,\n [`${serverKey}.args`]: prepared.mcp.args ?? [],\n [`${serverKey}.enabled_tools`]: prepared.enabledTools,\n [`${serverKey}.default_tools_approval_mode`]: \"approve\",\n [`${serverKey}.required`]: true,\n ...Object.fromEntries(DISABLED_FEATURES.map((feature) => [`features.${feature}`, false])),\n };\n}\n\nexport function buildCodexArgs(\n prepared: PreparedOneShotComponent,\n step: PreparedStepLike,\n options: InvocationArgsOptions,\n): string[] {\n const args = [\n ...(options.codexArgsPrefix ?? []),\n \"--ask-for-approval\",\n \"never\",\n \"exec\",\n \"--json\",\n \"--ephemeral\",\n \"--ignore-user-config\",\n \"--ignore-rules\",\n \"--strict-config\",\n \"--skip-git-repo-check\",\n \"--sandbox\",\n \"read-only\",\n \"--cd\",\n options.cwd,\n \"--model\",\n step.model,\n ...buildIsolationArgs(prepared),\n ];\n args.push(\"-\");\n return args;\n}\n\n/**\n * `inputs` carries the marshalled values this step's `consumes` names resolve to from earlier\n * steps' outputs in this same dispatch. When a step declares no `consumes` (every existing\n * single-step fixture, and the first step of any multi-step component), no input section is added.\n */\nexport function buildPrompt(\n prepared: PreparedOneShotComponent,\n step: PreparedStepLike,\n request: string,\n inputs: Record<string, unknown> = {},\n options: BuildPromptOptions = {},\n): string {\n const tools = prepared.enabledTools\n .map(\n (tool) =>\n `${prepared.mcp.name}.${tool} -> ${codexMcpCallableName(prepared.mcp.name, tool)}`,\n )\n .join(\", \");\n const terminalContract = [\n `The final answer must be one JSON object with exactly the produced field '${step.produces}'.`,\n ...(options.producedValue === \"string\"\n ? [`The value of '${step.produces}' must be a JSON string, not an object, array, number, boolean, or null.`]\n : []),\n \"Do not wrap the JSON in Markdown or include prose.\",\n ];\n const inputSection =\n step.consumes.length === 0\n ? []\n : [\n \"\",\n \"Inputs from earlier steps (JSON):\",\n JSON.stringify(Object.fromEntries(step.consumes.map((name) => [name, inputs[name]]))),\n ];\n return [\n `You are executing Warble target ${prepared.target}.`,\n `Run exactly one profile step: ${prepared.componentId}.${step.name}.`,\n `Only use the allowlisted MCP tools (raw identity -> Codex callable name): ${tools}.`,\n \"The raw and qualified names identify the same MCP tool; call the qualified Codex name, not a fallback.\",\n \"Do not use shell, file mutation, web, browser, apps, plugins, skills, or delegation.\",\n \"If the required MCP tool is unavailable or fails, fail loudly; do not substitute another mechanism.\",\n ...terminalContract,\n ...inputSection,\n \"\",\n \"Step contract:\",\n step.prompt,\n \"\",\n \"User request:\",\n request,\n ].join(\"\\n\");\n}\n","import { existsSync, mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n DISABLED_FEATURES,\n codexMcpCallableName,\n tomlString,\n tomlStringArray,\n} from \"./config.js\";\nimport type { PreparedAskComponent, PreparedAskStep } from \"./ask_prepare.js\";\nimport {\n REQUEST_TRANSPORT_SERVER,\n REQUEST_TRANSPORT_TOOL,\n STEP_TRANSPORT_TOOL,\n} from \"./request_transport.js\";\n\nconst ASK_DISABLED_FEATURES = DISABLED_FEATURES.filter(\n (feature) => feature !== \"multi_agent\",\n);\n\nexport interface AskAgentConfigFile {\n role: string;\n path: string;\n model: string;\n tools: string[];\n}\n\nexport interface AskAgentConfigBundle {\n directory: string;\n requestFile: string;\n stepRequestFile: string;\n agents: AskAgentConfigFile[];\n parentConfig: Record<string, unknown>;\n bindRequest: (request: string) => void;\n bindStepRequest: (request: string) => void;\n cleanup: () => void;\n}\n\nfunction renderConfigValue(value: unknown): string {\n if (typeof value === \"string\") return tomlString(value);\n if (typeof value === \"boolean\" || typeof value === \"number\") return String(value);\n if (Array.isArray(value) && value.every((entry) => typeof entry === \"string\")) {\n return tomlStringArray(value);\n }\n throw new Error(\"Ask app-server config contains an unsupported value\");\n}\n\n/**\n * Custom-agent roles must be registered when app-server starts. Supplying the\n * same keys only in thread/start is too late: the collaboration tool's agent\n * registry has already been constructed and spawnAgent rejects the role.\n */\nexport function buildAskAppServerArgs(bundle: AskAgentConfigBundle): string[] {\n const args = [\"app-server\", \"--stdio\", \"--strict-config\"];\n for (const [key, value] of Object.entries(bundle.parentConfig)) {\n args.push(\"-c\", `${key}=${renderConfigValue(value)}`);\n }\n return args;\n}\n\nfunction childInstructions(prepared: PreparedAskComponent, step: PreparedAskStep): string {\n const toolNames = step.enabledTools\n .map(\n (tool) =>\n `${prepared.mcp.name}.${tool} -> ${codexMcpCallableName(prepared.mcp.name, tool)}`,\n )\n .join(\", \");\n const requestTransportCallable = codexMcpCallableName(\n REQUEST_TRANSPORT_SERVER,\n REQUEST_TRANSPORT_TOOL,\n );\n const stepTransportCallable = codexMcpCallableName(\n REQUEST_TRANSPORT_SERVER,\n STEP_TRANSPORT_TOOL,\n );\n const dashboardContract =\n prepared.executionKind === \"generate_dashboard\"\n ? [\n `The exact allowed dashboard block contract is ${JSON.stringify(prepared.node.effect.render_blocks)}.`,\n \"Each contract entry's fields object is schema metadata, not an output wrapper: emit each declared field directly beside type at the block top level and never emit a fields key.\",\n \"A field whose type ends in ? is optional: omit it when unavailable and never emit null for it.\",\n \"Use every required field declared for a chosen block type, use no undeclared fields, and represent each row as a JSON object keyed by its column names.\",\n ]\n : [];\n const dashboardOutput =\n prepared.executionKind === \"generate_dashboard\" &&\n step.name === prepared.steps.at(-1)?.name\n ? [\n \"The value in the successful step envelope must be the dashboard render artifact: a JSON object with non-empty blocks, optional summary, and boolean verified.\",\n \"Blocks may use only the block types and fields declared in the exact allowed dashboard block contract above; include at least one data panel and one definition block.\",\n \"Set verified=true only when the required MCP queries completed successfully and the returned values were validated.\",\n ]\n : [];\n const requiredTool = step.requireSuccessfulTool\n ? [\n \"This step requires at least one successful call to an enabled MCP tool. The configured tool is available: attempt the call before reporting any tool availability failure.\",\n ]\n : [];\n const wrenToolArguments = step.enabledTools.includes(\"get_context\")\n ? [\n \"For wren.get_context, pass exactly one argument named question whose value is the authoritative original request text returned by the request transport call.\",\n ]\n : [];\n const queryCardinality = step.enabledTools.includes(\"run_sql\")\n ? [\n \"Before claiming verified=true, check join cardinality and fanout. Never compute independent table counts over a raw CROSS JOIN; use scalar subqueries or independently aggregated CTEs. For joined facts, use declared semantic relationships and distinct entity keys where needed so row multiplication cannot inflate aggregates.\",\n ]\n : [];\n return [\n `You are the named Warble step agent '${step.role}'.`,\n `Execute only IR step '${step.name}' and produce slot '${step.produces}'.`,\n `Before any reasoning or business MCP call, call ${REQUEST_TRANSPORT_SERVER}.${REQUEST_TRANSPORT_TOOL} through its exact qualified Codex callable ${requestTransportCallable} exactly once. Its returned text is the authoritative original user request for this turn.`,\n `Then call ${REQUEST_TRANSPORT_SERVER}.${STEP_TRANSPORT_TOOL} through its exact qualified Codex callable ${stepTransportCallable} exactly once. Its returned WARBLE_STEP_REQUEST envelope is the authoritative step and input slots; ignore any task-message copy of those inputs.`,\n `When MCP tools are exposed through code-mode exec, invoke exactly await tools.${requestTransportCallable}({}); do not guess, shorten, or rename the callable.`,\n \"Never ask the parent to copy, summarize, or reconstruct the original request, and never continue if the request transport call fails.\",\n `Use only these MCP tools when needed (raw identity -> exact qualified Codex callable): ${toolNames}.`,\n \"Under code-mode exec, invoke the qualified callable shown above through tools; do not guess an alias or use exec for any non-MCP operation.\",\n \"Do not use shell, file mutation, web, browser, apps, plugins, skills, or child agents.\",\n \"Return exactly one JSON object with keys warble_step, produces, ok, value, and error.\",\n `warble_step must equal '${step.name}' and produces must equal '${step.produces}'.`,\n \"On success set ok=true, put the produced slot value in value, and set error=null exactly; never use an empty error string.\",\n \"On failure set ok=false, keep the produced slot value with any diagnostics needed by a declared repair step, and use a non-empty stable non-secret error string.\",\n \"Do not wrap the JSON in markdown and do not add prose.\",\n ...requiredTool,\n ...wrenToolArguments,\n ...queryCardinality,\n ...dashboardContract,\n ...dashboardOutput,\n \"\",\n \"Step contract:\",\n step.prompt,\n ].join(\"\\n\");\n}\n\nexport function renderAskAgentToml(\n prepared: PreparedAskComponent,\n step: PreparedAskStep,\n requestFile: string,\n stepRequestFile: string,\n): string {\n const serverKey = `mcp_servers.${prepared.mcp.name}`;\n const requestServerKey = `mcp_servers.${REQUEST_TRANSPORT_SERVER}`;\n const builtRequestMcp = fileURLToPath(new URL(\"./request_mcp.js\", import.meta.url));\n const sourceRequestMcp = fileURLToPath(new URL(\"./request_mcp.ts\", import.meta.url));\n const sourceTsx = fileURLToPath(new URL(\"../node_modules/.bin/tsx\", import.meta.url));\n const requestMcp = existsSync(builtRequestMcp) ? builtRequestMcp : sourceRequestMcp;\n const requestMcpCommand = existsSync(builtRequestMcp) ? process.execPath : sourceTsx;\n if (!existsSync(requestMcp) || !existsSync(requestMcpCommand)) {\n throw new Error(\"Ask request transport executable is unavailable\");\n }\n const lines = [\n `name = ${tomlString(step.role)}`,\n `description = ${tomlString(`Executes Warble IR step ${step.name}`)}`,\n `developer_instructions = ${tomlString(childInstructions(prepared, step))}`,\n `model = ${tomlString(step.model)}`,\n `approval_policy = ${tomlString(\"never\")}`,\n `sandbox_mode = ${tomlString(\"read-only\")}`,\n \"\",\n \"[agents]\",\n \"enabled = false\",\n \"\",\n `[${serverKey}]`,\n `command = ${tomlString(prepared.mcp.command)}`,\n `args = ${tomlStringArray(prepared.mcp.args ?? [])}`,\n `enabled_tools = ${tomlStringArray(step.enabledTools)}`,\n `default_tools_approval_mode = ${tomlString(\"approve\")}`,\n \"required = true\",\n \"\",\n `[${requestServerKey}]`,\n `command = ${tomlString(requestMcpCommand)}`,\n `args = ${tomlStringArray([requestMcp, \"--request-file\", requestFile, \"--step-file\", stepRequestFile])}`,\n `enabled_tools = ${tomlStringArray([REQUEST_TRANSPORT_TOOL, STEP_TRANSPORT_TOOL])}`,\n `default_tools_approval_mode = ${tomlString(\"approve\")}`,\n \"required = true\",\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\nexport function createAskAgentConfigBundle(\n prepared: PreparedAskComponent,\n): AskAgentConfigBundle {\n const directory = mkdtempSync(join(tmpdir(), \"warble-codex-agents-\"));\n try {\n const requestFile = join(directory, \"original-request.txt\");\n const stepRequestFile = join(directory, \"step-request.txt\");\n writeFileSync(requestFile, \"\", { encoding: \"utf8\", mode: 0o600 });\n writeFileSync(stepRequestFile, \"\", { encoding: \"utf8\", mode: 0o600 });\n const agents = prepared.steps.map((step): AskAgentConfigFile => {\n const path = join(directory, `${step.role}.toml`);\n writeFileSync(path, renderAskAgentToml(prepared, step, requestFile, stepRequestFile), { encoding: \"utf8\", mode: 0o600 });\n return { role: step.role, path, model: step.model, tools: [...step.enabledTools] };\n });\n const parentConfig: Record<string, unknown> = {\n \"shell_environment_policy.inherit\": \"none\",\n project_doc_max_bytes: 0,\n project_root_markers: [],\n web_search: \"disabled\",\n // Current Codex collaboration tools are invoked through code-mode exec.\n // The parent has no business MCP servers and every non-collaboration\n // surface remains disabled below, so this only exposes the IR driver.\n \"features.code_mode.enabled\": true,\n \"features.multi_agent\": true,\n \"agents.enabled\": true,\n // Codex applies this as the total spawned-thread capacity for the session.\n // Warble enforces sequential spawn -> wait ordering in the event validator.\n \"agents.max_concurrent_threads_per_session\": prepared.steps.length,\n ...Object.fromEntries(\n ASK_DISABLED_FEATURES.map((feature) => [`features.${feature}`, false]),\n ),\n };\n for (const agent of agents) {\n parentConfig[`agents.${agent.role}.description`] =\n `Execute only the Warble step mapped to ${agent.role}`;\n parentConfig[`agents.${agent.role}.config_file`] = agent.path;\n }\n return {\n directory,\n requestFile,\n stepRequestFile,\n agents,\n parentConfig,\n bindRequest: (request) => writeFileSync(requestFile, request, { encoding: \"utf8\", mode: 0o600 }),\n bindStepRequest: (request) => writeFileSync(stepRequestFile, request, { encoding: \"utf8\", mode: 0o600 }),\n cleanup: () => rmSync(directory, { recursive: true, force: true }),\n };\n } catch (error) {\n rmSync(directory, { recursive: true, force: true });\n throw error;\n }\n}\n","import type { WarbleCodexEvent } from \"./events.js\";\n\nexport const SESSION_REFERENCE_VERSION = \"0.1\" as const;\n\nexport interface CodexSessionReference {\n version: typeof SESSION_REFERENCE_VERSION;\n target: \"codex:local\";\n threadId: string;\n forkedFromThreadId: string | null;\n}\n\nexport type SessionTurnStatus = \"in_progress\" | \"completed\" | \"interrupted\" | \"failed\";\n\nexport interface CodexTurnReference {\n threadId: string;\n turnId: string;\n status: SessionTurnStatus;\n}\n\nexport interface CodexArtifactReference {\n version: typeof SESSION_REFERENCE_VERSION;\n kind: \"mcp_tool_result\";\n threadId: string;\n turnId: string;\n itemId: string;\n server: string;\n tool: string;\n ok: boolean;\n}\n\nexport type CodexHistoryItem =\n | { type: \"user\" | \"assistant\"; itemId: string }\n | { type: \"artifact\"; reference: CodexArtifactReference };\n\nexport interface CodexHistoryTurn {\n id: string;\n status: SessionTurnStatus;\n items: CodexHistoryItem[];\n}\n\nexport interface CodexSessionHistory {\n session: CodexSessionReference;\n turns: CodexHistoryTurn[];\n}\n\nexport type CodexSessionEvent =\n | { t: \"session_started\" | \"session_resumed\" | \"session_forked\"; session: CodexSessionReference }\n | { t: \"session_recoverable\"; threadId: string | null; reason: \"transport_disconnect\" | \"app_server_crash\" | \"turn_timeout\" }\n | { t: \"session_failed\"; threadId: string | null; reason: \"protocol_violation\" }\n | { t: \"turn_started\"; turn: CodexTurnReference }\n | { t: \"turn_completed\"; turn: CodexTurnReference }\n | { t: \"artifact\"; reference: CodexArtifactReference }\n | ({ threadId: string; turnId: string } & WarbleCodexEvent);\n\nexport interface SessionIsolationOptions {\n codexHome: string;\n cwd: string;\n externalAuthentication: \"provisioned\";\n codexBin?: string;\n codexArgsPrefix?: string[];\n timeoutMs?: number;\n terminationGraceMs?: number;\n env?: NodeJS.ProcessEnv;\n onEvent?: (event: CodexSessionEvent) => void;\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport { CodexAppServerTransport } from \"./app_server_transport.js\";\nimport {\n buildAskAppServerArgs,\n createAskAgentConfigBundle,\n type AskAgentConfigBundle,\n} from \"./ask_config.js\";\nimport type { PreparedAskComponent, PreparedAskStep } from \"./ask_prepare.js\";\nimport {\n SESSION_REFERENCE_VERSION,\n type CodexSessionReference,\n type CodexTurnReference,\n type SessionIsolationOptions,\n} from \"./session_types.js\";\nimport { validateDashboardRenderEnvelope } from \"./render_contract.js\";\nimport {\n REQUEST_TRANSPORT_SERVER,\n REQUEST_TRANSPORT_TOOL,\n STEP_TRANSPORT_TOOL,\n} from \"./request_transport.js\";\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\nexport interface CodexAskStepResult {\n step: string;\n agentRole: string;\n agentThreadId: string;\n model: string;\n produced: string;\n ok: boolean;\n value: unknown;\n artifacts: CodexAskArtifactReference[];\n}\n\nexport interface CodexAskArtifactReference {\n version: typeof SESSION_REFERENCE_VERSION;\n kind: \"mcp_tool_result\";\n parentThreadId: string;\n parentTurnId: string;\n agentThreadId: string;\n step: string;\n agentRole: string;\n itemId: string;\n server: string;\n tool: string;\n ok: boolean;\n}\n\nexport interface CodexRenderArtifactReference {\n version: typeof SESSION_REFERENCE_VERSION;\n kind: \"render_envelope\";\n parentThreadId: string;\n parentTurnId: string;\n agentThreadId: string;\n step: string;\n agentRole: string;\n verified: boolean;\n blockTypes: string[];\n}\n\nexport type CodexAskEvent =\n | { t: \"session_started\" | \"session_resumed\"; session: CodexSessionReference }\n | { t: \"turn_started\" | \"turn_completed\"; turn: CodexTurnReference }\n | {\n t: \"agent_started\";\n parentThreadId: string;\n parentTurnId: string;\n step: string;\n agentRole: string;\n agentThreadId: string;\n model: string;\n }\n | {\n t: \"step_finished\";\n parentThreadId: string;\n parentTurnId: string;\n step: string;\n agentRole: string;\n agentThreadId: string;\n ok: boolean;\n }\n | { t: \"artifact\"; reference: CodexAskArtifactReference }\n | { t: \"render_artifact\"; reference: CodexRenderArtifactReference }\n | {\n t: \"render_degraded\";\n parentThreadId: string;\n parentTurnId: string;\n reason: \"invalid_render_envelope\";\n }\n | {\n t: \"session_recoverable\";\n threadId: string | null;\n reason: \"transport_disconnect\" | \"app_server_crash\" | \"turn_timeout\" | \"turn_cancelled\";\n }\n | { t: \"session_failed\"; threadId: string | null; reason: \"protocol_violation\" };\n\nexport interface CodexAskRuntimeOptions extends SessionIsolationOptions {\n turnTimeoutMs?: number;\n onAskEvent?: (event: CodexAskEvent) => void;\n}\n\nexport interface CodexAskRunResult {\n target: \"codex:local\";\n component: string;\n session: CodexSessionReference;\n turn: CodexTurnReference;\n finalText: string;\n value: unknown;\n steps: CodexAskStepResult[];\n artifact: CodexRenderArtifactReference | null;\n renderDegraded: boolean;\n}\n\ninterface SpawnRecord {\n callId: string;\n expected: PreparedAskStep;\n agentThreadId: string | null;\n model: string | null;\n prompt: string | null;\n stepRequest: string;\n waited: boolean;\n}\n\ninterface ActiveRun {\n threadId: string;\n turnId: string;\n started: boolean;\n completed: boolean;\n status: CodexTurnReference[\"status\"];\n spawns: SpawnRecord[];\n pendingItems: Map<string, string>;\n pendingChildThreadIds: Set<string>;\n pendingChildCompletedIds: Set<string>;\n deferredWaitItems: JsonRecord[];\n stepRequests: Array<string | undefined>;\n slots: Record<string, unknown>;\n childAnswers: Map<string, string>;\n finalText: string | null;\n deferredTurnCompletion: CodexTurnReference | null;\n stopReason: \"turn_timeout\" | \"turn_cancelled\" | null;\n stopCompleted: (() => void) | null;\n resolve: () => void;\n reject: (error: Error) => void;\n}\n\ninterface StepEnvelope {\n warble_step: string;\n produces: string;\n ok: boolean;\n value: unknown;\n error: string | null;\n}\n\ninterface AnswerQueryValue {\n columns: string[];\n rows: unknown[];\n summary: string;\n verified: true;\n definition: {\n sql: string;\n source_tables: string[];\n filters: unknown[];\n };\n}\n\nconst PASSIVE_PARENT_ITEMS = new Set([\n \"userMessage\",\n \"agentMessage\",\n \"reasoning\",\n \"plan\",\n \"subAgentActivity\",\n \"contextCompaction\",\n]);\n\nconst IGNORED_NOTIFICATIONS = new Set([\n \"thread/started\",\n \"thread/status/changed\",\n \"thread/tokenUsage/updated\",\n \"turn/plan/updated\",\n \"item/agentMessage/delta\",\n \"item/plan/delta\",\n \"item/reasoning/summaryTextDelta\",\n \"item/reasoning/summaryPartAdded\",\n \"item/reasoning/textDelta\",\n \"skills/changed\",\n \"mcpServer/startupStatus/updated\",\n \"account/updated\",\n \"account/rateLimits/updated\",\n \"remoteControl/status/changed\",\n \"model/rerouted\",\n \"configWarning\",\n \"warning\",\n]);\n\nconst CHILD_THREAD_NOTIFICATIONS = new Set([\n \"turn/started\",\n \"item/started\",\n \"item/completed\",\n \"turn/completed\",\n]);\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction record(value: unknown, context: string): JsonRecord {\n if (!isRecord(value)) throw new CodexDispatchError(`${context} requires an object`);\n return value;\n}\n\nfunction string(recordValue: JsonRecord, key: string, context: string): string {\n const value = recordValue[key];\n if (typeof value !== \"string\" || value.length === 0) {\n throw new CodexDispatchError(`${context} requires string ${key}`);\n }\n return value;\n}\n\nfunction sessionReference(thread: JsonRecord): CodexSessionReference {\n return {\n version: SESSION_REFERENCE_VERSION,\n target: \"codex:local\",\n threadId: string(thread, \"id\", \"thread\"),\n forkedFromThreadId:\n typeof thread[\"forkedFromId\"] === \"string\" ? thread[\"forkedFromId\"] : null,\n };\n}\n\nfunction turnStatus(value: unknown): CodexTurnReference[\"status\"] {\n switch (value) {\n case \"inProgress\":\n return \"in_progress\";\n case \"completed\":\n case \"interrupted\":\n case \"failed\":\n return value;\n default:\n throw new CodexDispatchError(\"turn requires a recognized status\");\n }\n}\n\nfunction turnReference(threadId: string, value: unknown): CodexTurnReference {\n const turn = record(value, \"turn\");\n return { threadId, turnId: string(turn, \"id\", \"turn\"), status: turnStatus(turn[\"status\"]) };\n}\n\nfunction validateReference(reference: CodexSessionReference): void {\n if (\n reference.version !== SESSION_REFERENCE_VERSION ||\n reference.target !== \"codex:local\" ||\n reference.threadId.length === 0\n ) {\n throw new CodexDispatchError(\"invalid codex session reference\");\n }\n}\n\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (isRecord(value)) {\n return `{${Object.keys(value)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value);\n}\n\nfunction parseEnvelope(text: string, step: PreparedAskStep): StepEnvelope {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n throw new CodexDispatchError(`agent '${step.role}' returned a non-JSON step envelope`);\n }\n const envelope = record(value, `agent '${step.role}' envelope`);\n const keys = Object.keys(envelope).sort();\n const expectedKeys = [\"error\", \"ok\", \"produces\", \"value\", \"warble_step\"];\n if (canonical(keys) !== canonical(expectedKeys)) {\n throw new CodexDispatchError(`agent '${step.role}' returned an unexpected envelope shape`);\n }\n if (\n envelope[\"warble_step\"] !== step.name ||\n envelope[\"produces\"] !== step.produces ||\n typeof envelope[\"ok\"] !== \"boolean\" ||\n (envelope[\"error\"] !== null && typeof envelope[\"error\"] !== \"string\")\n ) {\n throw new CodexDispatchError(`agent '${step.role}' returned a mismatched step envelope`);\n }\n if (envelope[\"ok\"] === true && envelope[\"error\"] !== null) {\n throw new CodexDispatchError(`agent '${step.role}' marked success with an error`);\n }\n if (\n envelope[\"ok\"] === false &&\n (typeof envelope[\"error\"] !== \"string\" || envelope[\"error\"].trim().length === 0)\n ) {\n throw new CodexDispatchError(`agent '${step.role}' marked failure without an error`);\n }\n return envelope as unknown as StepEnvelope;\n}\n\nfunction validateAnswerQueryValue(value: unknown): AnswerQueryValue {\n const answer = record(value, \"answer_query final value\");\n if (\n canonical(Object.keys(answer).sort()) !==\n canonical([\"columns\", \"definition\", \"rows\", \"summary\", \"verified\"])\n ) {\n throw new CodexDispatchError(\"answer_query success requires the canonical rich result shape\");\n }\n const definition = record(answer[\"definition\"], \"answer_query definition\");\n if (\n canonical(Object.keys(definition).sort()) !==\n canonical([\"filters\", \"source_tables\", \"sql\"])\n ) {\n throw new CodexDispatchError(\"answer_query success requires complete run provenance\");\n }\n if (\n !Array.isArray(answer[\"columns\"]) ||\n !answer[\"columns\"].every((column) => typeof column === \"string\" && column.length > 0) ||\n !Array.isArray(answer[\"rows\"]) ||\n typeof answer[\"summary\"] !== \"string\" ||\n answer[\"summary\"].trim().length === 0 ||\n answer[\"verified\"] !== true ||\n typeof definition[\"sql\"] !== \"string\" ||\n definition[\"sql\"].trim().length === 0 ||\n !Array.isArray(definition[\"source_tables\"]) ||\n !definition[\"source_tables\"].every(\n (table) => typeof table === \"string\" && table.length > 0,\n ) ||\n !Array.isArray(definition[\"filters\"])\n ) {\n throw new CodexDispatchError(\n \"answer_query success requires a grounded summary, verification, and complete run provenance\",\n );\n }\n return answer as unknown as AnswerQueryValue;\n}\n\nfunction parseStepRequest(text: string, step: PreparedAskStep): JsonRecord {\n const prefix = \"WARBLE_STEP_REQUEST\\n\";\n if (!text.startsWith(prefix)) {\n throw new CodexDispatchError(`agent '${step.role}' input lacks the Warble step envelope`);\n }\n let value: unknown;\n try {\n value = JSON.parse(text.slice(prefix.length));\n } catch {\n throw new CodexDispatchError(`agent '${step.role}' input has malformed JSON`);\n }\n const request = record(value, `agent '${step.role}' input`);\n const keys = Object.keys(request).sort();\n if (\n canonical(keys) !== canonical([\"inputs\", \"step\"]) ||\n request[\"step\"] !== step.name ||\n !isRecord(request[\"inputs\"])\n ) {\n throw new CodexDispatchError(`agent '${step.role}' input does not match its IR step`);\n }\n return request;\n}\n\nfunction buildStepRequest(step: PreparedAskStep, slots: Record<string, unknown>): string {\n return `WARBLE_STEP_REQUEST\\n${JSON.stringify({\n step: step.name,\n inputs: Object.fromEntries(step.consumes.map((slot) => [slot, slots[slot]])),\n })}`;\n}\n\n/**\n * Minimum/maximum spawn count implied purely by the prepared step chain: every unconditional\n * step is required (contributes to the floor), every step (unconditional or repair) contributes\n * to the ceiling. Shared by validateChildren and synthesizeDirectCollaboration so the two never\n * drift onto independent hardcoded bounds.\n */\nfunction stepCountBounds(steps: readonly PreparedAskStep[]): {\n minimumSteps: number;\n maximumSteps: number;\n} {\n return {\n minimumSteps: steps.filter((step) => !step.conditional).length,\n maximumSteps: steps.length,\n };\n}\n\n/**\n * Maps each step name to the step that repairs it, derived purely from IR-declared adjacency:\n * step[i] repairs step[i-1] when step[i].conditional and step[i].when.target === step[i-1].name.\n * A step with no entry in this map is \"required\" — validateStepChain guarantees no unconditional\n * step follows a repair, so this scan never needs to look past the immediate predecessor.\n */\nfunction repairersByTarget(steps: readonly PreparedAskStep[]): Map<string, PreparedAskStep> {\n const map = new Map<string, PreparedAskStep>();\n for (let index = 1; index < steps.length; index += 1) {\n const step = steps[index]!;\n const previous = steps[index - 1]!;\n if (step.conditional && step.when?.target === previous.name) {\n map.set(previous.name, step);\n }\n }\n return map;\n}\n\nexport function buildAskDriverPrompt(prepared: PreparedAskComponent): string {\n const steps = prepared.steps.map((step, index) => {\n const inputDescription =\n step.consumes.length === 0\n ? \"an empty inputs object\"\n : `inputs containing only ${step.consumes.join(\", \")} copied exactly from the prior agent value`;\n return `${index + 1}. Spawn agent_type=${step.role} for step=${step.name} with ${inputDescription}. Wait for it before any later spawn.`;\n });\n const repairers = repairersByTarget(prepared.steps);\n const repairRules = prepared.steps.flatMap((step) => {\n const repairer = repairers.get(step.name);\n if (repairer === undefined) return [];\n return [\n `If '${step.name}' returns ok=true, do not spawn '${repairer.role}'.`,\n `If it returns ok=false, spawn '${repairer.role}' exactly once; if repair fails, fail loudly.`,\n ];\n });\n const producesRenderEnvelope = prepared.executionKind === \"generate_dashboard\";\n const executionRules = producesRenderEnvelope\n ? [\n \"Every declared step is required. If any child returns ok=false, fail loudly and stop.\",\n \"Do not write files in the parent or children; the final validated render envelope is the consumer-persistable artifact output.\",\n ...repairRules,\n ]\n : repairRules;\n return [\n `Execute Warble component '${prepared.componentId}' by named child-agent delegation only.`,\n \"Do not perform any IR step in the parent and do not use business MCP tools in the parent.\",\n \"Use Codex's direct collaboration tools for every spawn and wait. Call spawn_agent and wait_agent as tool calls; do not invoke collaboration through exec or code mode.\",\n 'Select the exact custom agent type named for each step and send the exact child message below. Give the spawn a short unique task name when the current tool schema requires one.',\n \"Do not override the child model or reasoning effort, and do not fork the parent conversation into the child. After each spawn, wait for that child to complete before any later spawn.\",\n `The dispatcher supplies the authoritative original request directly to each child through ${REQUEST_TRANSPORT_SERVER}.${REQUEST_TRANSPORT_TOOL}; never copy, summarize, or include the request in a child message.`,\n \"For every child, send exactly this message:\",\n \"WARBLE_STEP_REQUEST\",\n '{\"step\":\"<step>\",\"inputs\":{\"<slot>\":<prior value>}}',\n \"The JSON object must contain only step and inputs. Never add the original request, a request summary, or any extra field.\",\n \"Each child returns a JSON envelope. Copy its value exactly into the next declared input slot.\",\n \"Spawn without an explicit model override: the named custom-agent config owns the model.\",\n \"\",\n ...steps,\n \"\",\n ...executionRules,\n \"Do not copy the final child value into the parent response; large structured values must remain authoritative in the child thread.\",\n 'Your final message must be exactly {\"warble_final_step\":\"<actual final successful step name>\",\"ok\":true} with no prose.',\n ].join(\"\\n\");\n}\n\nexport class CodexAskRuntime {\n private transport!: CodexAppServerTransport;\n private bundle!: AskAgentConfigBundle;\n private session: CodexSessionReference | null = null;\n private active: ActiveRun | null = null;\n private startingTurn = false;\n private pendingTurnNotifications: Array<readonly [method: string, params: unknown]> = [];\n private disconnected = false;\n\n private constructor(\n private readonly prepared: PreparedAskComponent,\n private readonly options: CodexAskRuntimeOptions,\n ) {}\n\n static async connect(\n prepared: PreparedAskComponent,\n options: CodexAskRuntimeOptions,\n ): Promise<CodexAskRuntime> {\n const runtime = new CodexAskRuntime(prepared, options);\n runtime.bundle = createAskAgentConfigBundle(prepared);\n try {\n runtime.transport = await CodexAppServerTransport.startWithArgs(\n [...(options.codexArgsPrefix ?? []), ...buildAskAppServerArgs(runtime.bundle)],\n options,\n (method, params) => runtime.onNotification(method, params),\n (error) => runtime.onDisconnect(error),\n );\n return runtime;\n } catch (error) {\n runtime.bundle.cleanup();\n throw error;\n }\n }\n\n async start(): Promise<CodexSessionReference> {\n this.ensureConnected();\n if (this.session !== null) throw new CodexDispatchError(\"an Ask session is already loaded\");\n const result = record(\n await this.transport.request(\"thread/start\", {\n model: this.prepared.models.orchestrator,\n cwd: this.options.cwd,\n approvalPolicy: \"never\",\n sandbox: \"read-only\",\n config: this.bundle.parentConfig,\n ephemeral: false,\n historyMode: \"legacy\",\n environments: [],\n runtimeWorkspaceRoots: [],\n selectedCapabilityRoots: [],\n dynamicTools: [],\n experimentalRawEvents: false,\n }),\n \"thread/start response\",\n );\n this.session = sessionReference(record(result[\"thread\"], \"thread/start thread\"));\n this.emit({ t: \"session_started\", session: this.session });\n return this.session;\n }\n\n async resume(reference: CodexSessionReference): Promise<CodexSessionReference> {\n validateReference(reference);\n this.ensureConnected();\n if (this.active !== null) throw new CodexDispatchError(\"cannot resume while an Ask turn is active\");\n const result = record(\n await this.transport.request(\"thread/resume\", {\n threadId: reference.threadId,\n model: this.prepared.models.orchestrator,\n cwd: this.options.cwd,\n approvalPolicy: \"never\",\n sandbox: \"read-only\",\n config: this.bundle.parentConfig,\n runtimeWorkspaceRoots: [],\n }),\n \"thread/resume response\",\n );\n const resumed = sessionReference(record(result[\"thread\"], \"thread/resume thread\"));\n if (resumed.threadId !== reference.threadId) {\n throw new CodexDispatchError(\"thread/resume returned a different thread id\");\n }\n this.session = resumed;\n this.emit({ t: \"session_resumed\", session: resumed });\n return resumed;\n }\n\n async run(\n reference: CodexSessionReference,\n request: string,\n signal?: AbortSignal,\n ): Promise<CodexAskRunResult> {\n validateReference(reference);\n this.ensureConnected();\n if (this.session?.threadId !== reference.threadId) {\n throw new CodexDispatchError(\"Ask session reference is not loaded; resume it first\");\n }\n if (this.active !== null) throw new CodexDispatchError(\"an Ask turn is already active\");\n if (request.trim().length === 0) throw new CodexDispatchError(\"Ask request must not be empty\");\n if (signal?.aborted) throw new CodexDispatchError(\"Ask turn was cancelled before start\");\n let resolveRun!: () => void;\n let rejectRun!: (error: Error) => void;\n const completion = new Promise<void>((resolve, reject) => {\n resolveRun = resolve;\n rejectRun = reject;\n });\n let turn: CodexTurnReference;\n this.startingTurn = true;\n this.pendingTurnNotifications = [];\n try {\n this.bundle.bindRequest(request);\n const initialStepRequest = buildStepRequest(this.prepared.steps[0]!, {});\n this.bundle.bindStepRequest(initialStepRequest);\n const result = record(\n await this.transport.request(\"turn/start\", {\n threadId: reference.threadId,\n input: [{ type: \"text\", text: buildAskDriverPrompt(this.prepared), text_elements: [] }],\n approvalPolicy: \"never\",\n environments: [],\n runtimeWorkspaceRoots: [],\n }),\n \"turn/start response\",\n );\n turn = turnReference(reference.threadId, result[\"turn\"]);\n if (turn.status !== \"in_progress\") {\n throw new CodexDispatchError(\"turn/start did not return an in-progress turn\");\n }\n this.active = {\n threadId: reference.threadId,\n turnId: turn.turnId,\n started: false,\n completed: false,\n status: \"in_progress\",\n spawns: [],\n pendingItems: new Map(),\n pendingChildThreadIds: new Set(),\n pendingChildCompletedIds: new Set(),\n deferredWaitItems: [],\n stepRequests: [initialStepRequest],\n slots: {},\n childAnswers: new Map(),\n finalText: null,\n deferredTurnCompletion: null,\n stopReason: null,\n stopCompleted: null,\n resolve: resolveRun,\n reject: rejectRun,\n };\n } catch (error) {\n this.startingTurn = false;\n this.pendingTurnNotifications = [];\n throw error;\n }\n this.startingTurn = false;\n const pendingNotifications = this.pendingTurnNotifications;\n this.pendingTurnNotifications = [];\n for (const [method, params] of pendingNotifications) {\n this.onNotification(method, params);\n }\n const timeoutMs = this.options.turnTimeoutMs ?? 120_000;\n const timer = setTimeout(() => {\n void this.stopTurn(turn, \"turn_timeout\");\n }, timeoutMs);\n const cancel = (): void => {\n void this.stopTurn(turn, \"turn_cancelled\");\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n if (signal?.aborted) cancel();\n try {\n await completion;\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", cancel);\n const active = this.active;\n if (active === null || active.turnId !== turn.turnId) {\n throw new CodexDispatchError(\"Ask turn state was displaced\");\n }\n const steps = await this.validateChildren(active);\n const finalStep = steps.at(-1);\n if (!finalStep?.ok) throw new CodexDispatchError(\"Ask run has no successful final step\");\n if (!isRecord(finalStep.value)) {\n throw new CodexDispatchError(\"Ask final value must be a JSON object\");\n }\n let parentFinal: unknown;\n try {\n parentFinal = JSON.parse(active.finalText ?? \"\");\n } catch {\n throw new CodexDispatchError(\"Ask parent final message is not JSON\");\n }\n const expectedReceipt = { warble_final_step: finalStep.step, ok: true };\n if (canonical(parentFinal) !== canonical(expectedReceipt)) {\n throw new CodexDispatchError(\"Ask parent final message does not match the final child receipt\");\n }\n let artifact: CodexRenderArtifactReference | null = null;\n let renderDegraded = false;\n let finalValue: unknown = finalStep.value;\n if (this.prepared.executionKind === \"answer_query\") {\n finalValue = validateAnswerQueryValue(finalStep.value);\n finalStep.value = finalValue;\n } else {\n try {\n const envelope = validateDashboardRenderEnvelope(finalStep.value, this.prepared.node);\n finalValue = envelope;\n finalStep.value = envelope;\n artifact = {\n version: SESSION_REFERENCE_VERSION,\n kind: \"render_envelope\",\n parentThreadId: active.threadId,\n parentTurnId: active.turnId,\n agentThreadId: finalStep.agentThreadId,\n step: finalStep.step,\n agentRole: finalStep.agentRole,\n verified: envelope.verified,\n blockTypes: envelope.blocks.map((block) => String(block[\"type\"])),\n };\n this.emit({ t: \"render_artifact\", reference: artifact });\n } catch (error) {\n if (!(error instanceof CodexDispatchError)) throw error;\n renderDegraded = true;\n this.emit({\n t: \"render_degraded\",\n parentThreadId: active.threadId,\n parentTurnId: active.turnId,\n reason: \"invalid_render_envelope\",\n });\n }\n }\n const completed: CodexTurnReference = {\n threadId: active.threadId,\n turnId: active.turnId,\n status: active.status,\n };\n this.emit({ t: \"turn_completed\", turn: completed });\n return {\n target: \"codex:local\",\n component: this.prepared.componentId,\n session: reference,\n turn: completed,\n finalText: JSON.stringify(finalValue),\n value: finalValue,\n steps,\n artifact,\n renderDegraded,\n };\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", cancel);\n this.startingTurn = false;\n this.pendingTurnNotifications = [];\n this.active = null;\n }\n }\n\n async restartAndResume(reference: CodexSessionReference): Promise<CodexSessionReference> {\n if (this.active !== null) throw new CodexDispatchError(\"cannot restart while an Ask turn is active\");\n await this.transport.close();\n this.transport = await CodexAppServerTransport.startWithArgs(\n [...(this.options.codexArgsPrefix ?? []), ...buildAskAppServerArgs(this.bundle)],\n this.options,\n (method, params) => this.onNotification(method, params),\n (error) => this.onDisconnect(error),\n );\n this.disconnected = false;\n try {\n return await this.resume(reference);\n } catch (error) {\n this.disconnected = true;\n await this.transport.close();\n throw error;\n }\n }\n\n async close(): Promise<void> {\n this.disconnected = true;\n this.active?.reject(new CodexDispatchError(\"Ask runtime closed during an active turn\"));\n this.active = null;\n await this.transport.close();\n this.bundle.cleanup();\n }\n\n private onNotification(method: string, paramsValue: unknown): void {\n try {\n if (IGNORED_NOTIFICATIONS.has(method)) return;\n const params = record(paramsValue, `${method} notification`);\n if (this.active === null && this.startingTurn) {\n this.pendingTurnNotifications.push([method, paramsValue]);\n return;\n }\n if (method === \"error\") {\n if (params[\"willRetry\"] === true) return;\n throw new CodexDispatchError(\"app-server reported a terminal Ask error\");\n }\n const active = this.active;\n if (active === null) throw new CodexDispatchError(`unexpected '${method}' without an active Ask turn`);\n const notificationThreadId = params[\"threadId\"];\n if (\n typeof notificationThreadId === \"string\" &&\n notificationThreadId !== active.threadId\n ) {\n const knownChild = active.spawns.some(\n (spawn) => spawn.agentThreadId === notificationThreadId,\n );\n if (knownChild && CHILD_THREAD_NOTIFICATIONS.has(method)) {\n this.observeChildNotification(method, params, active, notificationThreadId);\n return;\n }\n // Codex 0.146 can begin a child turn before completing the parent's\n // spawnAgent item. Buffer only the foreign thread identity until that\n // completion attributes exactly one receiver; no child content is\n // consumed here, and an unmatched identity still fails closed.\n if (\n CHILD_THREAD_NOTIFICATIONS.has(method) &&\n active.spawns.length < this.prepared.steps.length\n ) {\n active.pendingChildThreadIds.add(notificationThreadId);\n this.observeChildNotification(method, params, active, notificationThreadId);\n if (method === \"turn/completed\") {\n active.pendingChildCompletedIds.add(notificationThreadId);\n }\n if (active.pendingChildThreadIds.size > this.prepared.steps.length - active.spawns.length) {\n throw new CodexDispatchError(\"Ask received too many unattributed child threads\");\n }\n return;\n }\n throw new CodexDispatchError(\"Ask notification belongs to an unknown thread\");\n }\n if (method === \"turn/started\") {\n const turn = turnReference(string(params, \"threadId\", method), params[\"turn\"]);\n if (turn.threadId !== active.threadId || turn.turnId !== active.turnId || active.started) {\n throw new CodexDispatchError(\"Ask turn start notification does not match active state\");\n }\n active.started = true;\n this.emit({ t: \"turn_started\", turn });\n return;\n }\n if (method === \"item/started\" || method === \"item/completed\") {\n this.onItem(method, params, active);\n this.tryFinalizeTurn(active);\n return;\n }\n if (method === \"turn/completed\") {\n const turn = turnReference(string(params, \"threadId\", method), params[\"turn\"]);\n if (!active.started || turn.threadId !== active.threadId || turn.turnId !== active.turnId) {\n throw new CodexDispatchError(\"Ask turn completion does not match active state\");\n }\n if (active.stopReason !== null && turn.status === \"interrupted\") {\n active.completed = true;\n active.status = turn.status;\n active.stopCompleted?.();\n return;\n }\n if (turn.status !== \"completed\" || active.finalText === null) {\n throw new CodexDispatchError(\"Ask parent turn did not complete with a final answer\");\n }\n this.synthesizeDirectCollaboration(active);\n // Codex 0.146 may publish the parent turn completion before the\n // delayed spawnAgent/wait item completions that attribute children.\n // Retain the terminal turn and finalize as soon as those bounded,\n // ordered collaboration records arrive.\n active.deferredTurnCompletion = turn;\n this.tryFinalizeTurn(active);\n return;\n }\n throw new CodexDispatchError(`unsupported app-server notification '${method}'`);\n } catch (error) {\n const failure = error instanceof Error ? error : new Error(String(error));\n this.active?.reject(failure);\n this.onDisconnect(\n failure instanceof CodexDispatchError ? failure : new CodexDispatchError(failure.message),\n );\n void this.transport.close();\n }\n }\n\n private onItem(\n method: \"item/started\" | \"item/completed\",\n params: JsonRecord,\n active: ActiveRun,\n ): void {\n if (string(params, \"threadId\", method) !== active.threadId || string(params, \"turnId\", method) !== active.turnId) {\n throw new CodexDispatchError(\"Ask item belongs to a different parent turn\");\n }\n const item = record(params[\"item\"], `${method} item`);\n const type = string(item, \"type\", `${method} item`);\n if (type === \"collabAgentToolCall\") {\n this.onCollabItem(method, item, active);\n return;\n }\n if (!PASSIVE_PARENT_ITEMS.has(type)) {\n throw new CodexDispatchError(`isolation violation: Ask parent emitted forbidden '${type}'`);\n }\n if (method === \"item/completed\" && type === \"agentMessage\") {\n active.finalText = string(item, \"text\", type);\n }\n }\n\n private observeChildNotification(\n method: string,\n params: JsonRecord,\n active: ActiveRun,\n childThreadId: string,\n ): void {\n if (method !== \"item/completed\") return;\n const item = record(params[\"item\"], \"child item/completed item\");\n if (item[\"type\"] !== \"agentMessage\") return;\n if (active.childAnswers.has(childThreadId)) {\n throw new CodexDispatchError(\"Ask child emitted more than one final answer\");\n }\n const answer = string(item, \"text\", \"child agentMessage\");\n active.childAnswers.set(childThreadId, answer);\n const knownIndex = active.spawns.findIndex((spawn) => spawn.agentThreadId === childThreadId);\n const pendingIndex = [...active.pendingChildThreadIds].indexOf(childThreadId);\n const stepIndex = knownIndex >= 0 ? knownIndex : active.spawns.length + pendingIndex;\n const step = this.prepared.steps[stepIndex];\n if (!step) throw new CodexDispatchError(\"Ask child answer has no IR step attribution\");\n const envelope = parseEnvelope(answer, step);\n active.slots[step.produces] = envelope.value;\n const next = this.prepared.steps[stepIndex + 1];\n const repairers = repairersByTarget(this.prepared.steps);\n const isRecoverable = repairers.has(step.name);\n const shouldPrepareNext = next !== undefined && (isRecoverable ? !envelope.ok : envelope.ok);\n if (!shouldPrepareNext || next === undefined) return;\n const request = buildStepRequest(next, active.slots);\n active.stepRequests[stepIndex + 1] = request;\n this.bundle.bindStepRequest(request);\n }\n\n private onCollabItem(\n method: \"item/started\" | \"item/completed\",\n item: JsonRecord,\n active: ActiveRun,\n ): void {\n const id = string(item, \"id\", \"collaboration item\");\n const tool = string(item, \"tool\", \"collaboration item\");\n if (tool !== \"spawnAgent\" && tool !== \"wait\") {\n throw new CodexDispatchError(`Ask parent used unsupported collaboration tool '${tool}'`);\n }\n if (method === \"item/started\") {\n if (item[\"status\"] !== \"inProgress\" || active.pendingItems.has(id)) {\n throw new CodexDispatchError(\"collaboration item has an invalid start state\");\n }\n active.pendingItems.set(id, tool);\n return;\n }\n if (active.pendingItems.get(id) !== tool) {\n throw new CodexDispatchError(\"collaboration item completed without a matching start\");\n }\n active.pendingItems.delete(id);\n if (item[\"status\"] !== \"completed\") {\n throw new CodexDispatchError(`collaboration '${tool}' failed`);\n }\n if (tool === \"spawnAgent\") {\n const previous = active.spawns.at(-1);\n if (previous && !previous.waited) {\n throw new CodexDispatchError(\"Ask parent spawned the next agent before waiting for the prior one\");\n }\n const expected = this.prepared.steps[active.spawns.length];\n if (!expected) throw new CodexDispatchError(\"Ask parent spawned too many agents\");\n const receiverIds = item[\"receiverThreadIds\"];\n if (!Array.isArray(receiverIds) || receiverIds.length !== 1 || typeof receiverIds[0] !== \"string\") {\n throw new CodexDispatchError(\"spawnAgent must return exactly one child thread\");\n }\n const firstPendingChild = active.pendingChildThreadIds.values().next().value as string | undefined;\n if (firstPendingChild !== undefined && firstPendingChild !== receiverIds[0]) {\n throw new CodexDispatchError(\"spawnAgent attributed a different child thread than its notifications\");\n }\n if (firstPendingChild !== undefined) active.pendingChildThreadIds.delete(firstPendingChild);\n active.pendingChildCompletedIds.delete(receiverIds[0]);\n // Codex 0.146 reports `model: null` when the selected custom-agent\n // config owns the model. Older versions echoed the resolved model here.\n // A non-null value is an explicit override and must still match exactly;\n // the host-owned custom-agent layer is authoritative otherwise.\n const requestedModel = item[\"model\"];\n if (requestedModel !== null && requestedModel !== expected.model) {\n throw new CodexDispatchError(`agent '${expected.role}' ran on the wrong model`);\n }\n const stepRequest = active.stepRequests[active.spawns.length];\n if (stepRequest === undefined) {\n throw new CodexDispatchError(`agent '${expected.role}' spawned before its host input was ready`);\n }\n const spawn: SpawnRecord = {\n callId: id,\n expected,\n agentThreadId: receiverIds[0],\n model: expected.model,\n prompt: item[\"prompt\"] === null ? null : string(item, \"prompt\", \"spawnAgent\"),\n stepRequest,\n waited: false,\n };\n active.spawns.push(spawn);\n const deferred = active.deferredWaitItems.shift();\n if (deferred !== undefined) this.completeWait(deferred, active);\n return;\n }\n const current = active.spawns.at(-1);\n if (!current?.agentThreadId) {\n // Codex 0.146 may complete the direct wait_agent tool before the parent\n // spawnAgent item is delivered. Defer its attribution until that spawn\n // supplies the exact receiver thread id.\n if (active.deferredWaitItems.length >= this.prepared.steps.length - active.spawns.length) {\n throw new CodexDispatchError(\"too many waits completed before child attribution\");\n }\n active.deferredWaitItems.push(item);\n return;\n }\n this.completeWait(item, active);\n }\n\n private completeWait(item: JsonRecord, active: ActiveRun): void {\n const current = active.spawns.at(-1);\n if (!current?.agentThreadId || current.waited) {\n throw new CodexDispatchError(\"wait did not follow exactly one active child spawn\");\n }\n const receiverIds = item[\"receiverThreadIds\"];\n if (!Array.isArray(receiverIds) || receiverIds.length !== 1 || receiverIds[0] !== current.agentThreadId) {\n throw new CodexDispatchError(\"wait targeted a different child thread\");\n }\n const states = record(item[\"agentsStates\"], \"wait agentsStates\");\n const childState = record(states[current.agentThreadId], \"wait child state\");\n if (childState[\"status\"] !== \"completed\") {\n throw new CodexDispatchError(\"wait completed before the child agent succeeded\");\n }\n current.waited = true;\n }\n\n private tryFinalizeTurn(active: ActiveRun): void {\n const turn = active.deferredTurnCompletion;\n if (\n turn === null ||\n active.pendingItems.size > 0 ||\n active.pendingChildThreadIds.size > 0 ||\n active.deferredWaitItems.length > 0\n ) {\n return;\n }\n active.deferredTurnCompletion = null;\n active.completed = true;\n active.status = turn.status;\n active.resolve();\n }\n\n private synthesizeDirectCollaboration(active: ActiveRun): void {\n if (active.spawns.length > 0 || active.pendingChildThreadIds.size === 0) return;\n const childIds = [...active.pendingChildThreadIds];\n const { minimumSteps, maximumSteps } = stepCountBounds(this.prepared.steps);\n if (\n childIds.length < minimumSteps ||\n childIds.length > maximumSteps ||\n childIds.some((id) => !active.pendingChildCompletedIds.has(id))\n ) {\n throw new CodexDispatchError(\"direct collaboration children did not complete in the required sequence\");\n }\n if (active.deferredWaitItems.length !== childIds.length) {\n throw new CodexDispatchError(\"direct collaboration did not wait once for every child\");\n }\n active.spawns = childIds.map((agentThreadId, index) => {\n const stepRequest = active.stepRequests[index];\n if (stepRequest === undefined) {\n throw new CodexDispatchError(\"direct collaboration child spawned before its host input was ready\");\n }\n return {\n callId: `direct-${agentThreadId}`,\n expected: this.prepared.steps[index]!,\n agentThreadId,\n model: this.prepared.steps[index]!.model,\n prompt: null,\n stepRequest,\n waited: true,\n };\n });\n active.pendingChildThreadIds.clear();\n active.pendingChildCompletedIds.clear();\n active.deferredWaitItems = [];\n }\n\n private async validateChildren(active: ActiveRun): Promise<CodexAskStepResult[]> {\n const { minimumSteps, maximumSteps } = stepCountBounds(this.prepared.steps);\n if (\n active.spawns.length < minimumSteps ||\n active.spawns.length > maximumSteps ||\n active.spawns.some((spawn) => !spawn.waited)\n ) {\n throw new CodexDispatchError(\"Ask parent did not complete the required named-agent sequence\");\n }\n const results: CodexAskStepResult[] = [];\n const slots: Record<string, unknown> = {};\n const repairers = repairersByTarget(this.prepared.steps);\n for (const [index, spawn] of active.spawns.entries()) {\n const step = this.prepared.steps[index]!;\n if (spawn.expected !== step || spawn.agentThreadId === null || spawn.model !== step.model) {\n throw new CodexDispatchError(\"Ask child sequence does not match the IR\");\n }\n const child = record(\n await this.transport.request(\"thread/read\", {\n threadId: spawn.agentThreadId,\n includeTurns: true,\n }),\n \"child thread/read response\",\n );\n const thread = record(child[\"thread\"], \"child thread/read thread\");\n if (\n thread[\"id\"] !== spawn.agentThreadId ||\n thread[\"parentThreadId\"] !== active.threadId ||\n thread[\"agentRole\"] !== step.role\n ) {\n throw new CodexDispatchError(`child thread attribution failed for agent '${step.role}'`);\n }\n // Child artifacts are read and validated only after the parent turn completes.\n // Emit the public lifecycle after attribution succeeds and as one IR-ordered\n // unit instead of leaking the parent notification order (where a later spawn\n // can be observed before the prior child's deferred artifacts and finish).\n this.emit({\n t: \"agent_started\",\n parentThreadId: active.threadId,\n parentTurnId: active.turnId,\n step: step.name,\n agentRole: step.role,\n agentThreadId: spawn.agentThreadId,\n model: step.model,\n });\n const turns = thread[\"turns\"];\n if (!Array.isArray(turns) || turns.length !== 1) {\n throw new CodexDispatchError(`agent '${step.role}' must have exactly one turn`);\n }\n const turn = record(turns[0], `agent '${step.role}' turn`);\n if (turn[\"status\"] !== \"completed\" || !Array.isArray(turn[\"items\"])) {\n throw new CodexDispatchError(`agent '${step.role}' turn did not complete`);\n }\n let inputText: string | null = null;\n let answerText: string | null = null;\n const artifacts: CodexAskArtifactReference[] = [];\n let originalRequestCalls = 0;\n let stepRequestCalls = 0;\n let businessToolSeen = false;\n for (const itemValue of turn[\"items\"]) {\n const item = record(itemValue, `agent '${step.role}' item`);\n const type = string(item, \"type\", `agent '${step.role}' item`);\n if (type === \"userMessage\") {\n const content = item[\"content\"];\n if (!Array.isArray(content) || !isRecord(content[0]) || typeof content[0][\"text\"] !== \"string\") {\n throw new CodexDispatchError(`agent '${step.role}' user input is malformed`);\n }\n inputText = content[0][\"text\"];\n } else if (type === \"agentMessage\") {\n answerText = string(item, \"text\", `agent '${step.role}' answer`);\n } else if (type === \"mcpToolCall\") {\n const server = string(item, \"server\", \"child MCP item\");\n const tool = string(item, \"tool\", \"child MCP item\");\n const status = string(item, \"status\", \"child MCP item\");\n if (status !== \"completed\" && status !== \"failed\") {\n throw new CodexDispatchError(`agent '${step.role}' has an unfinished MCP tool`);\n }\n if (server === REQUEST_TRANSPORT_SERVER) {\n const successful =\n !businessToolSeen &&\n status === \"completed\" &&\n (item[\"error\"] === null || item[\"error\"] === undefined);\n if (tool === REQUEST_TRANSPORT_TOOL) {\n if (!successful || originalRequestCalls !== 0 || stepRequestCalls !== 0) {\n throw new CodexDispatchError(`agent '${step.role}' violated the original request transport contract`);\n }\n originalRequestCalls += 1;\n } else if (tool === STEP_TRANSPORT_TOOL) {\n if (!successful || originalRequestCalls !== 1 || stepRequestCalls !== 0) {\n throw new CodexDispatchError(`agent '${step.role}' violated the step request transport contract`);\n }\n stepRequestCalls += 1;\n } else {\n throw new CodexDispatchError(`agent '${step.role}' used an unknown request transport tool`);\n }\n continue;\n }\n if (server !== this.prepared.mcp.name || !step.enabledTools.includes(tool)) {\n throw new CodexDispatchError(`agent '${step.role}' used a non-allowlisted MCP tool`);\n }\n businessToolSeen = true;\n const reference: CodexAskArtifactReference = {\n version: SESSION_REFERENCE_VERSION,\n kind: \"mcp_tool_result\",\n parentThreadId: active.threadId,\n parentTurnId: active.turnId,\n agentThreadId: spawn.agentThreadId,\n step: step.name,\n agentRole: step.role,\n itemId: string(item, \"id\", \"child MCP item\"),\n server,\n tool,\n ok: status === \"completed\" && (item[\"error\"] === null || item[\"error\"] === undefined),\n };\n artifacts.push(reference);\n this.emit({ t: \"artifact\", reference });\n } else if (!new Set([\"reasoning\", \"plan\"]).has(type)) {\n throw new CodexDispatchError(`agent '${step.role}' emitted forbidden '${type}'`);\n }\n }\n if (answerText === null) {\n throw new CodexDispatchError(`agent '${step.role}' lacks a final answer`);\n }\n if (originalRequestCalls !== 1) {\n throw new CodexDispatchError(`agent '${step.role}' did not load the authoritative original request`);\n }\n if (stepRequestCalls !== 1) {\n throw new CodexDispatchError(`agent '${step.role}' did not load the authoritative step request`);\n }\n // Codex 0.146 direct collaboration persists the encrypted NEW_TASK\n // delivery outside the child turn, so thread/read no longer exposes a\n // child userMessage and the parent spawn item redacts its prompt. The\n // dedicated step transport is host-authored and its successful call is\n // the authoritative copy. Any visible compatibility copy must agree.\n const requestTexts = [spawn.stepRequest, inputText, spawn.prompt].filter(\n (value): value is string => value !== null,\n );\n const requests = requestTexts.map((text) => parseStepRequest(text, step));\n if (requests.some((request) => canonical(request) !== canonical(requests[0]))) {\n throw new CodexDispatchError(`agent '${step.role}' has conflicting step inputs`);\n }\n const request = requests[0]!;\n const inputs = request[\"inputs\"] as JsonRecord;\n if (Object.keys(inputs).sort().join(\",\") !== [...step.consumes].sort().join(\",\")) {\n throw new CodexDispatchError(`agent '${step.role}' received the wrong input slots`);\n }\n for (const consumed of step.consumes) {\n if (canonical(inputs[consumed]) !== canonical(slots[consumed])) {\n throw new CodexDispatchError(`agent '${step.role}' input '${consumed}' was not marshalled exactly`);\n }\n }\n const envelope = parseEnvelope(answerText, step);\n // Family-agnostic per-step business rule: a step with no designated\n // repairer is required and must succeed; a step with a designated repairer must trigger\n // that repairer exactly when it fails, and must not spawn it when it succeeds. Derived\n // purely from IR adjacency (repairersByTarget), not from executionKind.\n const repairer = repairers.get(step.name);\n if (repairer === undefined) {\n if (!envelope.ok) {\n throw new CodexDispatchError(\n step.conditional\n ? \"bounded repair attempt did not recover generation\"\n : `required step '${step.name}' failed`,\n );\n }\n } else {\n const repairerSpawned = active.spawns.length > index + 1;\n if (!envelope.ok && !repairerSpawned) {\n throw new CodexDispatchError(\n `step '${step.name}' failure did not trigger repair step '${repairer.name}'`,\n );\n }\n if (envelope.ok && repairerSpawned) {\n throw new CodexDispatchError(\n `repair step '${repairer.name}' ran even though '${step.name}' succeeded`,\n );\n }\n }\n if (step.requireSuccessfulTool && artifacts.length === 0) {\n throw new CodexDispatchError(`agent '${step.role}' completed without its required MCP tool attempt`);\n }\n if (envelope.ok && step.requireSuccessfulTool && !artifacts.some((artifact) => artifact.ok)) {\n throw new CodexDispatchError(`agent '${step.role}' claimed success without a successful MCP tool`);\n }\n slots[step.produces] = envelope.value;\n const result: CodexAskStepResult = {\n step: step.name,\n agentRole: step.role,\n agentThreadId: spawn.agentThreadId,\n model: step.model,\n produced: step.produces,\n ok: envelope.ok,\n value: envelope.value,\n artifacts,\n };\n results.push(result);\n this.emit({\n t: \"step_finished\",\n parentThreadId: active.threadId,\n parentTurnId: active.turnId,\n step: step.name,\n agentRole: step.role,\n agentThreadId: spawn.agentThreadId,\n ok: envelope.ok,\n });\n }\n return results;\n }\n\n private async stopTurn(\n turn: CodexTurnReference,\n reason: \"turn_timeout\" | \"turn_cancelled\",\n ): Promise<void> {\n if (this.active?.turnId !== turn.turnId || this.active.stopReason !== null) return;\n this.active.stopReason = reason;\n const transport = this.transport;\n let resolveStopped!: () => void;\n const stopped = new Promise<void>((resolve) => {\n resolveStopped = resolve;\n });\n this.active.stopCompleted = resolveStopped;\n try {\n await transport.request(\"turn/interrupt\", {\n threadId: turn.threadId,\n turnId: turn.turnId,\n });\n } catch {\n // Closing the process tree below is the hard stop.\n }\n let graceTimer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n stopped,\n new Promise<void>((resolve) => {\n graceTimer = setTimeout(resolve, this.options.terminationGraceMs ?? 1_000);\n }),\n ]);\n if (graceTimer !== undefined) clearTimeout(graceTimer);\n await transport.close();\n if (this.active?.turnId !== turn.turnId) return;\n const error = new CodexDispatchError(\n reason === \"turn_timeout\"\n ? `Ask turn '${turn.turnId}' timed out`\n : `Ask turn '${turn.turnId}' was cancelled`,\n );\n this.active.reject(error);\n this.onDisconnect(undefined, reason);\n }\n\n private onDisconnect(\n protocolError?: CodexDispatchError,\n reasonOverride?: \"turn_timeout\" | \"turn_cancelled\",\n ): void {\n if (this.disconnected) return;\n this.disconnected = true;\n if (protocolError) {\n this.emit({ t: \"session_failed\", threadId: this.session?.threadId ?? null, reason: \"protocol_violation\" });\n this.active?.reject(protocolError);\n } else {\n this.emit({\n t: \"session_recoverable\",\n threadId: this.session?.threadId ?? null,\n reason: reasonOverride ?? (this.active ? \"app_server_crash\" : \"transport_disconnect\"),\n });\n this.active?.reject(new CodexDispatchError(\"app-server disconnected during an Ask turn\"));\n }\n }\n\n private ensureConnected(): void {\n if (this.disconnected) throw new CodexDispatchError(\"app-server transport disconnected; resume required\");\n }\n\n private emit(event: CodexAskEvent): void {\n this.options.onAskEvent?.(event);\n }\n}\n","import { isAbsolute } from \"node:path\";\n\nimport { CodexDispatchError } from \"./error.js\";\nimport { assertDispatchableComponentIdentity } from \"./dispatch_registry.js\";\nimport {\n parseIr,\n SUPPORTED_IR_VERSION,\n TARGET,\n type ComponentNode,\n type WarbleIr,\n} from \"./ir.js\";\nimport type { CapabilityResolution } from \"./prepare.js\";\nimport { resolveStepModel, validateStepTopology, type OnFailureGuard } from \"./step_engine.js\";\nimport {\n ENRICH_ALLOWED_CAPABILITIES,\n guardrailMatches,\n hasExactCapabilities,\n isEnrichDomainCapability,\n resolveCapabilities,\n type EnrichDomainCapability,\n} from \"./target_profile.js\";\n\nexport type { EnrichDomainCapability };\n\nexport interface EnrichMcpServerConfig {\n name: string;\n command: string;\n args?: string[];\n toolsByCapability: Record<EnrichDomainCapability, string[]>;\n}\n\nexport interface PreparedEnrichStep {\n name: string;\n tier: string;\n model: string;\n prompt: string;\n consumes: string[];\n produces: string;\n when: OnFailureGuard | null;\n}\n\nexport interface PreparedEnrichComponent {\n target: typeof TARGET;\n profile: string;\n node: ComponentNode;\n componentId: string;\n domainCapabilities: EnrichDomainCapability[];\n steps: PreparedEnrichStep[];\n capabilities: CapabilityResolution[];\n enabledTools: string[];\n mcp: EnrichMcpServerConfig;\n}\n\nexport interface PrepareEnrichInput {\n ir: string | WarbleIr;\n component: string;\n /**\n * A single string binds every step in the component to that one model. A per-tier map is\n * required once a component declares steps at more than one tier — see `resolveStepModel`.\n */\n model: string | Record<string, string>;\n mcp: EnrichMcpServerConfig;\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction validateEnrichShape(node: ComponentNode): EnrichDomainCapability[] {\n assertDispatchableComponentIdentity(node);\n // Checked first, and by capability name rather than by shape: a component whose\n // required_capabilities include anything outside this target's honestly-guaranteed set for\n // Enrich (e.g. a gated-tool component's context_write_authz/context_validate/context_build/\n // version_control/human_approval) can never be legalized here, no matter what its other IR shape\n // looks like. This keeps the wall-hit deterministic and named, and it must never be relaxed to\n // make a gated-tool component dispatchable. It also keeps Enrich's tier allowlist ({cheap,\n // strong}, no `llm:per_step_tier` widening) intact regardless of step count.\n for (const capability of node.required_capabilities) {\n if (!ENRICH_ALLOWED_CAPABILITIES.has(capability)) {\n throw new CodexDispatchError(\n `component '${node.id}' cannot be dispatched by codex:local: ` +\n `required capability '${capability}' has no honest realization on this target`,\n );\n }\n }\n if (\n node.type !== \"analytical\" ||\n node.realization_kind !== \"skill\" ||\n node.trigger.kind !== \"one_shot\" ||\n node.effect.outcome.kind !== \"none\"\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: requires analytical/skill/one_shot/none`,\n );\n }\n if (node.context_binding.binding_mode !== \"pinned\") {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: requires a pinned context binding`,\n );\n }\n if (node.llm_calls.length === 0) {\n throw new CodexDispatchError(`component '${node.id}' wall-hit: at least one llm_call is required`);\n }\n // Validates the full step sequence: unique names, produces-slot discipline, consumes→produces\n // marshalling closure, and on_failure guard placement. This is where the three phase-A\n // wall-hits now live, generalized to n steps rather than hardcoded to one.\n validateStepTopology(node);\n if (\n node.guardrails.length !== 1 ||\n !guardrailMatches(node.guardrails[0], \"read_only_execution\", { requireScopeAbsent: true })\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: exactly one locked read_only_execution guardrail with no scope is required`,\n );\n }\n const domainCapabilities = node.required_capabilities.filter(isEnrichDomainCapability);\n if (domainCapabilities.length === 0) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: at least one of semantic_introspection/raw_material_read is required`,\n );\n }\n // Unlike Setup (which spawns a brand-new one-shot `codex exec` process per step and can pass\n // `--model` fresh each time — see `resolveStepModel`/`buildCodexArgs`), Enrich's session-based\n // transport (`CodexSessionRuntime`) binds one model to the whole persistent thread for its\n // entire lifetime: `thread/start` takes a single `model`, and there is no per-turn override.\n // Ask's own architecture confirms this is a real transport limit, not an arbitrary one: Ask\n // realizes multi-tier steps by spawning a *separate* sub-agent thread per tier\n // (`ask_runtime.ts`'s `spawnAgent`), a capability Enrich does not have. So an Enrich component\n // may now have more than one step, but it must still declare exactly one tier — the single-\n // `llm_call` shape this replaced only ever had one, and this keeps that one true as steps grow.\n const tiers = unique(node.llm_calls.map((step) => step.tier));\n if (tiers.length !== 1) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: this transport's persistent session supports exactly one ` +\n `tier per component; found '${tiers.join(\"', '\")}'`,\n );\n }\n const expectedLlm = `llm:${tiers[0]}`;\n if (!node.required_capabilities.includes(expectedLlm)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: required capability '${expectedLlm}' is missing`,\n );\n }\n const expectedCapabilities = new Set<string>([...domainCapabilities, expectedLlm]);\n if (!hasExactCapabilities(node.required_capabilities, expectedCapabilities)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: supports exactly ` +\n `'${domainCapabilities.join(\"', '\")}' and '${expectedLlm}' capabilities`,\n );\n }\n return domainCapabilities;\n}\n\nexport function matchesEnrichContractShape(node: ComponentNode): boolean {\n try {\n validateEnrichShape(node);\n return true;\n } catch (error) {\n if (error instanceof CodexDispatchError) return false;\n throw error;\n }\n}\n\n/**\n * The specific reason a component's IR shape does not match the Enrich contract, or null when it\n * does match. Mirrors `matchesEnrichContractShape`'s try/catch but preserves the validator's own\n * wall-hit message so a caller classifying across all three families can surface precisely which\n * structural expectation failed.\n */\nexport function enrichContractMismatchReason(node: ComponentNode): string | null {\n try {\n validateEnrichShape(node);\n return null;\n } catch (error) {\n if (error instanceof CodexDispatchError) return error.message;\n throw error;\n }\n}\n\nexport function prepareEnrich(input: PrepareEnrichInput): PreparedEnrichComponent {\n const ir = typeof input.ir === \"string\" ? parseIr(input.ir) : input.ir;\n if (ir.warble_ir_version !== SUPPORTED_IR_VERSION) {\n throw new CodexDispatchError(\n `unsupported warble_ir_version '${ir.warble_ir_version}' (supported: ${SUPPORTED_IR_VERSION})`,\n );\n }\n const node = ir.components.find((candidate) => candidate.id === input.component);\n if (!node) {\n throw new CodexDispatchError(\n `component '${input.component}' was not found in profile '${ir.profile}'`,\n );\n }\n const domainCapabilities = validateEnrichShape(node);\n const componentId = node.id;\n if (!/^[A-Za-z0-9_-]+$/.test(input.mcp.name)) {\n throw new CodexDispatchError(\n `MCP server name '${input.mcp.name}' must contain only letters, digits, '_' or '-'`,\n );\n }\n if (!isAbsolute(input.mcp.command)) {\n throw new CodexDispatchError(\n `MCP server command must be absolute when shell_environment_policy.inherit=none`,\n );\n }\n const enabledTools = unique(\n domainCapabilities.flatMap((capability) => input.mcp.toolsByCapability[capability] ?? []),\n );\n if (enabledTools.length === 0) {\n throw new CodexDispatchError(\n `component '${componentId}' has no allowlisted MCP tools for '${domainCapabilities.join(\"', '\")}'`,\n );\n }\n const topology = validateStepTopology(node);\n const steps: PreparedEnrichStep[] = node.llm_calls.map((call, index) => ({\n name: call.name,\n tier: call.tier,\n model: resolveStepModel(input.model, call.tier, componentId),\n prompt: call.prompt,\n consumes: call.consumes,\n produces: call.produces!,\n when: topology[index]!.when,\n }));\n return {\n target: TARGET,\n profile: ir.profile,\n node,\n componentId,\n domainCapabilities,\n steps,\n capabilities: resolveCapabilities(node.required_capabilities, input.mcp.name),\n enabledTools,\n mcp: input.mcp,\n };\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport type { ComponentNode, LlmCall } from \"./ir.js\";\n\n/**\n * The only `when` dialect this transport (and the Ask path) evaluates: a step runs only when an\n * earlier step in the same component failed. `target` names that earlier step.\n */\nexport interface OnFailureGuard {\n guard: \"on_failure\";\n target: string;\n}\n\n/**\n * Parses a step's `conditional`/`when` pair the same way Ask's `parseWhen` does: unconditional\n * steps must carry no guard, conditional steps must carry exactly `{guard: \"on_failure\", target}`.\n * Kept transport-neutral (no Ask import) so Setup/Enrich stay separate engines from Ask while\n * reading identically to it, without merging the three families.\n */\nexport function parseStepWhen(step: LlmCall): OnFailureGuard | null {\n if (!step.conditional) {\n if (step.when !== null) {\n throw new CodexDispatchError(`step '${step.name}' is unconditional but has a when guard`);\n }\n return null;\n }\n if (\n typeof step.when !== \"object\" ||\n step.when === null ||\n Array.isArray(step.when) ||\n (step.when as Record<string, unknown>)[\"guard\"] !== \"on_failure\" ||\n typeof (step.when as Record<string, unknown>)[\"target\"] !== \"string\"\n ) {\n throw new CodexDispatchError(`step '${step.name}' wall-hit: repair requires on_failure(target)`);\n }\n return {\n guard: \"on_failure\",\n target: (step.when as Record<string, string>)[\"target\"]!,\n };\n}\n\nexport interface StepTopology {\n when: OnFailureGuard | null;\n}\n\n/**\n * Validates the full step sequence's shape once every step has been individually accepted:\n *\n * - step names are unique (addressing by name, for both marshalling and on_failure targets,\n * requires this — it is also what turns the old \"grows a second step by cloning the same step\"\n * fixture into a genuine reject rather than an accidental accept);\n * - every step has a produced slot (the per-step generalization of the old single-step\n * \"requires a produced slot\" wall-hit — each step's completion is judged by whether it produced\n * what it declared, so every step needs that signal, not only the last one);\n * - every `consumes` name is satisfiable by some strictly earlier step's `produces` (unchanged\n * general rule from the single-step transport, now with more than one possible producer);\n * - an on_failure guard's target is the name of a strictly earlier step (no forward/self\n * reference — a target must already have run, or been skipped, by the time the guard is\n * evaluated);\n * - a conditional (on_failure-guarded) step must be the LAST step in the component. This is not\n * a hardcoded Setup/Enrich shape rule; it mirrors the one thing that keeps Ask's repair step\n * safe to skip — nothing downstream ever consumes a step that might not run. Without this rule\n * a validator could bless a component whose executor cannot honestly know what to feed a later\n * consumer when its producer was skipped, which is exactly the defect the validator's\n * accept-set-equals-execute-set invariant exists to prevent.\n */\nexport function validateStepTopology(node: ComponentNode): StepTopology[] {\n const names = new Set<string>();\n for (const step of node.llm_calls) {\n if (names.has(step.name)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step name '${step.name}' is declared more than once`,\n );\n }\n names.add(step.name);\n }\n const topology: StepTopology[] = [];\n const produced = new Set<string>();\n for (let index = 0; index < node.llm_calls.length; index += 1) {\n const step = node.llm_calls[index]!;\n for (const consumed of step.consumes) {\n if (!produced.has(consumed)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${step.name}' consumes '${consumed}' but no earlier step produces it`,\n );\n }\n }\n if (step.produces === null) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: this transport requires a produced slot; step '${step.name}' produces none`,\n );\n }\n produced.add(step.produces);\n const when = parseStepWhen(step);\n if (when !== null) {\n if (index !== node.llm_calls.length - 1) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: conditional step '${step.name}' must be the last step; a step nothing downstream can safely consume from must not have output others rely on`,\n );\n }\n if (!names.has(when.target) || !node.llm_calls.slice(0, index).some((earlier) => earlier.name === when.target)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: step '${step.name}' on_failure target '${when.target}' is not an earlier step`,\n );\n }\n }\n topology.push({ when });\n }\n return topology;\n}\n\n/**\n * Parses a step's terminal text the way both Setup and Enrich judge whether a step \"succeeded\":\n * valid JSON, a single-key object whose key is exactly the step's declared `produces` name, with\n * a non-null value. Shared so Setup gains the same produces-field discipline Enrich already had,\n * and so a step's on_failure guard (see `validateStepTopology`) and a step's marshalled output\n * are judged by the identical rule.\n */\nexport function parseStepTerminal(text: string, produces: string): Record<string, unknown> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new CodexDispatchError(\"step terminal is not JSON\");\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CodexDispatchError(\"step terminal must be a JSON object\");\n }\n const record = parsed as Record<string, unknown>;\n const keys = Object.keys(record);\n if (keys.length !== 1 || keys[0] !== produces || record[produces] === null) {\n throw new CodexDispatchError(`step terminal requires exactly the produced field '${produces}'`);\n }\n return record;\n}\n\n/** A step's outcome after this dispatch has attempted (or skipped) it. */\nexport type StepOutcome =\n | { ran: true; ok: true; value: unknown }\n | { ran: true; ok: false }\n | { ran: false };\n\n/**\n * Decides, from the prior steps' recorded outcomes, whether a step with the given guard should\n * run this dispatch. `null` (unconditional) always runs. An on_failure guard runs only when its\n * target step ran and did not succeed — mirroring Ask's on_failure(target) direction (skip on\n * success, run on failure) while judging \"failure\" in terms this transport can honestly observe\n * (produces-field match) rather than borrowing Ask's structured-envelope `ok` field, which this\n * transport's steps have no contract to emit.\n */\nexport function shouldRunStep(when: OnFailureGuard | null, outcomes: ReadonlyMap<string, StepOutcome>): boolean {\n if (when === null) return true;\n const target = outcomes.get(when.target);\n return target !== undefined && target.ran && !target.ok;\n}\n\n/**\n * Resolves the model bound to a step's tier from a `PrepareInput.model` value that may be either\n * a single string (every step in the component runs at that one tier/model — the shape every\n * existing single-step fixture already uses) or a per-tier map (needed once a component declares\n * steps at more than one tier). Kept generic on the tier string itself: the validator already\n * deleted the tier whitelist, so this must not reintroduce one.\n */\nexport function resolveStepModel(model: string | Record<string, string>, tier: string, componentId: string): string {\n const resolved = typeof model === \"string\" ? model : model[tier];\n if (resolved === undefined || resolved.trim().length === 0) {\n throw new CodexDispatchError(\n `component '${componentId}' wall-hit: no model binding for tier '${tier}'`,\n );\n }\n return resolved;\n}\n","import { isAbsolute } from \"node:path\";\n\nimport { CodexDispatchError } from \"./error.js\";\nimport { assertDispatchableComponentIdentity } from \"./dispatch_registry.js\";\nimport {\n parseIr,\n SUPPORTED_IR_VERSION,\n TARGET,\n type ComponentNode,\n type WarbleIr,\n} from \"./ir.js\";\nimport { resolveStepModel, validateStepTopology, type OnFailureGuard } from \"./step_engine.js\";\nimport {\n guardrailMatches,\n hasExactCapabilities,\n isSetupDomainCapability,\n resolveCapabilities,\n type SetupDomainCapability,\n} from \"./target_profile.js\";\n\nexport type { SetupDomainCapability };\nexport type { OnFailureGuard };\n\nexport interface McpServerConfig {\n name: string;\n command: string;\n args?: string[];\n toolsByCapability: Record<SetupDomainCapability, string[]>;\n}\n\nexport interface CapabilityResolution {\n capability: string;\n outcome: \"native\" | \"realize-via\";\n via: string | null;\n}\n\nexport interface PreparedSetupStep {\n name: string;\n tier: string;\n model: string;\n prompt: string;\n consumes: string[];\n produces: string;\n when: OnFailureGuard | null;\n}\n\nexport interface PreparedSetupComponent {\n target: typeof TARGET;\n profile: string;\n node: ComponentNode;\n componentId: string;\n domainCapability: SetupDomainCapability;\n steps: PreparedSetupStep[];\n capabilities: CapabilityResolution[];\n enabledTools: string[];\n mcp: McpServerConfig;\n}\n\nexport interface PrepareInput {\n ir: string | WarbleIr;\n component: string;\n /**\n * A single string binds every step in the component to that one model (the shape every\n * existing single-step fixture already uses, and still all that's required when a component\n * declares only one tier). A per-tier map is required once a component declares steps at more\n * than one tier — see `resolveStepModel`.\n */\n model: string | Record<string, string>;\n mcp: McpServerConfig;\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction validateSetupShape(node: ComponentNode): SetupDomainCapability {\n if (\n node.type !== \"analytical\" ||\n node.realization_kind !== \"skill\" ||\n node.trigger.kind !== \"one_shot\" ||\n node.effect.outcome.kind !== \"none\" ||\n node.effect.render_blocks.length !== 0\n ) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: requires analytical/skill/one_shot/none with no render blocks`,\n );\n }\n if (node.llm_calls.length === 0) {\n throw new CodexDispatchError(`component '${node.id}' wall-hit: at least one llm_call is required`);\n }\n // Validates the full step sequence: unique names, produces-slot discipline, consumes→produces\n // marshalling closure, and on_failure guard placement. This is where the three phase-A\n // wall-hits (\"exactly one llm_call\", \"does not evaluate step conditions\", \"requires a produced\n // slot\") now live, generalized to n steps rather than hardcoded to one.\n validateStepTopology(node);\n if (node.guardrails.length !== 1 || !guardrailMatches(node.guardrails[0], \"setup_execution\")) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: exactly one locked setup_execution guardrail with scope '.' is required`,\n );\n }\n const domainCapabilities = node.required_capabilities.filter(isSetupDomainCapability);\n if (domainCapabilities.length !== 1) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: exactly one of source_connect/context_build is required`,\n );\n }\n const tiers = unique(node.llm_calls.map((step) => step.tier));\n const expectedLlm = tiers.length === 1 ? `llm:${tiers[0]}` : \"llm:per_step_tier\";\n if (!node.required_capabilities.includes(expectedLlm)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: required capability '${expectedLlm}' is missing`,\n );\n }\n const expectedCapabilities = new Set<string>([domainCapabilities[0]!, expectedLlm]);\n if (!hasExactCapabilities(node.required_capabilities, expectedCapabilities)) {\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: supports exactly '${domainCapabilities[0]}' and '${expectedLlm}' capabilities`,\n );\n }\n return domainCapabilities[0]!;\n}\n\nexport function matchesSetupContractShape(node: ComponentNode): boolean {\n try {\n validateSetupShape(node);\n return true;\n } catch (error) {\n if (error instanceof CodexDispatchError) return false;\n throw error;\n }\n}\n\n/**\n * The specific reason a component's IR shape does not match the Setup contract, or null when it\n * does match. This mirrors `matchesSetupContractShape`'s try/catch but preserves the validator's\n * own wall-hit message instead of collapsing it to a boolean, so a caller classifying across all\n * three families can surface precisely which structural expectation failed.\n */\nexport function setupContractMismatchReason(node: ComponentNode): string | null {\n try {\n validateSetupShape(node);\n return null;\n } catch (error) {\n if (error instanceof CodexDispatchError) return error.message;\n throw error;\n }\n}\n\nexport function prepareSetup(input: PrepareInput): PreparedSetupComponent {\n const ir = typeof input.ir === \"string\" ? parseIr(input.ir) : input.ir;\n if (ir.warble_ir_version !== SUPPORTED_IR_VERSION) {\n throw new CodexDispatchError(\n `unsupported warble_ir_version '${ir.warble_ir_version}' (supported: ${SUPPORTED_IR_VERSION})`,\n );\n }\n const node = ir.components.find((candidate) => candidate.id === input.component);\n if (!node) {\n throw new CodexDispatchError(`component '${input.component}' was not found in profile '${ir.profile}'`);\n }\n assertDispatchableComponentIdentity(node);\n const domainCapability = validateSetupShape(node);\n const componentId = node.id;\n if (!/^[A-Za-z0-9_-]+$/.test(input.mcp.name)) {\n throw new CodexDispatchError(\n `MCP server name '${input.mcp.name}' must contain only letters, digits, '_' or '-'`,\n );\n }\n if (!isAbsolute(input.mcp.command)) {\n throw new CodexDispatchError(\n `MCP server command must be absolute when shell_environment_policy.inherit=none`,\n );\n }\n const enabledTools = unique(input.mcp.toolsByCapability[domainCapability]);\n if (enabledTools.length === 0) {\n throw new CodexDispatchError(\n `component '${componentId}' has no allowlisted MCP tools for '${domainCapability}'`,\n );\n }\n const topology = validateStepTopology(node);\n const steps: PreparedSetupStep[] = node.llm_calls.map((call, index) => ({\n name: call.name,\n tier: call.tier,\n model: resolveStepModel(input.model, call.tier, componentId),\n prompt: call.prompt,\n consumes: call.consumes,\n produces: call.produces!,\n when: topology[index]!.when,\n }));\n return {\n target: TARGET,\n profile: ir.profile,\n node,\n componentId,\n domainCapability,\n steps,\n capabilities: resolveCapabilities(node.required_capabilities, input.mcp.name),\n enabledTools,\n mcp: input.mcp,\n };\n}\n\nexport function prepareAllSetup(\n raw: string,\n config: Omit<PrepareInput, \"ir\" | \"component\">,\n): PreparedSetupComponent[] {\n const ir = parseIr(raw);\n // Aggregate preparation must reject a reserved host-only identity before preparing any\n // component, so a direct caller cannot receive a partial array preceding the wall-hit.\n for (const node of ir.components) assertDispatchableComponentIdentity(node);\n return ir.components.map((node) =>\n prepareSetup({ ...config, ir, component: node.id }),\n );\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport type { ComponentNode, WarbleIr } from \"./ir.js\";\nimport { askContractMismatchReason, matchesAskContractShape } from \"./ask_prepare.js\";\nimport { assertDispatchableComponentIdentity } from \"./dispatch_registry.js\";\nimport { enrichContractMismatchReason, matchesEnrichContractShape } from \"./enrich_prepare.js\";\nimport { setupContractMismatchReason, matchesSetupContractShape } from \"./prepare.js\";\n\n/**\n * The public CLI is intentionally profile-agnostic. These are implementation contracts selected\n * from a parsed component's declared IR shape, never from a command spelling, profile name, or\n * component identity.\n */\nexport type DispatchContract = \"setup\" | \"ask\" | \"enrich\";\n\nfunction selectedComponent(ir: WarbleIr, component: string): ComponentNode {\n const node = ir.components.find((candidate) => candidate.id === component);\n if (!node) {\n throw new CodexDispatchError(`component '${component}' was not found in profile '${ir.profile}'`);\n }\n return node;\n}\n\n/**\n * Select the native execution contract only when exactly one complete structural contract matches.\n * This check runs before configuration, preparation, or a runtime launch.\n */\nexport function classifyDispatchContract(ir: WarbleIr, component: string): DispatchContract {\n const node = selectedComponent(ir, component);\n assertDispatchableComponentIdentity(node);\n const matches = [\n ...(matchesSetupContractShape(node) ? ([\"setup\"] as const) : []),\n ...(matchesAskContractShape(node) ? ([\"ask\"] as const) : []),\n ...(matchesEnrichContractShape(node) ? ([\"enrich\"] as const) : []),\n ];\n if (matches.length === 1) return matches[0]!;\n if (matches.length === 0) {\n // No single family shape matched. Rather than collapse to one generic sentence, surface each\n // family validator's own specific wall-hit reason so the diagnostic still names the concrete\n // structural expectation that failed (e.g. a guardrail contract mismatch), not just the fact\n // that nothing matched.\n const reasons = [\n setupContractMismatchReason(node),\n askContractMismatchReason(node),\n enrichContractMismatchReason(node),\n ].filter((reason): reason is string => reason !== null);\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: no supported codex:local execution contract matches its complete IR shape` +\n (reasons.length > 0 ? ` (${reasons.join(\" | \")})` : \"\"),\n );\n }\n throw new CodexDispatchError(\n `component '${node.id}' wall-hit: ambiguous codex:local execution contracts (${matches.join(\", \")})`,\n );\n}\n\n/**\n * Setup is the sole whole-profile manifest/describe contract. Other shapes are scoped dispatches\n * and therefore require an explicit --component selection.\n */\nexport function supportsSetupAggregate(ir: WarbleIr): boolean {\n // Scan the complete profile for host-only identities before testing whether it is an aggregate.\n // Otherwise a preceding non-Setup node could short-circuit `.every()` and leave a forged\n // reserved identity unchecked on the generic manifest/describe path.\n for (const node of ir.components) assertDispatchableComponentIdentity(node);\n return ir.components.length > 0 && ir.components.every(matchesSetupContractShape);\n}\n","import { SUPPORTED_IR_VERSION, TARGET } from \"./ir.js\";\nimport type { PreparedSetupComponent } from \"./prepare.js\";\nimport type { PreparedAskComponent } from \"./ask_prepare.js\";\nimport type { PreparedEnrichComponent } from \"./enrich_prepare.js\";\n\nexport interface StepManifest {\n name: string;\n tier: string;\n model: string;\n consumes: string[];\n produces: string | null;\n agent_role?: string;\n conditional?: boolean;\n when?: { guard: string; target: string } | null;\n tools?: string[];\n}\n\nexport interface AgentManifest {\n id: string;\n verb: string;\n component_type: string;\n realization_kind: string;\n trigger: string;\n outcome: string;\n steps: StepManifest[];\n capabilities: PreparedSetupComponent[\"capabilities\"];\n tools: Array<{ name: string; source: string; agents?: string[] }>;\n guardrails: Record<string, unknown>;\n artifact_output?: {\n kind: \"render_envelope\";\n persistence: \"consumer\";\n block_types: string[];\n };\n}\n\nexport interface Manifest {\n manifest_version: \"0.1\";\n compat: {\n min_ir_version: typeof SUPPORTED_IR_VERSION;\n max_ir_version: typeof SUPPORTED_IR_VERSION;\n };\n profile: string;\n target: typeof TARGET;\n session: SessionManifest;\n agents: AgentManifest[];\n}\n\nexport const SESSION_LIFECYCLE_OPERATIONS = [\n \"start\",\n \"resume\",\n \"read\",\n \"turn\",\n \"steer\",\n \"interrupt\",\n \"fork\",\n] as const;\n\nexport interface SessionManifest {\n persistence: \"codex_thread_history\";\n lifecycle_operations: Array<(typeof SESSION_LIFECYCLE_OPERATIONS)[number]>;\n artifact_reference:\n | \"allowlisted_mcp_tool_result\"\n | \"allowlisted_mcp_tool_result_or_render_envelope\";\n isolation: \"dedicated_persistent_codex_home\";\n authentication: \"externally_provisioned\";\n}\n\nexport interface TargetDescription {\n target: typeof TARGET;\n phase:\n | \"setup-only\"\n | \"setup-and-ask-parity\"\n | \"setup-ask-and-dashboard-parity\"\n | \"enrich-parity\";\n execution_modes: Array<\"one_shot\" | \"persistent_session\">;\n session_persistence: SessionManifest[\"persistence\"];\n lifecycle_operations: SessionManifest[\"lifecycle_operations\"];\n supported_components: string[];\n tiers: string[];\n capabilities: string[];\n tools: string[];\n guardrails: string[];\n}\n\nexport function buildAskAgentManifest(prepared: PreparedAskComponent): AgentManifest {\n const toolAgents = new Map<string, string[]>();\n for (const step of prepared.steps) {\n for (const tool of step.enabledTools) {\n const agents = toolAgents.get(tool) ?? [];\n if (!agents.includes(step.role)) agents.push(step.role);\n toolAgents.set(tool, agents);\n }\n }\n const dashboard = prepared.executionKind === \"generate_dashboard\";\n return {\n id: prepared.node.id,\n verb: prepared.node.verb,\n component_type: prepared.node.type,\n realization_kind: prepared.node.realization_kind,\n trigger: prepared.node.trigger.kind,\n outcome: prepared.node.effect.outcome.kind,\n steps: prepared.steps.map((step) => ({\n name: step.name,\n tier: step.tier,\n model: step.model,\n consumes: [...step.consumes],\n produces: step.produces,\n agent_role: step.role,\n conditional: step.conditional,\n when: step.when,\n tools: [...step.enabledTools],\n })),\n capabilities: prepared.capabilities,\n tools: [...toolAgents].map(([name, agents]) => ({\n name,\n source: `mcp:${prepared.mcp.name}`,\n agents,\n })),\n guardrails: {\n read_only_execution: { enforcement: \"per_agent_mcp_only_read_only_sandbox\", locked: true },\n ...(dashboard\n ? {\n artifact_write: {\n enforcement: \"consumer_persisted_render_envelope\",\n locked: true,\n scope: \".\",\n },\n render_contract: {\n enforcement: \"validated_ir_declared_render_envelope\",\n on_failure: \"degrade\",\n },\n }\n : {\n deterministic_gate: {\n enforcement: \"child_result_envelope_and_event_attribution\",\n locked: true,\n },\n row_limit: { threshold: 1000 },\n statement_timeout: { threshold: 30 },\n }),\n ordered_delegation: {\n enforcement: \"named_child_threads_in_ir_order\",\n flattening: \"forbidden\",\n },\n ...(dashboard\n ? {}\n : {\n conditional_repair: {\n guard: prepared.steps[2]!.when,\n max_attempts: prepared.maxRepairAttempts,\n exhaustion: \"loud_fail\",\n },\n }),\n isolated_codex_config: {\n parent_tools: \"multi_agent_only\",\n child_tools: \"per_step_exact_mcp_allowlist\",\n approval_policy: \"never\",\n sandbox: \"read-only\",\n api_key_environment: \"removed\",\n },\n },\n ...(dashboard\n ? {\n artifact_output: {\n kind: \"render_envelope\" as const,\n persistence: \"consumer\" as const,\n block_types: prepared.node.effect.render_blocks.map((block) =>\n typeof block === \"object\" && block !== null && \"type\" in block\n ? String((block as { type: unknown }).type)\n : \"unknown\",\n ),\n },\n }\n : {}),\n };\n}\n\nexport function buildAskManifest(prepared: PreparedAskComponent): Manifest {\n return {\n manifest_version: \"0.1\",\n compat: {\n min_ir_version: SUPPORTED_IR_VERSION,\n max_ir_version: SUPPORTED_IR_VERSION,\n },\n profile: prepared.profile,\n target: TARGET,\n session: {\n persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n artifact_reference:\n prepared.executionKind === \"generate_dashboard\"\n ? \"allowlisted_mcp_tool_result_or_render_envelope\"\n : \"allowlisted_mcp_tool_result\",\n isolation: \"dedicated_persistent_codex_home\",\n authentication: \"externally_provisioned\",\n },\n agents: [buildAskAgentManifest(prepared)],\n };\n}\n\nexport function describeAskTarget(prepared: PreparedAskComponent): TargetDescription {\n return {\n target: TARGET,\n phase:\n prepared.executionKind === \"generate_dashboard\"\n ? \"setup-ask-and-dashboard-parity\"\n : \"setup-and-ask-parity\",\n execution_modes: [\"persistent_session\"],\n session_persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n supported_components: [prepared.componentId],\n tiers: [...new Set(prepared.steps.map((step) => step.tier))],\n capabilities: prepared.capabilities.map((entry) => entry.capability),\n tools: [...new Set(prepared.steps.flatMap((step) => step.enabledTools))],\n guardrails:\n prepared.executionKind === \"generate_dashboard\"\n ? [\n \"read_only_execution\",\n \"artifact_write\",\n \"render_contract\",\n \"ordered_delegation\",\n \"isolated_codex_config\",\n ]\n : [\n \"read_only_execution\",\n \"deterministic_gate\",\n \"row_limit\",\n \"statement_timeout\",\n \"ordered_delegation\",\n \"conditional_repair\",\n \"isolated_codex_config\",\n ],\n };\n}\n\nexport function buildAgentManifest(prepared: PreparedSetupComponent): AgentManifest {\n return {\n id: prepared.node.id,\n verb: prepared.node.verb,\n component_type: prepared.node.type,\n realization_kind: prepared.node.realization_kind,\n trigger: prepared.node.trigger.kind,\n outcome: prepared.node.effect.outcome.kind,\n steps: prepared.steps.map((step) => ({\n name: step.name,\n tier: step.tier,\n model: step.model,\n consumes: step.consumes,\n produces: step.produces,\n })),\n capabilities: prepared.capabilities,\n tools: prepared.enabledTools.map((name) => ({\n name,\n source: `mcp:${prepared.mcp.name}`,\n })),\n guardrails: {\n setup_execution: {\n enforcement: \"mcp_only_read_only_sandbox\",\n locked: true,\n scope: \".\",\n },\n isolated_codex_config: {\n ignore_user_config: true,\n ephemeral: true,\n approval_policy: \"never\",\n sandbox: \"read-only\",\n api_key_environment: \"removed\",\n },\n },\n };\n}\n\nexport function buildManifest(prepared: readonly PreparedSetupComponent[]): Manifest {\n const first = prepared[0];\n if (!first) {\n throw new Error(\"cannot build a manifest without prepared components\");\n }\n return {\n manifest_version: \"0.1\",\n compat: {\n min_ir_version: SUPPORTED_IR_VERSION,\n max_ir_version: SUPPORTED_IR_VERSION,\n },\n profile: first.profile,\n target: TARGET,\n session: {\n persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n artifact_reference: \"allowlisted_mcp_tool_result\",\n isolation: \"dedicated_persistent_codex_home\",\n authentication: \"externally_provisioned\",\n },\n agents: prepared.map(buildAgentManifest),\n };\n}\n\nexport function describeTarget(prepared: readonly PreparedSetupComponent[]): TargetDescription {\n return {\n target: TARGET,\n phase: \"setup-only\",\n execution_modes: [\"one_shot\", \"persistent_session\"],\n session_persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n supported_components: prepared.map((component) => component.componentId),\n tiers: [...new Set(prepared.flatMap((component) => component.steps.map((step) => step.tier)))],\n capabilities: [\n ...new Set(prepared.flatMap((component) => component.capabilities.map((entry) => entry.capability))),\n ],\n tools: [...new Set(prepared.flatMap((component) => component.enabledTools))],\n guardrails: [\"setup_execution\", \"isolated_codex_config\"],\n };\n}\n\n// Enrich is scoped-only (no whole-profile aggregator), mirroring Ask rather than Setup: the profile\n// deliberately mixes two dispatchable read-only skills with a gated-tool component (non-`skill`\n// realization_kind, host-owned capabilities) that no headless target can ever legalize, so a\n// `.map()`-style aggregator across the whole profile would always throw and would not describe\n// anything real. Each enrichment component is dispatched with its own `dispatch --component <id>`\n// turn, exactly like the two existing families' per-component calls.\nexport function buildEnrichAgentManifest(prepared: PreparedEnrichComponent): AgentManifest {\n return {\n id: prepared.node.id,\n verb: prepared.node.verb,\n component_type: prepared.node.type,\n realization_kind: prepared.node.realization_kind,\n trigger: prepared.node.trigger.kind,\n outcome: prepared.node.effect.outcome.kind,\n steps: prepared.steps.map((step) => ({\n name: step.name,\n tier: step.tier,\n model: step.model,\n consumes: step.consumes,\n produces: step.produces,\n })),\n capabilities: prepared.capabilities,\n tools: prepared.enabledTools.map((name) => ({\n name,\n source: `mcp:${prepared.mcp.name}`,\n })),\n guardrails: {\n read_only_execution: {\n enforcement: \"mcp_only_read_only_sandbox\",\n locked: true,\n },\n isolated_codex_config: {\n ignore_user_config: true,\n ephemeral: true,\n approval_policy: \"never\",\n sandbox: \"read-only\",\n api_key_environment: \"removed\",\n },\n },\n };\n}\n\nexport function buildEnrichManifest(prepared: PreparedEnrichComponent): Manifest {\n return {\n manifest_version: \"0.1\",\n compat: {\n min_ir_version: SUPPORTED_IR_VERSION,\n max_ir_version: SUPPORTED_IR_VERSION,\n },\n profile: prepared.profile,\n target: TARGET,\n session: {\n persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n artifact_reference: \"allowlisted_mcp_tool_result\",\n isolation: \"dedicated_persistent_codex_home\",\n authentication: \"externally_provisioned\",\n },\n agents: [buildEnrichAgentManifest(prepared)],\n };\n}\n\nexport function describeEnrichTarget(prepared: PreparedEnrichComponent): TargetDescription {\n return {\n target: TARGET,\n phase: \"enrich-parity\",\n execution_modes: [\"one_shot\", \"persistent_session\"],\n session_persistence: \"codex_thread_history\",\n lifecycle_operations: [...SESSION_LIFECYCLE_OPERATIONS],\n supported_components: [prepared.componentId],\n tiers: [...new Set(prepared.steps.map((step) => step.tier))],\n capabilities: prepared.capabilities.map((entry) => entry.capability),\n tools: [...prepared.enabledTools],\n guardrails: [\"read_only_execution\", \"isolated_codex_config\"],\n };\n}\n","import { resolve } from \"node:path\";\n\nimport { CodexAppServerTransport, type CatalogTransportOptions } from \"./app_server_transport.js\";\n\n/** The deliberately small host-facing contract for provider-owned model discovery. */\nexport const MODEL_CATALOG_VERSION = 1 as const;\n\nexport interface ModelCatalogModel {\n model: string;\n displayName: string;\n description?: string;\n isDefault?: boolean;\n reasoningEfforts?: Array<{ value: string; displayName: string; description?: string }>;\n}\n\nexport type ModelCatalogUnavailableCode =\n | \"not_authenticated\"\n | \"runtime_unavailable\"\n | \"timeout\"\n | \"protocol_error\";\n\nexport type ModelCatalogResult =\n | {\n version: typeof MODEL_CATALOG_VERSION;\n status: \"ready\";\n provider: \"codex\";\n models: ModelCatalogModel[];\n }\n | {\n version: typeof MODEL_CATALOG_VERSION;\n status: \"unavailable\";\n provider: \"codex\";\n code: ModelCatalogUnavailableCode;\n retryable: boolean;\n };\n\nexport interface DiscoverCodexModelsOptions {\n cwd?: string;\n codexHome?: string;\n codexBin?: string;\n timeoutMs?: number;\n env?: NodeJS.ProcessEnv;\n}\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\nconst PAGE_LIMIT = 100;\nconst MAX_PAGES = 100;\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction unavailable(code: ModelCatalogUnavailableCode, retryable: boolean): ModelCatalogResult {\n return { version: MODEL_CATALOG_VERSION, status: \"unavailable\", provider: \"codex\", code, retryable };\n}\n\nfunction classify(error: unknown): ModelCatalogResult {\n const message = error instanceof Error ? error.message.toLowerCase() : \"\";\n if (message.includes(\"timed out\")) return unavailable(\"timeout\", true);\n if (/(not authenticated|unauthenticated|authentication|login required|sign in)/.test(message)) {\n return unavailable(\"not_authenticated\", false);\n }\n if (/(enoent|failed to start|not found|transport is not available|disconnected)/.test(message)) {\n return unavailable(\"runtime_unavailable\", true);\n }\n // Never reflect raw JSON-RPC/provider errors: their payload is outside the public contract.\n return unavailable(\"protocol_error\", false);\n}\n\nfunction text(record: JsonRecord, field: string, required = false): string | undefined {\n const value = record[field];\n if (value === undefined && !required) return undefined;\n if (typeof value !== \"string\") throw new Error(\"malformed model catalog response\");\n return value;\n}\n\nfunction mapModel(raw: unknown): ModelCatalogModel | null {\n if (!isRecord(raw)) throw new Error(\"malformed model catalog response\");\n // Defense in depth: the request has includeHidden=false and an unexpected hidden model still\n // never reaches a host picker.\n if (raw[\"hidden\"] === true) return null;\n const model = text(raw, \"model\", true)!;\n const displayName = text(raw, \"displayName\", true)!;\n const description = text(raw, \"description\");\n const isDefault = raw[\"isDefault\"];\n if (isDefault !== undefined && typeof isDefault !== \"boolean\") {\n throw new Error(\"malformed model catalog response\");\n }\n const effortsRaw = raw[\"supportedReasoningEfforts\"];\n let reasoningEfforts: ModelCatalogModel[\"reasoningEfforts\"];\n if (effortsRaw !== undefined) {\n if (!Array.isArray(effortsRaw)) throw new Error(\"malformed model catalog response\");\n reasoningEfforts = effortsRaw.map((effort) => {\n if (!isRecord(effort)) throw new Error(\"malformed model catalog response\");\n const value = text(effort, \"reasoningEffort\", true)!;\n const effortDescription = text(effort, \"description\");\n return {\n value,\n // The app-server protocol exposes an effort value, not a separate label.\n displayName: value,\n ...(effortDescription === undefined ? {} : { description: effortDescription }),\n };\n });\n }\n return {\n model,\n displayName,\n ...(description === undefined ? {} : { description }),\n ...(isDefault === undefined ? {} : { isDefault }),\n ...(reasoningEfforts === undefined ? {} : { reasoningEfforts }),\n };\n}\n\nfunction pageResponse(value: unknown): { data: unknown[]; nextCursor: string | null } {\n if (!isRecord(value) || !Array.isArray(value[\"data\"])) {\n throw new Error(\"malformed model catalog response\");\n }\n const nextCursor = value[\"nextCursor\"];\n if (nextCursor !== null && nextCursor !== undefined && typeof nextCursor !== \"string\") {\n throw new Error(\"malformed model catalog response\");\n }\n return { data: value[\"data\"], nextCursor: (nextCursor ?? null) as string | null };\n}\n\n/**\n * List authenticated Codex models over app-server without creating a thread or a turn.\n * Only explicitly mapped model-picker fields ever leave this module.\n */\nexport async function discoverCodexModels(\n options: DiscoverCodexModelsOptions = {},\n): Promise<ModelCatalogResult> {\n const timeoutMs = options.timeoutMs ?? 10_000;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return unavailable(\"protocol_error\", false);\n let transport: CodexAppServerTransport | undefined;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const transportOptions: CatalogTransportOptions = {\n cwd: resolve(options.cwd ?? process.cwd()),\n timeoutMs,\n ...(options.codexHome ? { codexHome: resolve(options.codexHome) } : {}),\n ...(options.codexBin ? { codexBin: resolve(options.codexBin) } : {}),\n ...(options.env ? { env: options.env } : {}),\n };\n const deadline = new Promise<never>((_, reject) => {\n timeout = setTimeout(() => {\n void transport?.close();\n reject(new Error(\"model catalog timed out\"));\n }, timeoutMs);\n });\n const list = (async (): Promise<ModelCatalogResult> => {\n transport = await CodexAppServerTransport.startCatalog(transportOptions);\n const models: ModelCatalogModel[] = [];\n let cursor: string | null = null;\n for (let page = 0; page < MAX_PAGES; page += 1) {\n const response = pageResponse(await transport.request(\"model/list\", {\n cursor,\n limit: PAGE_LIMIT,\n includeHidden: false,\n }));\n for (const raw of response.data) {\n const model = mapModel(raw);\n if (model !== null) models.push(model);\n }\n if (response.nextCursor === null) {\n return { version: MODEL_CATALOG_VERSION, status: \"ready\", provider: \"codex\", models };\n }\n cursor = response.nextCursor;\n }\n throw new Error(\"model catalog pagination limit exceeded\");\n })();\n return await Promise.race([list, deadline]);\n } catch (error) {\n return classify(error);\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n await transport?.close();\n }\n}\n","import { buildIsolationConfig, buildPrompt, type PreparedStepLike } from \"./config.js\";\nimport { CodexDispatchError } from \"./error.js\";\nimport { CodexAppServerTransport } from \"./app_server_transport.js\";\nimport type { PreparedSetupComponent } from \"./prepare.js\";\nimport type { PreparedEnrichComponent } from \"./enrich_prepare.js\";\nimport {\n SESSION_REFERENCE_VERSION,\n type CodexArtifactReference,\n type CodexHistoryItem,\n type CodexHistoryTurn,\n type CodexSessionEvent,\n type CodexSessionHistory,\n type CodexSessionReference,\n type CodexTurnReference,\n type SessionIsolationOptions,\n type SessionTurnStatus,\n} from \"./session_types.js\";\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\ninterface ActiveTurn {\n started: boolean;\n pendingTools: Set<string>;\n successfulTools: number;\n hasAnswer: boolean;\n}\n\ninterface TurnWaiter {\n resolve: (turn: CodexTurnReference) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\nconst FORBIDDEN_ITEM_TYPES = new Set([\n \"commandExecution\",\n \"fileChange\",\n \"webSearch\",\n \"imageGeneration\",\n \"collabAgentToolCall\",\n \"subAgentActivity\",\n \"dynamicToolCall\",\n \"imageView\",\n \"sleep\",\n \"enteredReviewMode\",\n \"exitedReviewMode\",\n]);\n\nconst PASSIVE_ITEM_TYPES = new Set([\n \"userMessage\",\n \"agentMessage\",\n \"reasoning\",\n \"plan\",\n \"compacted\",\n \"contextCompaction\",\n]);\n\nconst IGNORED_NOTIFICATIONS = new Set([\n \"skills/changed\",\n \"thread/name/updated\",\n \"thread/goal/updated\",\n \"thread/goal/cleared\",\n \"thread/settings/updated\",\n \"thread/status/changed\",\n \"thread/tokenUsage/updated\",\n \"thread/compacted\",\n \"turn/diff/updated\",\n \"turn/plan/updated\",\n \"item/agentMessage/delta\",\n \"item/plan/delta\",\n \"item/mcpToolCall/progress\",\n \"item/reasoning/summaryTextDelta\",\n \"item/reasoning/summaryPartAdded\",\n \"item/reasoning/textDelta\",\n \"mcpServer/startupStatus/updated\",\n \"account/updated\",\n \"account/rateLimits/updated\",\n \"app/list/updated\",\n \"remoteControl/status/changed\",\n \"fs/changed\",\n \"model/rerouted\",\n \"model/verification\",\n \"model/safetyBuffering/updated\",\n \"turn/moderationMetadata\",\n \"warning\",\n \"guardianWarning\",\n \"deprecationNotice\",\n]);\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requiredRecord(value: unknown, context: string): JsonRecord {\n if (!isRecord(value)) throw new CodexDispatchError(`${context} requires an object`);\n return value;\n}\n\nfunction requiredString(record: JsonRecord, key: string, context: string): string {\n const value = record[key];\n if (typeof value !== \"string\" || value.length === 0) {\n throw new CodexDispatchError(`${context} requires string ${key}`);\n }\n return value;\n}\n\nfunction sessionReference(thread: JsonRecord): CodexSessionReference {\n return {\n version: SESSION_REFERENCE_VERSION,\n target: \"codex:local\",\n threadId: requiredString(thread, \"id\", \"thread\"),\n forkedFromThreadId:\n typeof thread[\"forkedFromId\"] === \"string\" ? thread[\"forkedFromId\"] : null,\n };\n}\n\nfunction turnStatus(value: unknown): SessionTurnStatus {\n switch (value) {\n case \"inProgress\":\n return \"in_progress\";\n case \"completed\":\n case \"interrupted\":\n case \"failed\":\n return value;\n default:\n throw new CodexDispatchError(\"turn requires a recognized status\");\n }\n}\n\nfunction turnReference(threadId: string, turn: JsonRecord): CodexTurnReference {\n return {\n threadId,\n turnId: requiredString(turn, \"id\", \"turn\"),\n status: turnStatus(turn[\"status\"]),\n };\n}\n\nfunction validateReference(reference: CodexSessionReference): void {\n if (\n reference.version !== SESSION_REFERENCE_VERSION ||\n reference.target !== \"codex:local\" ||\n reference.threadId.length === 0\n ) {\n throw new CodexDispatchError(\"invalid codex session reference\");\n }\n}\n\nexport class CodexSessionRuntime {\n private transport!: CodexAppServerTransport;\n private session: CodexSessionReference | null = null;\n private readonly activeTurns = new Map<string, ActiveTurn>();\n private readonly waiters = new Map<string, TurnWaiter[]>();\n private readonly stepNameByTurn = new Map<string, string>();\n private disconnected = false;\n\n private constructor(\n private readonly prepared: PreparedSetupComponent | PreparedEnrichComponent,\n private readonly options: SessionIsolationOptions,\n ) {}\n\n /**\n * The model bound to this persistent thread for its whole lifetime. `thread/start` takes a\n * single `model` with no per-turn override, so unlike Setup's one-shot-process-per-step\n * transport, every step dispatched through one session must resolve to the same model — see\n * `enrich_prepare.ts`'s single-tier-per-component requirement, which is what makes this true by\n * construction rather than by convention.\n */\n private get model(): string {\n return this.prepared.steps[0]!.model;\n }\n\n static async connect(\n prepared: PreparedSetupComponent | PreparedEnrichComponent,\n options: SessionIsolationOptions,\n ): Promise<CodexSessionRuntime> {\n if (prepared.steps.length === 0) {\n throw new CodexDispatchError(\"cannot connect a session runtime without at least one prepared step\");\n }\n const sessionModel = prepared.steps[0]!.model;\n for (const step of prepared.steps) {\n if (step.model !== sessionModel) {\n throw new CodexDispatchError(\n \"this transport's persistent session is bound to one model per thread; \" +\n `step '${step.name}' requires a different model than the session's first step`,\n );\n }\n }\n const runtime = new CodexSessionRuntime(prepared, options);\n runtime.transport = await CodexAppServerTransport.start(\n prepared,\n options,\n (method, params) => runtime.onNotification(method, params),\n (error) => runtime.onDisconnect(error),\n );\n return runtime;\n }\n\n async start(): Promise<CodexSessionReference> {\n this.ensureConnected();\n if (this.session !== null) {\n throw new CodexDispatchError(\"a session is already loaded; use a new runtime to start another\");\n }\n const result = requiredRecord(\n await this.transport.request(\"thread/start\", {\n model: this.model,\n cwd: this.options.cwd,\n approvalPolicy: \"never\",\n sandbox: \"read-only\",\n config: buildIsolationConfig(this.prepared),\n ephemeral: false,\n historyMode: \"legacy\",\n environments: [],\n runtimeWorkspaceRoots: [],\n selectedCapabilityRoots: [],\n dynamicTools: [],\n experimentalRawEvents: false,\n }),\n \"thread/start response\",\n );\n const reference = sessionReference(requiredRecord(result[\"thread\"], \"thread/start thread\"));\n this.session = reference;\n this.emit({ t: \"session_started\", session: reference });\n return reference;\n }\n\n async resume(reference: CodexSessionReference): Promise<CodexSessionReference> {\n validateReference(reference);\n this.ensureConnected();\n this.requireNoActiveTurns(\"resume\");\n if (this.session !== null && this.session.threadId !== reference.threadId) {\n throw new CodexDispatchError(\n \"a different session is already loaded; use a new runtime to resume another\",\n );\n }\n const result = requiredRecord(\n await this.transport.request(\"thread/resume\", {\n threadId: reference.threadId,\n model: this.model,\n cwd: this.options.cwd,\n approvalPolicy: \"never\",\n sandbox: \"read-only\",\n config: buildIsolationConfig(this.prepared),\n runtimeWorkspaceRoots: [],\n }),\n \"thread/resume response\",\n );\n const resumed = sessionReference(requiredRecord(result[\"thread\"], \"thread/resume thread\"));\n if (resumed.threadId !== reference.threadId) {\n throw new CodexDispatchError(\"thread/resume returned a different thread id\");\n }\n this.session = resumed;\n this.emit({ t: \"session_resumed\", session: resumed });\n return resumed;\n }\n\n async read(reference: CodexSessionReference): Promise<CodexSessionHistory> {\n validateReference(reference);\n this.ensureConnected();\n const result = requiredRecord(\n await this.transport.request(\"thread/read\", { threadId: reference.threadId, includeTurns: true }),\n \"thread/read response\",\n );\n const thread = requiredRecord(result[\"thread\"], \"thread/read thread\");\n const readReference = sessionReference(thread);\n if (readReference.threadId !== reference.threadId) {\n throw new CodexDispatchError(\"thread/read returned a different thread id\");\n }\n const turns = Array.isArray(thread[\"turns\"])\n ? thread[\"turns\"].map((turn) => this.projectHistoryTurn(reference.threadId, turn))\n : [];\n return { session: readReference, turns };\n }\n\n /**\n * `step`/`inputs` default to this component's first (and, for every existing single-step\n * fixture, only) step with no marshalled inputs — so every pre-existing caller that never named\n * a step keeps building the exact same prompt as before. A multi-step caller (the n-step Enrich\n * executor) passes the step actually being dispatched this turn, plus that step's marshalled\n * `consumes` values, and this records which step owns the resulting turn id so the\n * `step_start`/`step_finish` events this turn emits are attributed correctly rather than always\n * naming the component's first step.\n */\n async turn(\n reference: CodexSessionReference,\n input: string,\n step: PreparedStepLike = this.prepared.steps[0]!,\n inputs: Record<string, unknown> = {},\n ): Promise<CodexTurnReference> {\n this.requireCurrent(reference);\n if (input.length === 0) throw new CodexDispatchError(\"turn input must not be empty\");\n const result = requiredRecord(\n await this.transport.request(\"turn/start\", {\n threadId: reference.threadId,\n input: [\n { type: \"text\", text: buildPrompt(this.prepared, step, input, inputs), text_elements: [] },\n ],\n approvalPolicy: \"never\",\n environments: [],\n runtimeWorkspaceRoots: [],\n }),\n \"turn/start response\",\n );\n const turn = turnReference(reference.threadId, requiredRecord(result[\"turn\"], \"turn/start turn\"));\n if (turn.status !== \"in_progress\") {\n throw new CodexDispatchError(\"turn/start did not return an in-progress turn\");\n }\n this.ensureActiveTurn(turn.turnId);\n this.stepNameByTurn.set(turn.turnId, step.name);\n return turn;\n }\n\n async steer(\n reference: CodexSessionReference,\n turnId: string,\n input: string,\n ): Promise<CodexTurnReference> {\n this.requireCurrent(reference);\n const result = requiredRecord(\n await this.transport.request(\"turn/steer\", {\n threadId: reference.threadId,\n expectedTurnId: turnId,\n input: [{ type: \"text\", text: input, text_elements: [] }],\n }),\n \"turn/steer response\",\n );\n if (requiredString(result, \"turnId\", \"turn/steer response\") !== turnId) {\n throw new CodexDispatchError(\"turn/steer returned a different turn id\");\n }\n return { threadId: reference.threadId, turnId, status: \"in_progress\" };\n }\n\n async interrupt(reference: CodexSessionReference, turnId: string): Promise<void> {\n this.requireCurrent(reference);\n await this.transport.request(\"turn/interrupt\", { threadId: reference.threadId, turnId });\n }\n\n async fork(\n reference: CodexSessionReference,\n lastTurnId?: string,\n ): Promise<CodexSessionReference> {\n validateReference(reference);\n this.ensureConnected();\n this.requireNoActiveTurns(\"fork\");\n const result = requiredRecord(\n await this.transport.request(\"thread/fork\", {\n threadId: reference.threadId,\n ...(lastTurnId === undefined ? {} : { lastTurnId }),\n model: this.model,\n cwd: this.options.cwd,\n approvalPolicy: \"never\",\n sandbox: \"read-only\",\n config: buildIsolationConfig(this.prepared),\n ephemeral: false,\n runtimeWorkspaceRoots: [],\n }),\n \"thread/fork response\",\n );\n const forked = sessionReference(requiredRecord(result[\"thread\"], \"thread/fork thread\"));\n if (forked.threadId === reference.threadId || forked.forkedFromThreadId !== reference.threadId) {\n throw new CodexDispatchError(\"thread/fork returned an invalid lineage\");\n }\n this.emit({ t: \"session_forked\", session: forked });\n return forked;\n }\n\n waitForTurn(turn: CodexTurnReference, timeoutMs = this.options.timeoutMs ?? 120_000): Promise<CodexTurnReference> {\n if (turn.status !== \"in_progress\") return Promise.resolve(turn);\n if (this.disconnected || !this.activeTurns.has(turn.turnId)) {\n return Promise.reject(new CodexDispatchError(\"turn is no longer active; resume required\"));\n }\n return new Promise((resolveWaiter, rejectWaiter) => {\n const timer = setTimeout(() => {\n this.removeWaiter(turn.turnId, waiter);\n const error = new CodexDispatchError(`turn '${turn.turnId}' timed out`);\n void (async () => {\n try {\n await this.interrupt(\n { version: SESSION_REFERENCE_VERSION, target: \"codex:local\", threadId: turn.threadId, forkedFromThreadId: null },\n turn.turnId,\n );\n } catch {\n // The transport is closed below even when best-effort interrupt fails.\n }\n this.onDisconnect(error, \"turn_timeout\");\n await this.transport.close();\n rejectWaiter(error);\n })();\n }, timeoutMs);\n const waiter: TurnWaiter = { resolve: resolveWaiter, reject: rejectWaiter, timer };\n const list = this.waiters.get(turn.turnId) ?? [];\n list.push(waiter);\n this.waiters.set(turn.turnId, list);\n });\n }\n\n async restartAndResume(reference: CodexSessionReference): Promise<CodexSessionReference> {\n if (!this.disconnected && this.activeTurns.size > 0) {\n throw new CodexDispatchError(\"cannot restart while a turn is active; interrupt it first\");\n }\n await this.transport.close();\n const transport = await CodexAppServerTransport.start(\n this.prepared,\n this.options,\n (method, params) => this.onNotification(method, params),\n (error) => this.onDisconnect(error),\n );\n this.transport = transport;\n this.disconnected = false;\n try {\n return await this.resume(reference);\n } catch (error) {\n this.disconnected = true;\n await this.transport.close();\n throw error;\n }\n }\n\n async close(): Promise<void> {\n this.disconnected = true;\n const error = new CodexDispatchError(\"session runtime closed during an active turn\");\n for (const [turnId] of this.activeTurns) {\n this.settleWaiters(\n { threadId: this.session?.threadId ?? \"unknown\", turnId, status: \"failed\" },\n error,\n );\n }\n this.activeTurns.clear();\n this.stepNameByTurn.clear();\n await this.transport.close();\n }\n\n private onNotification(method: string, paramsValue: unknown): void {\n const params = requiredRecord(paramsValue, `${method} notification`);\n if (method === \"thread/started\" || IGNORED_NOTIFICATIONS.has(method)) return;\n if (method === \"error\") {\n const threadId = requiredString(params, \"threadId\", method);\n this.requireNotificationThread(threadId);\n const turnId = requiredString(params, \"turnId\", method);\n requiredRecord(params[\"error\"], \"error notification error\");\n const active = this.activeTurns.get(turnId);\n if (!active?.started) {\n throw new CodexDispatchError(\"app-server error notification has no active turn\");\n }\n if (params[\"willRetry\"] === true) return;\n if (params[\"willRetry\"] !== false) {\n throw new CodexDispatchError(\"app-server error notification requires willRetry\");\n }\n throw new CodexDispatchError(\"app-server reported a terminal turn error\");\n }\n if (method === \"turn/started\") {\n const threadId = requiredString(params, \"threadId\", method);\n this.requireNotificationThread(threadId);\n const turn = turnReference(threadId, requiredRecord(params[\"turn\"], `${method} turn`));\n const active = this.ensureActiveTurn(turn.turnId);\n if (active.started) throw new CodexDispatchError(\"duplicate turn start notification\");\n active.started = true;\n this.emit({ t: \"turn_started\", turn });\n const stepName = this.stepNameByTurn.get(turn.turnId) ?? this.prepared.steps[0]!.name;\n this.emit({ threadId, turnId: turn.turnId, t: \"step_start\", id: stepName, name: stepName });\n return;\n }\n if (method === \"item/started\" || method === \"item/completed\") {\n this.onItem(method, params);\n return;\n }\n if (method === \"turn/completed\") {\n this.onTurnCompleted(params);\n return;\n }\n throw new CodexDispatchError(`unsupported app-server notification '${method}'`);\n }\n\n private onItem(method: \"item/started\" | \"item/completed\", params: JsonRecord): void {\n const threadId = requiredString(params, \"threadId\", method);\n this.requireNotificationThread(threadId);\n const turnId = requiredString(params, \"turnId\", method);\n const item = requiredRecord(params[\"item\"], `${method} item`);\n const type = requiredString(item, \"type\", `${method} item`);\n if (FORBIDDEN_ITEM_TYPES.has(type)) {\n throw new CodexDispatchError(`isolation violation: app-server emitted forbidden '${type}'`);\n }\n const active = this.ensureActiveTurn(turnId);\n if (!active.started) throw new CodexDispatchError(\"item emitted before turn started\");\n if (type === \"mcpToolCall\") {\n const itemId = requiredString(item, \"id\", type);\n const server = requiredString(item, \"server\", type);\n const tool = requiredString(item, \"tool\", type);\n if (server !== this.prepared.mcp.name || !this.prepared.enabledTools.includes(tool)) {\n throw new CodexDispatchError(`isolation violation: non-allowlisted MCP tool '${server}.${tool}'`);\n }\n if (method === \"item/started\") {\n if (item[\"status\"] !== \"inProgress\") {\n throw new CodexDispatchError(\"MCP item start requires in-progress status\");\n }\n if (active.pendingTools.has(itemId)) throw new CodexDispatchError(\"duplicate MCP item start\");\n active.pendingTools.add(itemId);\n this.emit({ threadId, turnId, t: \"tool_call\", id: itemId, name: `${server}.${tool}` });\n return;\n }\n if (!active.pendingTools.delete(itemId)) throw new CodexDispatchError(\"MCP item completed without start\");\n const status = requiredString(item, \"status\", type);\n if (status !== \"completed\" && status !== \"failed\") {\n throw new CodexDispatchError(\"MCP item completed with an invalid status\");\n }\n const ok = status === \"completed\" && (item[\"error\"] === null || item[\"error\"] === undefined);\n if (ok) active.successfulTools += 1;\n const reference: CodexArtifactReference = {\n version: SESSION_REFERENCE_VERSION,\n kind: \"mcp_tool_result\",\n threadId,\n turnId,\n itemId,\n server,\n tool,\n ok,\n };\n this.emit({ t: \"artifact\", reference });\n this.emit({ threadId, turnId, t: \"tool_result\", id: itemId, ok, ...(ok ? {} : { error: \"allowlisted MCP tool failed\" }) });\n return;\n }\n if (!PASSIVE_ITEM_TYPES.has(type)) {\n throw new CodexDispatchError(`unsupported app-server item type '${type}'`);\n }\n if (method === \"item/completed\" && type === \"agentMessage\") {\n const text = requiredString(item, \"text\", type);\n active.hasAnswer = true;\n this.emit({ threadId, turnId, t: \"answer\", text });\n }\n }\n\n private onTurnCompleted(params: JsonRecord): void {\n const threadId = requiredString(params, \"threadId\", \"turn/completed\");\n this.requireNotificationThread(threadId);\n const turn = turnReference(threadId, requiredRecord(params[\"turn\"], \"turn/completed turn\"));\n const active = this.activeTurns.get(turn.turnId);\n if (!active) throw new CodexDispatchError(\"turn completed without starting\");\n if (!active.started) throw new CodexDispatchError(\"turn completed before start notification\");\n if (active.pendingTools.size > 0) throw new CodexDispatchError(\"turn completed with pending MCP tools\");\n if (turn.status === \"completed\" && (active.successfulTools === 0 || !active.hasAnswer)) {\n throw new CodexDispatchError(\"completed turn lacks a successful allowlisted tool or answer\");\n }\n this.activeTurns.delete(turn.turnId);\n const ok = turn.status === \"completed\";\n const stepName = this.stepNameByTurn.get(turn.turnId) ?? this.prepared.steps[0]!.name;\n this.stepNameByTurn.delete(turn.turnId);\n this.emit({ threadId, turnId: turn.turnId, t: \"step_finish\", id: stepName, ok });\n this.emit({ t: \"turn_completed\", turn });\n const error = turn.status === \"failed\" ? new CodexDispatchError(`turn '${turn.turnId}' failed`) : null;\n this.settleWaiters(turn, error);\n }\n\n private projectHistoryTurn(threadId: string, value: unknown): CodexHistoryTurn {\n const turn = requiredRecord(value, \"history turn\");\n const reference = turnReference(threadId, turn);\n const items: CodexHistoryItem[] = [];\n if (Array.isArray(turn[\"items\"])) {\n for (const itemValue of turn[\"items\"]) {\n const item = requiredRecord(itemValue, \"history item\");\n const type = requiredString(item, \"type\", \"history item\");\n if (type === \"agentMessage\") {\n items.push({ type: \"assistant\", itemId: requiredString(item, \"id\", type) });\n } else if (type === \"userMessage\") {\n items.push({ type: \"user\", itemId: requiredString(item, \"id\", type) });\n } else if (type === \"mcpToolCall\") {\n const server = requiredString(item, \"server\", type);\n const tool = requiredString(item, \"tool\", type);\n if (server !== this.prepared.mcp.name || !this.prepared.enabledTools.includes(tool)) {\n throw new CodexDispatchError(\"history contains a non-allowlisted MCP tool\");\n }\n const status = requiredString(item, \"status\", type);\n if (status !== \"completed\" && status !== \"failed\") {\n throw new CodexDispatchError(\"history MCP item has an invalid status\");\n }\n items.push({\n type: \"artifact\",\n reference: {\n version: SESSION_REFERENCE_VERSION,\n kind: \"mcp_tool_result\",\n threadId,\n turnId: reference.turnId,\n itemId: requiredString(item, \"id\", type),\n server,\n tool,\n ok: status === \"completed\" && (item[\"error\"] === null || item[\"error\"] === undefined),\n },\n });\n } else if (FORBIDDEN_ITEM_TYPES.has(type)) {\n throw new CodexDispatchError(`history contains forbidden '${type}' item`);\n } else if (!PASSIVE_ITEM_TYPES.has(type)) {\n throw new CodexDispatchError(`history contains unsupported '${type}' item`);\n }\n }\n }\n return { id: reference.turnId, status: reference.status, items };\n }\n\n private ensureActiveTurn(turnId: string): ActiveTurn {\n let active = this.activeTurns.get(turnId);\n if (!active) {\n active = { started: false, pendingTools: new Set(), successfulTools: 0, hasAnswer: false };\n this.activeTurns.set(turnId, active);\n }\n return active;\n }\n\n private requireCurrent(reference: CodexSessionReference): void {\n validateReference(reference);\n this.ensureConnected();\n if (this.session?.threadId !== reference.threadId) {\n throw new CodexDispatchError(\"session reference is not loaded; resume it first\");\n }\n }\n\n private requireNotificationThread(threadId: string): void {\n if (this.session?.threadId !== threadId) {\n throw new CodexDispatchError(\"app-server notification belongs to a different thread\");\n }\n }\n\n private requireNoActiveTurns(operation: string): void {\n if (this.activeTurns.size > 0) {\n throw new CodexDispatchError(\n `cannot ${operation} while a turn is active; interrupt it first`,\n );\n }\n }\n\n private ensureConnected(): void {\n if (this.disconnected) throw new CodexDispatchError(\"app-server transport disconnected; resume required\");\n }\n\n private onDisconnect(\n protocolError?: CodexDispatchError,\n reasonOverride?: \"turn_timeout\",\n ): void {\n if (this.disconnected) return;\n this.disconnected = true;\n if (protocolError && reasonOverride === undefined) {\n this.emit({\n t: \"session_failed\",\n threadId: this.session?.threadId ?? null,\n reason: \"protocol_violation\",\n });\n } else {\n const reason = reasonOverride ?? (this.activeTurns.size > 0 ? \"app_server_crash\" : \"transport_disconnect\");\n this.emit({ t: \"session_recoverable\", threadId: this.session?.threadId ?? null, reason });\n }\n for (const [turnId] of this.activeTurns) {\n this.settleWaiters(\n { threadId: this.session?.threadId ?? \"unknown\", turnId, status: \"failed\" },\n protocolError ?? new CodexDispatchError(\"app-server disconnected during an active turn\"),\n );\n }\n this.activeTurns.clear();\n this.stepNameByTurn.clear();\n }\n\n private settleWaiters(turn: CodexTurnReference, error: Error | null): void {\n const waiters = this.waiters.get(turn.turnId) ?? [];\n this.waiters.delete(turn.turnId);\n for (const waiter of waiters) {\n clearTimeout(waiter.timer);\n if (error) waiter.reject(error);\n else waiter.resolve(turn);\n }\n }\n\n private removeWaiter(turnId: string, waiter: TurnWaiter): void {\n const remaining = (this.waiters.get(turnId) ?? []).filter((candidate) => candidate !== waiter);\n if (remaining.length === 0) this.waiters.delete(turnId);\n else this.waiters.set(turnId, remaining);\n }\n\n private emit(event: CodexSessionEvent): void {\n this.options.onEvent?.(event);\n }\n}\n","import { CodexDispatchError } from \"./error.js\";\nimport type { PreparedEnrichComponent } from \"./enrich_prepare.js\";\nimport { CodexSessionRuntime } from \"./session.js\";\nimport type { CodexSessionEvent, SessionIsolationOptions } from \"./session_types.js\";\nimport { parseStepTerminal, shouldRunStep, type StepOutcome } from \"./step_engine.js\";\n\n/** One step's dispatch-time evidence: whether it ran (an on_failure guard may skip it) and, if it\n * ran, whether its terminal matched its declared `produces` slot. Mirrors `run.ts`'s\n * `SetupStepRunOutcome` — kept as a separate type (not imported from `run.ts`) so Setup and Enrich\n * stay two independent engines, by design. */\nexport interface EnrichStepRunOutcome {\n name: string;\n ran: boolean;\n ok: boolean;\n value?: unknown;\n}\n\nexport interface EnrichRunResult {\n target: \"codex:local\";\n component: string;\n /** The last step that actually ran's raw terminal text — unchanged for every existing\n * single-step component, since there the last step run is the only step run. */\n finalText: string;\n /** The parsed terminal object of the last step that actually ran. */\n value: unknown;\n events: CodexSessionEvent[];\n steps: EnrichStepRunOutcome[];\n}\n\n/**\n * Execute a read-only enrichment component's steps, in order, through one persistent Codex\n * app-server session. The Codex thread is created before the first model turn begins; this\n * preserves durable session history before any metered work can occur, while the host remains\n * owner of enrichment run bookkeeping. Every step of one dispatch shares the same thread — see\n * `session.ts`'s `CodexSessionRuntime.turn`, which now takes the current step and its marshalled\n * `consumes` inputs — with produces/consumes marshalled between turns exactly as `run.ts`'s\n * `runSetup` marshals them between one-shot processes, and the same recoverable-vs-fatal\n * on_failure evaluation (`shouldRunStep`/`parseStepTerminal`).\n */\nexport async function runEnrich(\n prepared: PreparedEnrichComponent,\n request: string,\n options: SessionIsolationOptions,\n): Promise<EnrichRunResult> {\n if (request.trim().length === 0) throw new CodexDispatchError(\"enrichment request must not be empty\");\n const events: CodexSessionEvent[] = [];\n // `CodexSessionRuntime` fans every event for the whole session's lifetime out through one\n // `onEvent` callback fixed at `connect()` time — there is no per-turn subscription. So each\n // step's answer is captured into this one mutable slot, reset immediately before that step's\n // turn starts, and read immediately after that turn completes; the loop below never has two\n // turns in flight at once, so there is no risk of one step reading another's answer.\n let currentAnswer: string | null = null;\n const onEvent = (event: CodexSessionEvent): void => {\n events.push(event);\n if (event.t === \"answer\") currentAnswer = event.text;\n options.onEvent?.(event);\n };\n const runtime = await CodexSessionRuntime.connect(prepared, { ...options, onEvent });\n try {\n const session = await runtime.start();\n const slots: Record<string, unknown> = {};\n const outcomes = new Map<string, StepOutcome>();\n const steps: EnrichStepRunOutcome[] = [];\n let lastFinalText: string | null = null;\n let lastValue: unknown;\n\n for (const step of prepared.steps) {\n if (!shouldRunStep(step.when, outcomes)) {\n outcomes.set(step.name, { ran: false });\n steps.push({ name: step.name, ran: false, ok: false });\n continue;\n }\n const inputs = Object.fromEntries(step.consumes.map((name) => [name, slots[name]]));\n currentAnswer = null;\n const turn = await runtime.turn(session, request, step, inputs);\n const completed = await runtime.waitForTurn(turn, options.timeoutMs ?? 120_000);\n if (completed.status !== \"completed\" || currentAnswer === null) {\n throw new CodexDispatchError(`enrichment step '${step.name}' did not complete with a terminal answer`);\n }\n const finalText: string = currentAnswer;\n // Same recoverable-vs-fatal rule as `run.ts`'s `runSetup`: a step's produces-mismatch is\n // only survivable when some later step's on_failure guard actually names it; otherwise it\n // fails the whole dispatch exactly as the original single-turn transport always did.\n const hasGuardedConsumer = prepared.steps.some((candidate) => candidate.when?.target === step.name);\n let record: Record<string, unknown>;\n try {\n record = parseStepTerminal(finalText, step.produces);\n } catch (error) {\n if (hasGuardedConsumer && error instanceof CodexDispatchError) {\n outcomes.set(step.name, { ran: true, ok: false });\n steps.push({ name: step.name, ran: true, ok: false });\n lastFinalText = finalText;\n continue;\n }\n throw error;\n }\n const value = record[step.produces];\n slots[step.produces] = value;\n outcomes.set(step.name, { ran: true, ok: true, value });\n steps.push({ name: step.name, ran: true, ok: true, value });\n lastFinalText = finalText;\n lastValue = record;\n }\n\n if (lastFinalText === null) {\n // Unreachable for any component `validateStepTopology` accepts — see `run.ts`'s identical\n // backstop for why: the only conditional step allowed is the last one, targeting a strictly\n // earlier step, so a component can only be conditional-only when it has zero steps, which\n // `prepareEnrich` already rejects.\n throw new CodexDispatchError(\"enrichment dispatch completed without running any step\");\n }\n return {\n target: prepared.target,\n component: prepared.componentId,\n finalText: lastFinalText,\n value: lastValue,\n events,\n steps,\n };\n } finally {\n await runtime.close();\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\n\nimport { buildCodexArgs, buildPrompt, sanitizeCodexEnvironment } from \"./config.js\";\nimport { CodexDispatchError } from \"./error.js\";\nimport { CodexJsonlMapper, type WarbleCodexEvent } from \"./events.js\";\nimport type { PreparedSetupComponent, PreparedSetupStep } from \"./prepare.js\";\nimport { parseStepTerminal, shouldRunStep, type StepOutcome } from \"./step_engine.js\";\n\nexport interface RunOptions {\n cwd: string;\n request: string;\n codexBin?: string;\n codexArgsPrefix?: string[];\n timeoutMs?: number;\n terminationGraceMs?: number;\n signal?: AbortSignal;\n env?: NodeJS.ProcessEnv;\n onEvent?: (event: WarbleCodexEvent) => void;\n}\n\n/** One step's dispatch-time evidence: whether it ran (an on_failure guard may skip it) and, if\n * it ran, whether its terminal matched its declared `produces` slot. */\nexport interface SetupStepRunOutcome {\n name: string;\n ran: boolean;\n ok: boolean;\n value?: unknown;\n}\n\nexport interface RunResult {\n target: \"codex:local\";\n component: string;\n /** The last step that actually ran's raw terminal text — unchanged for every existing\n * single-step component, since there the last step run is the only step run. */\n finalText: string;\n events: WarbleCodexEvent[];\n steps: SetupStepRunOutcome[];\n}\n\n/** Spawns exactly one Codex process for exactly one step, mirroring the transport's original\n * one-shot design per step rather than per dispatch — Setup has no persistent session to reuse\n * across steps, so each step gets its own child process. */\nasync function runOneStep(\n prepared: PreparedSetupComponent,\n step: PreparedSetupStep,\n inputs: Record<string, unknown>,\n options: RunOptions,\n events: WarbleCodexEvent[],\n): Promise<string> {\n const mapper = new CodexJsonlMapper(step.name, prepared.mcp.name, prepared.enabledTools);\n const args = buildCodexArgs(prepared, step, {\n cwd: options.cwd,\n ...(options.codexArgsPrefix ? { codexArgsPrefix: options.codexArgsPrefix } : {}),\n });\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn(options.codexBin ?? \"codex\", args, {\n cwd: options.cwd,\n env: sanitizeCodexEnvironment(options.env),\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n } catch (error) {\n throw new CodexDispatchError(`failed to start codex: ${String(error)}`);\n }\n if (child.stdin === null || child.stdout === null || child.stderr === null) {\n child.kill(\"SIGTERM\");\n throw new CodexDispatchError(\"failed to start codex with piped stdio\");\n }\n const childStdin = child.stdin;\n const childStdout = child.stdout;\n const childStderr = child.stderr;\n const exitPromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(\n (resolve, reject) => {\n child.once(\"error\", (error) =>\n reject(new CodexDispatchError(`failed to start codex: ${error.message}`)),\n );\n child.once(\"close\", (code, signal) => resolve({ code, signal }));\n },\n );\n childStderr.resume();\n\n let terminalError: Error | null = null;\n let terminationRequested = false;\n let killTimer: ReturnType<typeof setTimeout> | undefined;\n const terminationGraceMs = options.terminationGraceMs ?? 1_000;\n const signalProcessTree = (signal: NodeJS.Signals) => {\n if (child.pid === undefined) return;\n if (process.platform !== \"win32\") {\n try {\n process.kill(-child.pid, signal);\n return;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ESRCH\") return;\n }\n }\n child.kill(signal);\n };\n const terminateProcessTree = () => {\n if (terminationRequested) return;\n terminationRequested = true;\n signalProcessTree(\"SIGTERM\");\n killTimer = setTimeout(() => signalProcessTree(\"SIGKILL\"), terminationGraceMs);\n };\n const lines = createInterface({ input: childStdout });\n lines.on(\"line\", (line) => {\n if (line.trim().length === 0 || terminalError) return;\n try {\n for (const event of mapper.nextLine(line)) {\n events.push(event);\n options.onEvent?.(event);\n }\n } catch (error) {\n terminalError = error instanceof Error ? error : new Error(String(error));\n terminateProcessTree();\n }\n });\n\n const prompt = buildPrompt(prepared, step, options.request, inputs, { producedValue: \"string\" });\n childStdin.end(prompt);\n\n let aborted = false;\n const abort = () => {\n aborted = true;\n terminateProcessTree();\n };\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n const timeoutMs = options.timeoutMs ?? 120_000;\n const timer = setTimeout(abort, timeoutMs);\n\n const exit = await exitPromise.finally(() => {\n clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", abort);\n lines.close();\n if (terminationRequested) signalProcessTree(\"SIGKILL\");\n if (killTimer !== undefined) clearTimeout(killTimer);\n });\n\n if (terminalError) throw terminalError;\n if (aborted) {\n const reason = options.signal?.aborted ? \"cancelled\" : `timed out after ${timeoutMs}ms`;\n throw new CodexDispatchError(`codex dispatch ${reason}`);\n }\n if (exit.code !== 0) {\n throw new CodexDispatchError(\n `codex exited with ${exit.code ?? exit.signal ?? \"unknown\"}`,\n );\n }\n return mapper.result().finalText;\n}\n\nexport async function runSetup(\n prepared: PreparedSetupComponent,\n options: RunOptions,\n): Promise<RunResult> {\n if (options.signal?.aborted) {\n throw new CodexDispatchError(\"codex dispatch cancelled before start\");\n }\n const events: WarbleCodexEvent[] = [];\n const slots: Record<string, unknown> = {};\n const outcomes = new Map<string, StepOutcome>();\n const steps: SetupStepRunOutcome[] = [];\n let lastFinalText: string | null = null;\n\n for (const step of prepared.steps) {\n if (!shouldRunStep(step.when, outcomes)) {\n outcomes.set(step.name, { ran: false });\n steps.push({ name: step.name, ran: false, ok: false });\n continue;\n }\n const inputs = Object.fromEntries(step.consumes.map((name) => [name, slots[name]]));\n const finalText = await runOneStep(prepared, step, inputs, options, events);\n // Whether a step's produces-mismatch is fatal or recoverable depends on whether any later\n // step in this component actually guards on it — the accept-set-equals-execute-set invariant\n // applied the other way round: a step that no on_failure guard ever names must fail the whole\n // dispatch exactly as it always has, since nothing downstream is prepared to observe it fail.\n const hasGuardedConsumer = prepared.steps.some((candidate) => candidate.when?.target === step.name);\n let record: Record<string, unknown>;\n try {\n record = parseStepTerminal(finalText, step.produces);\n } catch (error) {\n if (hasGuardedConsumer && error instanceof CodexDispatchError) {\n outcomes.set(step.name, { ran: true, ok: false });\n steps.push({ name: step.name, ran: true, ok: false });\n lastFinalText = finalText;\n continue;\n }\n throw error;\n }\n const value = record[step.produces];\n slots[step.produces] = value;\n outcomes.set(step.name, { ran: true, ok: true, value });\n steps.push({ name: step.name, ran: true, ok: true, value });\n lastFinalText = finalText;\n }\n\n if (lastFinalText === null) {\n // Unreachable for any component `validateStepTopology` accepts: the only conditional step\n // allowed is the last one, and it must target a strictly earlier step, so a component can\n // only be conditional-only when it has zero steps, which prepare already rejects. Kept as a\n // defensive backstop, not a reachable branch.\n throw new CodexDispatchError(\"codex dispatch completed without running any step\");\n }\n return {\n target: prepared.target,\n component: prepared.componentId,\n finalText: lastFinalText,\n events,\n steps,\n };\n}\n","import { CodexDispatchError } from \"./error.js\";\n\nexport type WarbleCodexEvent =\n | { t: \"step_start\"; id: string; name: string }\n | { t: \"tool_call\"; id: string; name: string }\n | { t: \"tool_result\"; id: string; ok: boolean; error?: string }\n | { t: \"answer\"; text: string }\n | { t: \"step_finish\"; id: string; ok: boolean; detail?: string };\n\ninterface JsonRecord {\n [key: string]: unknown;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction itemOf(event: JsonRecord): JsonRecord | null {\n return isRecord(event[\"item\"]) ? event[\"item\"] : null;\n}\n\nfunction itemType(item: JsonRecord): string {\n return typeof item[\"type\"] === \"string\" ? item[\"type\"] : \"\";\n}\n\nfunction toolIdentity(item: JsonRecord): { server: string; tool: string; name: string } {\n const server = typeof item[\"server\"] === \"string\" ? item[\"server\"] : \"\";\n const tool = typeof item[\"tool\"] === \"string\" ? item[\"tool\"] : \"\";\n if (server.length === 0 || tool.length === 0) {\n throw new CodexDispatchError(\"mcp_tool_call requires string server and tool fields\");\n }\n return { server, tool, name: `${server}.${tool}` };\n}\n\nconst FORBIDDEN_ITEM_TYPES = new Set([\n \"command_execution\",\n \"file_change\",\n \"web_search\",\n \"image_generation\",\n \"collab_agent_tool_call\",\n]);\n\nexport class CodexJsonlMapper {\n private started = false;\n private finished = false;\n private threadStarted = false;\n private finalText: string | null = null;\n private failureDetail: string | null = null;\n private toolFailureDetail: string | null = null;\n private readonly pendingTools = new Map<string, string>();\n private successfulToolCount = 0;\n private readonly enabledTools: ReadonlySet<string>;\n\n constructor(\n private readonly stepId: string,\n private readonly expectedMcpServer: string,\n enabledTools: readonly string[],\n ) {\n this.enabledTools = new Set(enabledTools);\n }\n\n nextLine(line: string): WarbleCodexEvent[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch (error) {\n throw new CodexDispatchError(`codex stdout contained non-JSONL data: ${String(error)}`);\n }\n if (!isRecord(parsed) || typeof parsed[\"type\"] !== \"string\") {\n throw new CodexDispatchError(\"codex JSONL event requires a string type\");\n }\n const type = parsed[\"type\"];\n if (this.finished) {\n throw new CodexDispatchError(`codex emitted '${type}' after the terminal turn event`);\n }\n if (type === \"thread.started\") {\n if (this.threadStarted || this.started) {\n throw new CodexDispatchError(\"codex emitted duplicate or out-of-order thread.started\");\n }\n this.threadStarted = true;\n return [];\n }\n if (type === \"turn.started\") {\n if (!this.threadStarted) {\n throw new CodexDispatchError(\"codex emitted turn.started before thread.started\");\n }\n if (this.started) throw new CodexDispatchError(\"codex emitted duplicate turn.started\");\n this.started = true;\n return [{ t: \"step_start\", id: this.stepId, name: this.stepId }];\n }\n if (type === \"item.started\" || type === \"item.completed\") {\n if (!this.started) {\n throw new CodexDispatchError(`codex emitted ${type} before turn.started`);\n }\n return this.onItem(type, parsed);\n }\n if (type === \"turn.failed\" || type === \"error\") {\n return this.finish(false, type === \"turn.failed\" ? \"codex turn failed\" : \"codex runtime error\");\n }\n if (type === \"turn.completed\") {\n return this.finish(true);\n }\n return [];\n }\n\n result(): { finalText: string; threadStarted: boolean; turnCompleted: boolean } {\n if (!this.threadStarted) throw new CodexDispatchError(\"codex JSONL ended without thread.started\");\n if (!this.finished) throw new CodexDispatchError(\"codex JSONL ended without turn.completed\");\n if (this.failureDetail !== null) {\n throw new CodexDispatchError(`codex turn failed: ${this.failureDetail}`);\n }\n if (this.successfulToolCount === 0) {\n if (this.toolFailureDetail !== null) {\n throw new CodexDispatchError(`required MCP tool failed: ${this.toolFailureDetail}`);\n }\n throw new CodexDispatchError(\"codex turn completed without a successful allowlisted MCP tool call\");\n }\n if (this.finalText === null) throw new CodexDispatchError(\"codex JSONL ended without an agent message\");\n return {\n finalText: this.finalText,\n threadStarted: this.threadStarted,\n turnCompleted: this.finished,\n };\n }\n\n private onItem(\n eventType: \"item.started\" | \"item.completed\",\n event: JsonRecord,\n ): WarbleCodexEvent[] {\n const item = itemOf(event);\n if (!item) throw new CodexDispatchError(`${eventType} requires an item object`);\n const type = itemType(item);\n if (FORBIDDEN_ITEM_TYPES.has(type)) {\n throw new CodexDispatchError(\n `isolation violation: codex emitted forbidden '${type}' item`,\n );\n }\n if (type === \"mcp_tool_call\") {\n const id = typeof item[\"id\"] === \"string\" ? item[\"id\"] : \"\";\n if (id.length === 0) throw new CodexDispatchError(\"mcp_tool_call requires an id\");\n const identity = toolIdentity(item);\n if (\n identity.server !== this.expectedMcpServer ||\n !this.enabledTools.has(identity.tool)\n ) {\n throw new CodexDispatchError(\n `isolation violation: codex emitted non-allowlisted MCP tool '${identity.name}'`,\n );\n }\n if (eventType === \"item.started\") {\n if (this.pendingTools.has(id)) {\n throw new CodexDispatchError(`mcp_tool_call '${id}' started more than once`);\n }\n this.pendingTools.set(id, identity.name);\n return [\n {\n t: \"tool_call\",\n id,\n name: identity.name,\n },\n ];\n }\n const name = this.pendingTools.get(id);\n if (name === undefined) {\n throw new CodexDispatchError(`mcp_tool_call '${id}' completed without starting`);\n }\n if (name !== identity.name) {\n throw new CodexDispatchError(\n `mcp_tool_call '${id}' completed as '${identity.name}' after starting as '${name}'`,\n );\n }\n this.pendingTools.delete(id);\n const status = item[\"status\"];\n if (status !== \"completed\" && status !== \"failed\") {\n throw new CodexDispatchError(\n `completed mcp_tool_call '${id}' requires completed or failed status`,\n );\n }\n const failed =\n status === \"failed\" || (item[\"error\"] !== undefined && item[\"error\"] !== null);\n if (failed) this.toolFailureDetail = name;\n else this.successfulToolCount += 1;\n return [\n {\n t: \"tool_result\",\n id,\n ok: !failed,\n ...(failed ? { error: \"allowlisted MCP tool failed\" } : {}),\n },\n ];\n }\n if (eventType === \"item.completed\" && type === \"agent_message\") {\n const text = item[\"text\"];\n if (typeof text !== \"string\") {\n throw new CodexDispatchError(\"completed agent_message requires text\");\n }\n this.finalText = text;\n return [{ t: \"answer\", text }];\n }\n return [];\n }\n\n private finish(ok: boolean, detail?: string): WarbleCodexEvent[] {\n if (!this.started) {\n throw new CodexDispatchError(\"codex turn finished before turn.started\");\n }\n if (this.finished) throw new CodexDispatchError(\"codex emitted duplicate terminal turn event\");\n if (this.pendingTools.size > 0) {\n throw new CodexDispatchError(\n `codex turn finished with pending MCP tool calls: ${[...this.pendingTools.keys()].join(\", \")}`,\n );\n }\n if (ok && this.successfulToolCount === 0) {\n if (this.toolFailureDetail !== null) {\n throw new CodexDispatchError(`required MCP tool failed: ${this.toolFailureDetail}`);\n }\n throw new CodexDispatchError(\"codex turn completed without a successful allowlisted MCP tool call\");\n }\n if (ok && this.finalText === null) {\n throw new CodexDispatchError(\"codex JSONL ended without an agent message\");\n }\n this.finished = true;\n if (!ok) this.failureDetail = detail ?? \"unknown failure\";\n return [\n {\n t: \"step_finish\",\n id: this.stepId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C1E;AAEA,KAAK,EAAE,MAAM,CAAC,UAAmB;AAC/B,MAAI,iBAAiB,mBAAoB,MAAK,MAAM,OAAO;AAC3D,OAAK,iBAAiB,QAAQ,MAAM,SAAS,MAAM,UAAU,OAAO,KAAK,CAAC;AAC5E,CAAC;","names":["writeFileSync","resolve","isRecord","itemType","isAbsolute","isRecord","isAbsolute","existsSync","join","existsSync","join","isRecord","text","resolve","spawn","request","isAbsolute","text","record","unique","isAbsolute","isAbsolute","unique","isAbsolute","resolve","isRecord","record","resolve","IGNORED_NOTIFICATIONS","isRecord","record","sessionReference","turnStatus","turnReference","validateReference","text","record","spawn","createInterface","isRecord","FORBIDDEN_ITEM_TYPES","text","spawn","resolve","createInterface","record","resolve","mcp","prepared","text","writeFileSync","result"]}
|