@tangle-network/agent-runtime 3.0.1 → 3.0.2

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.
Files changed (72) hide show
  1. package/dist/{activation-kREPGozZ.d.ts → activation-BzC4bbcR.d.ts} +2 -2
  2. package/dist/{activation-BE0duxMf.js → activation-DJsJdvb7.js} +4 -4
  3. package/dist/{activation-BE0duxMf.js.map → activation-DJsJdvb7.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +3 -3
  6. package/dist/{bundle-ZHO7QFZw.js → bundle-DYwJ3alD.js} +2 -2
  7. package/dist/{bundle-ZHO7QFZw.js.map → bundle-DYwJ3alD.js.map} +1 -1
  8. package/dist/candidate-execution/index.d.ts +2 -2
  9. package/dist/candidate-execution/index.js +4 -4
  10. package/dist/{coordination-manager-B9goecNC.js → coordination-manager-CXlabreV.js} +4 -4
  11. package/dist/{coordination-manager-B9goecNC.js.map → coordination-manager-CXlabreV.js.map} +1 -1
  12. package/dist/{delegate-C-wmgWCF.js → delegate-DgMQo-K8.js} +2 -2
  13. package/dist/{delegate-C-wmgWCF.js.map → delegate-DgMQo-K8.js.map} +1 -1
  14. package/dist/durable.d.ts +1 -1
  15. package/dist/durable.js +8 -8
  16. package/dist/{graph-C_564r0C.js → graph-DSVXDbSf.js} +5 -5
  17. package/dist/{graph-C_564r0C.js.map → graph-DSVXDbSf.js.map} +1 -1
  18. package/dist/{improve-BZdFdcUC.js → improve-CMSrJ22U.js} +7 -7
  19. package/dist/{improve-BZdFdcUC.js.map → improve-CMSrJ22U.js.map} +1 -1
  20. package/dist/index.d.ts +4 -4
  21. package/dist/index.js +10 -10
  22. package/dist/intelligence.d.ts +4 -4
  23. package/dist/intelligence.js +7 -7
  24. package/dist/kernel.d.ts +2 -2
  25. package/dist/kernel.js +11 -11
  26. package/dist/{loop-runner-D8NZLPE5.d.ts → loop-runner-BU5HX1Y7.d.ts} +2 -2
  27. package/dist/{loop-runner-_9_GtzO5.js → loop-runner-De7RIY_2.js} +2 -2
  28. package/dist/{loop-runner-_9_GtzO5.js.map → loop-runner-De7RIY_2.js.map} +1 -1
  29. package/dist/loop-runner-bin.d.ts +1 -1
  30. package/dist/loop-runner-bin.js +1 -1
  31. package/dist/mcp/bin.js +3 -3
  32. package/dist/mcp/index.d.ts +1 -1
  33. package/dist/mcp/index.js +6 -6
  34. package/dist/{prepare-CU0LM1_X.js → prepare-BfaOus1-.js} +3 -3
  35. package/dist/{prepare-CU0LM1_X.js.map → prepare-BfaOus1-.js.map} +1 -1
  36. package/dist/{profile-By6JkIQi.js → profile-CvucOo-Q.js} +2 -2
  37. package/dist/{profile-By6JkIQi.js.map → profile-CvucOo-Q.js.map} +1 -1
  38. package/dist/profiles.d.ts +1 -1
  39. package/dist/{protected-model-port-BBsYuEY0.d.ts → protected-model-port-DEsNIYi1.d.ts} +2 -2
  40. package/dist/{provision-supervisor-DX4fd6Ib.js → provision-supervisor-BoOIYwov.js} +5 -5
  41. package/dist/{provision-supervisor-DX4fd6Ib.js.map → provision-supervisor-BoOIYwov.js.map} +1 -1
  42. package/dist/{run-cancellation-BTjyVpVW.js → run-cancellation-3tqWES3A.js} +2 -2
  43. package/dist/{run-cancellation-BTjyVpVW.js.map → run-cancellation-3tqWES3A.js.map} +1 -1
  44. package/dist/{runtime-DsH0QnW0.js → runtime-1dL7Te6f.js} +12 -12
  45. package/dist/{runtime-DsH0QnW0.js.map → runtime-1dL7Te6f.js.map} +1 -1
  46. package/dist/{scope-BeI3tmVX.js → scope-CwhYLg6s.js} +2 -2
  47. package/dist/{scope-BeI3tmVX.js.map → scope-CwhYLg6s.js.map} +1 -1
  48. package/dist/{search-executor-C-E-umcI.js → search-executor-5d-avuUt.js} +4 -4
  49. package/dist/{search-executor-C-E-umcI.js.map → search-executor-5d-avuUt.js.map} +1 -1
  50. package/dist/{server-DAYqKU6o.js → server-DtAPLLu3.js} +4 -4
  51. package/dist/{server-DAYqKU6o.js.map → server-DtAPLLu3.js.map} +1 -1
  52. package/dist/{structural-rollout-DHdmB9MR.js → structural-rollout-Dk0NlRpZ.js} +4 -4
  53. package/dist/{structural-rollout-DHdmB9MR.js.map → structural-rollout-Dk0NlRpZ.js.map} +1 -1
  54. package/dist/{supervise-QzwZc6K2.js → supervise-DYtL1RvC.js} +6 -6
  55. package/dist/{supervise-QzwZc6K2.js.map → supervise-DYtL1RvC.js.map} +1 -1
  56. package/dist/{supervision-discovery-CyvJVbTM.js → supervision-discovery-EtxsGdsk.js} +3 -3
  57. package/dist/{supervision-discovery-CyvJVbTM.js.map → supervision-discovery-EtxsGdsk.js.map} +1 -1
  58. package/dist/{supervisor-REUnT7iX.js → supervisor-CORJv7-r.js} +3 -3
  59. package/dist/{supervisor-REUnT7iX.js.map → supervisor-CORJv7-r.js.map} +1 -1
  60. package/dist/testing.d.ts +1 -1
  61. package/dist/testing.js +13 -13
  62. package/dist/{top-web-DRfER2jW.js → top-web-B0a7QfaZ.js} +4 -4
  63. package/dist/{top-web-DRfER2jW.js.map → top-web-B0a7QfaZ.js.map} +1 -1
  64. package/dist/tui/bin.js +3 -3
  65. package/dist/tui/index.d.ts +2 -2
  66. package/dist/tui/index.js +2 -2
  67. package/dist/{types-Bm4xC_e-.d.ts → types-QS0ItMiE.d.ts} +2 -2
  68. package/dist/{workspace-streams-BSEkDu3H.js → workspace-streams-COSTjQLW.js} +17 -20
  69. package/dist/workspace-streams-COSTjQLW.js.map +1 -0
  70. package/dist/{workspace-streams-BdZsd12p.d.ts → workspace-streams-DbKiDOWA.d.ts} +3 -2
  71. package/package.json +1 -1
  72. package/dist/workspace-streams-BSEkDu3H.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { i as ConfigError } from "./errors-AzSuGI23.js";
2
- import { t as supervise } from "./supervise-QzwZc6K2.js";
2
+ import { t as supervise } from "./supervise-DYtL1RvC.js";
3
3
  import { agentProfileSchema } from "@tangle-network/agent-interface";
4
4
  import { computeFindingId, makeFinding } from "@tangle-network/agent-eval";
5
5
  // src/runtime/supervise/authoring.ts
@@ -205,4 +205,4 @@ async function delegate(intent, opts) {
205
205
  }
206
206
  export { defaultProfileRichnessThresholds as a, assessAuthoredProfile as i, delegate as n, profileRichnessFinding as o, asAuthoredProfile as r, supervisorInstructions as s, defaultDelegateBudget as t };
207
207
 
208
- //# sourceMappingURL=delegate-C-wmgWCF.js.map
208
+ //# sourceMappingURL=delegate-DgMQo-K8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"delegate-C-wmgWCF.js","names":[],"sources":["../src/runtime/supervise/authoring.ts","../src/runtime/supervise/delegate.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions, tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific guidance are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt\n}\n\n/** Narrow an untyped `spawn_worker` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n if (!resolveSystemPrompt(parsed.data).trim()) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt },\n }\n}\n\n/** The supervisor skill: an explicit profile-authoring instruction, never an implicit Runtime\n * policy. Editing this text changes how a profile designs the descendants it spawns. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_worker with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.appendSystemPrompt: rich additive instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • tools.agent_runtime_coordination_spawn_worker: true ONLY when this child should author and drive descendants. Add only the other agent_runtime_coordination_<verb> tools it will call, such as observe_agent or steer_agent.',\n ' • A child with spawn_worker MUST carry this complete profile-authoring instruction as an immutable resources.skills entry with resources.failOnError: true, so it can author its own descendants from the same contract.',\n ' • metadata may describe the work, but it never grants recursion or selects a Runtime execution path.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n '3. End your turn while your workers run: Runtime wakes you with each settled worker. A settlement says valid:true only if the deployable check passed.',\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.appendSystemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n \"5. read_journal to re-read YOUR OWN record before you decide the next move: every spawn you made, every settle, every question and answer, every steer, every analyst finding — oldest first, this node only, including what you did before a restart. Use it to see what you already tried instead of trying it again. It is paged: pass the returned nextRow as the next call's sinceRow, narrow with kinds, and raise limit/maxBytes only as far as you will actually read. A truncated:true page means a bound cut it short — keep paging before you conclude you have read everything.\",\n '6. AUTHOR YOUR OWN LENS when the questions you can already ask of a settled trace do not cover the failure you are chasing: define_analyst takes an id, a description, an area, the question in your own words, the instructions for answering it with trace evidence, and the smallest toolGroup that can answer it (model is the seat it runs on; omit it for the run default). It is DATA, never code. Then run_analyst it on any settled worker like a lens the run shipped with, and read the finding. list_analysts shows what you have. Define a lens when you need a different question asked — not a second copy of a question already on the menu.',\n '7. EVERY refusal you get back carries a `reason` naming the exact unmet condition. Read it and change that condition — a spawn refused for budget-exhausted needs a smaller budget or the refund of a settled worker, an invalid-profile needs the named field fixed, a submit_result refused because the check THREW is a broken check to report, not a result to resubmit. Never repeat a call that was refused without changing what it was refused for.',\n '8. ask_parent ONLY when you genuinely cannot decide, and then READ ITS OUTCOME. \"queued-for-parent\" means an inbox above you now holds the question. \"no-parent\" means no inbox above you is configured to receive it: the question is still on the run record for anyone watching, but nothing will route an answer back to you, so do not block. Decide it with answer_question, or answer_question with deferReason to record that it stays open, and carry on — a blocking question left undecided also refuses your stop.',\n '9. Once the work is delivered, end your turn with nothing left running.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// receives in its next wake — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** Resolved authored guidance from replacement, addition and instruction sections. */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read authored guidance without requiring replacement of native coding instructions. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n return [\n Reflect.get(o, 'systemPrompt'),\n Reflect.get(o, 'appendSystemPrompt'),\n ...(Array.isArray(Reflect.get(o, 'instructions')) ? Reflect.get(o, 'instructions') : []),\n Reflect.get(o, 'system'),\n ]\n .filter((value) => typeof value === 'string')\n .join('\\n\\n')\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n","/**\n *\n * `delegate` — the one generic delegation verb. You hand it an INTENT (what you want done) and it\n * hands that intent to a default AUTHORING supervisor: a router-brained supervisor whose standing\n * instruction is `supervisorInstructions()` (the authoring-agent-profiles skill). The supervisor\n * DECOMPOSES the intent and AUTHORS the worker profile it needs per sub-task — there is NO hardcoded\n * coder/researcher profile here. That is the whole point: `delegate('fix the failing test', …)` and\n * `delegate('research X and cite sources', …)` route through the SAME front door; the supervisor\n * writes a code-shaped or research-shaped worker on its own.\n *\n * It is a thin wrapper over `supervise()` — the one front door — so the conserved-budget pool, the\n * completion oracle (`deliverable`), the coordination toolbox, and equal-compute accounting all come\n * for free; nothing is hand-rolled. The result is `supervise()`'s `SupervisedResult` returned\n * UNCHANGED, so its `spentTotal` (`{ iterations, tokens, usd, ms }`) rides straight back to the\n * caller on BOTH paths — a `winner` carries the delivered worker's spend, a `no-winner` carries the\n * spend incurred before it failed. That cost channel means a `delegate()` caller always learns what\n * the delegation actually spent.\n *\n * @experimental\n */\n\nimport { ConfigError } from '../../errors'\nimport type { RouterTransportConfig } from '../router-http-transport'\nimport type { DeliverableSpec } from './completion-gate'\nimport type { ExecutorConfig } from './runtime'\nimport { supervise } from './supervise'\nimport type { SupervisorProfile } from './supervisor-agent'\nimport type { Budget, SupervisedResult } from './types'\n\n/** The conserved pool a `delegate()` call applies when the caller does not pass its own `budget`.\n * A modest token ceiling + a small iteration ceiling — generous enough for a few-worker decompose,\n * bounded enough that an unsupervised intent cannot run away. Callers override via `opts.budget`. */\nexport const defaultDelegateBudget: Budget = { maxIterations: 50, maxTokens: 200_000 }\n\n/** Inputs to {@link delegate}. The intent is the first positional arg; everything here is optional\n * with explicit execution identity, so the common call names one exact supervisor profile. */\nexport interface DelegateOptions<Out = unknown> {\n /** The completion oracle (settled ⟺ delivered) the authored workers settle against. Strongly\n * recommended — without it the supervisor trusts a worker's self-report. For a code intent,\n * `patchDelivered()` is the canonical example; for a free-form answer, a content check. */\n readonly deliverable?: DeliverableSpec<Out>\n /** WHERE the authored workers run — the worker-execution backend (`router-tools` / `sandbox` /\n * `cli-worktree` / …). The supervisor authors the worker PROFILE; this is the substrate it runs\n * on. Provide this OR `makeWorkerAgent`-style wiring through `supervise()` is unavailable. */\n readonly backend?: ExecutorConfig\n /** The conserved compute pool for the whole delegation. Defaults to {@link defaultDelegateBudget}. */\n readonly budget?: Budget\n /** Exact executable authoring supervisor. Model, prompt, harness, and provider live here. */\n readonly supervisorProfile: SupervisorProfile\n /** Router endpoint/auth for a `cli-base` supervisor; contains no behavioral settings. */\n readonly router: RouterTransportConfig\n /** Restrict the run to this subset of models (forwarded to `supervise()`). */\n readonly allowedModels?: readonly string[]\n readonly runId?: string\n}\n\n/**\n * Delegate an INTENT to a default authoring supervisor and return its `SupervisedResult` unchanged.\n *\n * The supervisor authors + spawns whatever worker the intent needs over the conserved-budget pool;\n * `result.spentTotal` reports what the whole delegation actually cost. A `winner` result carries the\n * authored worker's delivered output; a `no-winner` result names why (never a fabricated success).\n */\nexport async function delegate<Out = unknown>(\n intent: string,\n opts: DelegateOptions<Out>,\n): Promise<SupervisedResult<Out>> {\n if (typeof intent !== 'string' || intent.trim().length === 0) {\n throw new ConfigError('delegate: `intent` must be a non-empty string')\n }\n return supervise(opts.supervisorProfile, intent, {\n budget: opts.budget ?? defaultDelegateBudget,\n ...(opts.backend ? { backend: opts.backend } : {}),\n ...(opts.deliverable ? { deliverable: opts.deliverable as DeliverableSpec<unknown> } : {}),\n router: opts.router,\n ...(opts.allowedModels ? { allowedModels: opts.allowedModels } : {}),\n ...(opts.runId ? { runId: opts.runId } : {}),\n }) as Promise<SupervisedResult<Out>>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,kBAAkB,KAAsC;CACtE,MAAM,SAAS,mBAAmB,UAAU,GAAG;CAC/C,IAAI,CAAC,OAAO,SAAS,OAAO;CAC5B,IAAI,CAAC,oBAAoB,OAAO,IAAI,CAAC,CAAC,KAAK,GAAG,OAAO;CACrD,OAAO;EACL,GAAG,OAAO;EACV,MACE,OAAO,OAAO,KAAK,SAAS,YAAY,OAAO,KAAK,KAAK,SAAS,IAC9D,OAAO,KAAK,OACZ;EACN,QAAQ,EAAE,GAAG,OAAO,KAAK,OAAO;CAClC;AACF;;;AAIA,SAAgB,uBAAuB,MAAkC;CACvE,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAI,MAAM,OAAO,CAAC,IAAI,aAAa,KAAK,MAAM,IAAI,CAAC;CACrD,CAAC,CAAC,KAAK,IAAI;AACb;;AAqBA,MAAa,mCAA8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B,SAAS,SAAS,kBAAkB,SAAS,SAAS,SAAS,UAAU,SAAS,UAAU,OAAO,SAAS,OAAO,YAAY,SAAS,SAAS,QAAQ,CAAC;EACzM,CACF;EACA,GAAI,SAAS,OACT,EAAE,oBAAoB,cAAc,SAAS,KAAK,UAAU,SAAS,QAAQ,KAAK,IAAI,EAAE,GAAG,IAC3F,CAAC;EACL,UAAU,iBAAiB;GACzB;GACA,MAAM;GACN;GACA,OAAO,YAAY,SAAS,OAAO,SAAS;EAC9C,CAAC;CACH,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;AC/MA,MAAa,wBAAgC;CAAE,eAAe;CAAI,WAAW;AAAQ;;;;;;;;AA+BrF,eAAsB,SACpB,QACA,MACgC;CAChC,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,CAAC,CAAC,WAAW,GACzD,MAAM,IAAI,YAAY,+CAA+C;CAEvE,OAAO,UAAU,KAAK,mBAAmB,QAAQ;EAC/C,QAAQ,KAAK,UAAU;EACvB,GAAI,KAAK,UAAU,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;EAChD,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,YAAwC,IAAI,CAAC;EACxF,QAAQ,KAAK;EACb,GAAI,KAAK,gBAAgB,EAAE,eAAe,KAAK,cAAc,IAAI,CAAC;EAClE,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC5C,CAAC;AACH"}
1
+ {"version":3,"file":"delegate-DgMQo-K8.js","names":[],"sources":["../src/runtime/supervise/authoring.ts","../src/runtime/supervise/delegate.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions, tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific guidance are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt\n}\n\n/** Narrow an untyped `spawn_worker` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n if (!resolveSystemPrompt(parsed.data).trim()) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt },\n }\n}\n\n/** The supervisor skill: an explicit profile-authoring instruction, never an implicit Runtime\n * policy. Editing this text changes how a profile designs the descendants it spawns. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_worker with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.appendSystemPrompt: rich additive instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • tools.agent_runtime_coordination_spawn_worker: true ONLY when this child should author and drive descendants. Add only the other agent_runtime_coordination_<verb> tools it will call, such as observe_agent or steer_agent.',\n ' • A child with spawn_worker MUST carry this complete profile-authoring instruction as an immutable resources.skills entry with resources.failOnError: true, so it can author its own descendants from the same contract.',\n ' • metadata may describe the work, but it never grants recursion or selects a Runtime execution path.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n '3. End your turn while your workers run: Runtime wakes you with each settled worker. A settlement says valid:true only if the deployable check passed.',\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.appendSystemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n \"5. read_journal to re-read YOUR OWN record before you decide the next move: every spawn you made, every settle, every question and answer, every steer, every analyst finding — oldest first, this node only, including what you did before a restart. Use it to see what you already tried instead of trying it again. It is paged: pass the returned nextRow as the next call's sinceRow, narrow with kinds, and raise limit/maxBytes only as far as you will actually read. A truncated:true page means a bound cut it short — keep paging before you conclude you have read everything.\",\n '6. AUTHOR YOUR OWN LENS when the questions you can already ask of a settled trace do not cover the failure you are chasing: define_analyst takes an id, a description, an area, the question in your own words, the instructions for answering it with trace evidence, and the smallest toolGroup that can answer it (model is the seat it runs on; omit it for the run default). It is DATA, never code. Then run_analyst it on any settled worker like a lens the run shipped with, and read the finding. list_analysts shows what you have. Define a lens when you need a different question asked — not a second copy of a question already on the menu.',\n '7. EVERY refusal you get back carries a `reason` naming the exact unmet condition. Read it and change that condition — a spawn refused for budget-exhausted needs a smaller budget or the refund of a settled worker, an invalid-profile needs the named field fixed, a submit_result refused because the check THREW is a broken check to report, not a result to resubmit. Never repeat a call that was refused without changing what it was refused for.',\n '8. ask_parent ONLY when you genuinely cannot decide, and then READ ITS OUTCOME. \"queued-for-parent\" means an inbox above you now holds the question. \"no-parent\" means no inbox above you is configured to receive it: the question is still on the run record for anyone watching, but nothing will route an answer back to you, so do not block. Decide it with answer_question, or answer_question with deferReason to record that it stays open, and carry on — a blocking question left undecided also refuses your stop.',\n '9. Once the work is delivered, end your turn with nothing left running.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// receives in its next wake — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** Resolved authored guidance from replacement, addition and instruction sections. */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read authored guidance without requiring replacement of native coding instructions. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n return [\n Reflect.get(o, 'systemPrompt'),\n Reflect.get(o, 'appendSystemPrompt'),\n ...(Array.isArray(Reflect.get(o, 'instructions')) ? Reflect.get(o, 'instructions') : []),\n Reflect.get(o, 'system'),\n ]\n .filter((value) => typeof value === 'string')\n .join('\\n\\n')\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n","/**\n *\n * `delegate` — the one generic delegation verb. You hand it an INTENT (what you want done) and it\n * hands that intent to a default AUTHORING supervisor: a router-brained supervisor whose standing\n * instruction is `supervisorInstructions()` (the authoring-agent-profiles skill). The supervisor\n * DECOMPOSES the intent and AUTHORS the worker profile it needs per sub-task — there is NO hardcoded\n * coder/researcher profile here. That is the whole point: `delegate('fix the failing test', …)` and\n * `delegate('research X and cite sources', …)` route through the SAME front door; the supervisor\n * writes a code-shaped or research-shaped worker on its own.\n *\n * It is a thin wrapper over `supervise()` — the one front door — so the conserved-budget pool, the\n * completion oracle (`deliverable`), the coordination toolbox, and equal-compute accounting all come\n * for free; nothing is hand-rolled. The result is `supervise()`'s `SupervisedResult` returned\n * UNCHANGED, so its `spentTotal` (`{ iterations, tokens, usd, ms }`) rides straight back to the\n * caller on BOTH paths — a `winner` carries the delivered worker's spend, a `no-winner` carries the\n * spend incurred before it failed. That cost channel means a `delegate()` caller always learns what\n * the delegation actually spent.\n *\n * @experimental\n */\n\nimport { ConfigError } from '../../errors'\nimport type { RouterTransportConfig } from '../router-http-transport'\nimport type { DeliverableSpec } from './completion-gate'\nimport type { ExecutorConfig } from './runtime'\nimport { supervise } from './supervise'\nimport type { SupervisorProfile } from './supervisor-agent'\nimport type { Budget, SupervisedResult } from './types'\n\n/** The conserved pool a `delegate()` call applies when the caller does not pass its own `budget`.\n * A modest token ceiling + a small iteration ceiling — generous enough for a few-worker decompose,\n * bounded enough that an unsupervised intent cannot run away. Callers override via `opts.budget`. */\nexport const defaultDelegateBudget: Budget = { maxIterations: 50, maxTokens: 200_000 }\n\n/** Inputs to {@link delegate}. The intent is the first positional arg; everything here is optional\n * with explicit execution identity, so the common call names one exact supervisor profile. */\nexport interface DelegateOptions<Out = unknown> {\n /** The completion oracle (settled ⟺ delivered) the authored workers settle against. Strongly\n * recommended — without it the supervisor trusts a worker's self-report. For a code intent,\n * `patchDelivered()` is the canonical example; for a free-form answer, a content check. */\n readonly deliverable?: DeliverableSpec<Out>\n /** WHERE the authored workers run — the worker-execution backend (`router-tools` / `sandbox` /\n * `cli-worktree` / …). The supervisor authors the worker PROFILE; this is the substrate it runs\n * on. Provide this OR `makeWorkerAgent`-style wiring through `supervise()` is unavailable. */\n readonly backend?: ExecutorConfig\n /** The conserved compute pool for the whole delegation. Defaults to {@link defaultDelegateBudget}. */\n readonly budget?: Budget\n /** Exact executable authoring supervisor. Model, prompt, harness, and provider live here. */\n readonly supervisorProfile: SupervisorProfile\n /** Router endpoint/auth for a `cli-base` supervisor; contains no behavioral settings. */\n readonly router: RouterTransportConfig\n /** Restrict the run to this subset of models (forwarded to `supervise()`). */\n readonly allowedModels?: readonly string[]\n readonly runId?: string\n}\n\n/**\n * Delegate an INTENT to a default authoring supervisor and return its `SupervisedResult` unchanged.\n *\n * The supervisor authors + spawns whatever worker the intent needs over the conserved-budget pool;\n * `result.spentTotal` reports what the whole delegation actually cost. A `winner` result carries the\n * authored worker's delivered output; a `no-winner` result names why (never a fabricated success).\n */\nexport async function delegate<Out = unknown>(\n intent: string,\n opts: DelegateOptions<Out>,\n): Promise<SupervisedResult<Out>> {\n if (typeof intent !== 'string' || intent.trim().length === 0) {\n throw new ConfigError('delegate: `intent` must be a non-empty string')\n }\n return supervise(opts.supervisorProfile, intent, {\n budget: opts.budget ?? defaultDelegateBudget,\n ...(opts.backend ? { backend: opts.backend } : {}),\n ...(opts.deliverable ? { deliverable: opts.deliverable as DeliverableSpec<unknown> } : {}),\n router: opts.router,\n ...(opts.allowedModels ? { allowedModels: opts.allowedModels } : {}),\n ...(opts.runId ? { runId: opts.runId } : {}),\n }) as Promise<SupervisedResult<Out>>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;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GAAI,KAAK,UAAU,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;EAChD,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,YAAwC,IAAI,CAAC;EACxF,QAAQ,KAAK;EACb,GAAI,KAAK,gBAAgB,EAAE,eAAe,KAAK,cAAc,IAAI,CAAC;EAClE,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC5C,CAAC;AACH"}
package/dist/durable.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $u as ObserverJournal, $v as EscalateQuestion, Ap as CoordinationPublicAddress, Au as VersionJudge, Bu as PursuitObserverDelivery, Cf as RunParkingRecord, Cu as JudgedPursuitVersion, D as RetainedPendingCause, Dp as CoordinationAuthentication, Du as PursuitVersionStop, Eu as PursuitVersionChain, Fp as CoordinationRejectReason, Fu as SupervisePursuitOptions, Gf as DriveHarnessOwnerContext, Gu as PursuitNodeTiming, Hd as WorkerSlots, Hu as PursuitNodeCost, Hv as WorkerWatchOptions, Iu as SupervisedPursuitResult, Ju as PursuitRunProjection, Ku as PursuitNodeUsage, Lf as RootStreamRecord, Lu as superviseGraphPursuit, Md as PursuitFork, Mp as CoordinationTransportOptions, Mu as assertPursuitVersions, Nd as RUN_FORK_CORRELATION_KEYS, Nu as SuperviseGraphPursuitOptions, Ou as PursuitVersions, Pp as CoordinationHttpAudit, Pu as SupervisePursuitError, Qu as FileObserverJournal, Rd as AuthorizedSpawn, Rf as readRootStream, Ru as supervisePursuit, Sf as RunParkingPolicy, Tu as NextPursuitVersionInput, Uu as PursuitNodePlatform, V as NodeId, Vu as PursuitCostProvenance, Wu as PursuitNodeProjection, Xu as PursuitStatus, Yu as PursuitRunTotals, Zu as projectPursuit, bf as ParkedRun, ed as ObserverRecord, fy as AuthorizedDownMessage, hy as DownMessageAuthorizationInput, if as SelectSeat, it as SupervisedResult, jp as CoordinationReadAccess, ju as VersionVerdict, kh as ToolLoopCompactionOptions, ku as SettledPursuitVersion, my as ContinuityMode, nd as observerRecordDigest, nf as SeatSelectionInput, ny as QuestionEscalationOutcome, qf as ResolveDriveHarness, qu as PursuitProjection, rt as RootStreamReceipt, sb as AnalyzeOnSettleRoute, td as ObserverRecordKind, tf as SeatSelection, tp as ManagerWakePolicy, wf as readRunParking, wu as NextPursuitVersion, xf as RunParkedError, xy as MapOnSettleRoute, yf as DeadlineCheckIn, zd as AuthorizedSpawnContext, zf as readRootStreamReceipt, zu as RunReopen } from "./types-Bm4xC_e-.js";
1
+ import { $u as ObserverJournal, $v as EscalateQuestion, Ap as CoordinationPublicAddress, Au as VersionJudge, Bu as PursuitObserverDelivery, Cf as RunParkingRecord, Cu as JudgedPursuitVersion, D as RetainedPendingCause, Dp as CoordinationAuthentication, Du as PursuitVersionStop, Eu as PursuitVersionChain, Fp as CoordinationRejectReason, Fu as SupervisePursuitOptions, Gf as DriveHarnessOwnerContext, Gu as PursuitNodeTiming, Hd as WorkerSlots, Hu as PursuitNodeCost, Hv as WorkerWatchOptions, Iu as SupervisedPursuitResult, Ju as PursuitRunProjection, Ku as PursuitNodeUsage, Lf as RootStreamRecord, Lu as superviseGraphPursuit, Md as PursuitFork, Mp as CoordinationTransportOptions, Mu as assertPursuitVersions, Nd as RUN_FORK_CORRELATION_KEYS, Nu as SuperviseGraphPursuitOptions, Ou as PursuitVersions, Pp as CoordinationHttpAudit, Pu as SupervisePursuitError, Qu as FileObserverJournal, Rd as AuthorizedSpawn, Rf as readRootStream, Ru as supervisePursuit, Sf as RunParkingPolicy, Tu as NextPursuitVersionInput, Uu as PursuitNodePlatform, V as NodeId, Vu as PursuitCostProvenance, Wu as PursuitNodeProjection, Xu as PursuitStatus, Yu as PursuitRunTotals, Zu as projectPursuit, bf as ParkedRun, ed as ObserverRecord, fy as AuthorizedDownMessage, hy as DownMessageAuthorizationInput, if as SelectSeat, it as SupervisedResult, jp as CoordinationReadAccess, ju as VersionVerdict, kh as ToolLoopCompactionOptions, ku as SettledPursuitVersion, my as ContinuityMode, nd as observerRecordDigest, nf as SeatSelectionInput, ny as QuestionEscalationOutcome, qf as ResolveDriveHarness, qu as PursuitProjection, rt as RootStreamReceipt, sb as AnalyzeOnSettleRoute, td as ObserverRecordKind, tf as SeatSelection, tp as ManagerWakePolicy, wf as readRunParking, wu as NextPursuitVersion, xf as RunParkedError, xy as MapOnSettleRoute, yf as DeadlineCheckIn, zd as AuthorizedSpawnContext, zf as readRootStreamReceipt, zu as RunReopen } from "./types-QS0ItMiE.js";
2
2
  import { n as RuntimeDecisionKind, r as RuntimeDecisionPoint, t as RuntimeDecisionEvidenceRef } from "./runtime-hooks-ZQqPw-0g.js";
3
3
  import { a as ChatTurnProducer, c as handleChatTurn, i as ChatTurnIdentity, n as ChatStreamEvent, o as ChatTurnResult, r as ChatTurnHooks, s as RunChatTurnInput, t as deriveExecutionId } from "./execution-handle-CujvqgCn.js";
4
4
  import { ToolSpan } from "@tangle-network/agent-eval";
package/dist/durable.js CHANGED
@@ -1,16 +1,16 @@
1
- import { L as FileSpawnJournal, Oi as assertValidBudget, Vt as loadSpawnForest, Xr as runtimeFailureCause, _ as supervisorRunDir, _i as contentAddress, a as readRootStream, dn as FileObserverJournal, fn as createFileObserverHooks, o as readRootStreamReceipt, pn as observerRecordDigest, qt as FileResultBlobStore, wr as authoredProfileDigest, y as workerCancellationsDir } from "./scope-BeI3tmVX.js";
1
+ import { L as FileSpawnJournal, Oi as assertValidBudget, Vt as loadSpawnForest, Xr as runtimeFailureCause, _ as supervisorRunDir, _i as contentAddress, a as readRootStream, dn as FileObserverJournal, fn as createFileObserverHooks, o as readRootStreamReceipt, pn as observerRecordDigest, qt as FileResultBlobStore, wr as authoredProfileDigest, y as workerCancellationsDir } from "./scope-CwhYLg6s.js";
2
2
  import { f as RuntimeRunStateError, m as ValidationError } from "./errors-AzSuGI23.js";
3
- import { Y as errorMessage } from "./workspace-streams-BSEkDu3H.js";
3
+ import { Y as errorMessage } from "./workspace-streams-COSTjQLW.js";
4
4
  import { n as isNoEntError } from "./jsonl-file-BBP9Dz9w.js";
5
- import { Et as isFiniteNumber, Tt as failedItems, i as RunParkedError, r as assertResumeLimits, s as readRunParking } from "./supervisor-REUnT7iX.js";
5
+ import { Et as isFiniteNumber, Tt as failedItems, i as RunParkedError, r as assertResumeLimits, s as readRunParking } from "./supervisor-CORJv7-r.js";
6
6
  import { a as writeAtomicDurableFile, c as mutateRunClaim, i as syncDurableDirectory, l as runGenerationPath, r as publishExclusiveDurableFile, s as fenceRunWrite, u as runWithWriteClaim } from "./durable-file-DstVeHcj.js";
7
7
  import { a as withPursuitContext, t as composeRuntimeHooks } from "./runtime-hooks-CsW2pfFk.js";
8
- import { a as applyExactAgentProfileDiff } from "./profile-By6JkIQi.js";
9
- import { a as runCancelRequestFile, h as rootCoordinationOwner, o as runCancellationFile, v as FileCoordinationLog } from "./run-cancellation-BTjyVpVW.js";
10
- import { a as superviseRootProfile, p as runToolSpans, t as supervise } from "./supervise-QzwZc6K2.js";
11
- import { a as graphExecutionOptions, i as superviseAgentGraph } from "./graph-C_564r0C.js";
8
+ import { a as applyExactAgentProfileDiff } from "./profile-CvucOo-Q.js";
9
+ import { a as runCancelRequestFile, h as rootCoordinationOwner, o as runCancellationFile, v as FileCoordinationLog } from "./run-cancellation-3tqWES3A.js";
10
+ import { a as superviseRootProfile, p as runToolSpans, t as supervise } from "./supervise-DYtL1RvC.js";
11
+ import { a as graphExecutionOptions, i as superviseAgentGraph } from "./graph-DSVXDbSf.js";
12
12
  import { n as handleChatTurn, t as deriveExecutionId } from "./execution-handle-Bd2_nUB6.js";
13
- import { a as parseSettleRecord, c as settleRecordDigest, d as projectPursuit, i as SettledRunDirectoryError, l as writeFailureRecord, n as FAILURE_RECORD_FILE, o as readFailureRecord, r as SETTLE_RECORD_FILE, s as readSettleRecord, t as discoverDurableSupervisionRun, u as writeSettleRecord } from "./supervision-discovery-CyvJVbTM.js";
13
+ import { a as parseSettleRecord, c as settleRecordDigest, d as projectPursuit, i as SettledRunDirectoryError, l as writeFailureRecord, n as FAILURE_RECORD_FILE, o as readFailureRecord, r as SETTLE_RECORD_FILE, s as readSettleRecord, t as discoverDurableSupervisionRun, u as writeSettleRecord } from "./supervision-discovery-EtxsGdsk.js";
14
14
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sha256Bytes } from "@tangle-network/agent-interface";
15
15
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
16
16
  import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync } from "node:fs";
@@ -1,11 +1,11 @@
1
- import { Jr as runtimeFlowBrain, _i as contentAddress } from "./scope-BeI3tmVX.js";
1
+ import { Jr as runtimeFlowBrain, _i as contentAddress } from "./scope-CwhYLg6s.js";
2
2
  import { i as ConfigError, m as ValidationError } from "./errors-AzSuGI23.js";
3
3
  import { c as withJsonlFileLock, o as readCommittedJsonLines, t as appendCommittedJsonLine } from "./jsonl-file-BBP9Dz9w.js";
4
- import { Rt as defaultRunCommand } from "./supervisor-REUnT7iX.js";
4
+ import { Rt as defaultRunCommand } from "./supervisor-CORJv7-r.js";
5
5
  import { v as harnessRunsAgent } from "./model-policy-C-RGAUW4.js";
6
6
  import { t as composeRuntimeHooks } from "./runtime-hooks-CsW2pfFk.js";
7
- import { f as createFileRunContext, m as withRunContext, p as createInMemoryRunContext } from "./coordination-manager-B9goecNC.js";
8
- import { C as flowRootProfile, E as validateFlowGraph, I as kernelPromptRegistry, O as graphRootProfile, S as createFlowRun, T as routeFlowOf, b as createGraphOverlay, i as profileGuidanceComposer, k as validateGraphTopology, r as superviseWithTestBrain, t as supervise, w as journaledGateDecider, x as GraphRouteError } from "./supervise-QzwZc6K2.js";
7
+ import { f as createFileRunContext, m as withRunContext, p as createInMemoryRunContext } from "./coordination-manager-CXlabreV.js";
8
+ import { C as flowRootProfile, E as validateFlowGraph, I as kernelPromptRegistry, O as graphRootProfile, S as createFlowRun, T as routeFlowOf, b as createGraphOverlay, i as profileGuidanceComposer, k as validateGraphTopology, r as superviseWithTestBrain, t as supervise, w as journaledGateDecider, x as GraphRouteError } from "./supervise-DYtL1RvC.js";
9
9
  import { canonicalCandidateDigest } from "@tangle-network/agent-interface";
10
10
  import { mkdirSync, realpathSync } from "node:fs";
11
11
  import { isAbsolute, join, relative, resolve } from "node:path";
@@ -575,4 +575,4 @@ function superviseAgentGraph(graph, opts, brain) {
575
575
  }
576
576
  export { graphExecutionOptions as a, superviseAgentGraph as i, runGraph as n, runGraphWithTestBrain as r, GraphEdgeCapError as t };
577
577
 
578
- //# sourceMappingURL=graph-C_564r0C.js.map
578
+ //# sourceMappingURL=graph-DSVXDbSf.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"graph-C_564r0C.js","names":[],"sources":["../src/runtime/supervise/graph-backend.ts","../src/runtime/supervise/stored-graph-check.ts","../src/runtime/supervise/graph.ts"],"sourcesContent":["import { ValidationError } from '../../errors'\nimport type { RunGraphOptions } from './graph'\n\n/** Graph nodes expose JSON outputs through Runtime's resumable execution transports. */\nexport function graphExecutionOptions(options: RunGraphOptions): RunGraphOptions {\n if (options.makeLeafAgent) return options\n const backend = options.backend\n if (backend)\n return backend.backend === 'bridge' || backend.backend === 'provider'\n ? { ...options, backend: { ...backend, outputFormat: 'json' } }\n : options\n const bridgeUrl = process.env.CLI_BRIDGE_URL\n const bridgeBearer = process.env.BRIDGE_BEARER ?? process.env.CLI_BRIDGE_BEARER\n if (!bridgeUrl || !bridgeBearer)\n throw new ValidationError(\n 'runGraph: start CLI Bridge and supply backend: { backend: \"bridge\", bridgeUrl, bridgeBearer, cwd }, or configure CLI_BRIDGE_URL and BRIDGE_BEARER',\n )\n return {\n ...options,\n backend: {\n backend: 'bridge',\n bridgeUrl,\n bridgeBearer,\n cwd: process.cwd(),\n outputFormat: 'json',\n },\n }\n}\n","import { mkdirSync, realpathSync } from 'node:fs'\nimport { isAbsolute, join, relative } from 'node:path'\nimport { contentAddress } from '../../durable/content-address'\nimport {\n appendCommittedJsonLine,\n readCommittedJsonLines,\n withJsonlFileLock,\n} from '../../durable/jsonl-file'\nimport { ValidationError } from '../../errors'\nimport { defaultRunCommand } from '../../mcp/worktree-harness'\nimport type { CompletionCheckContext } from './completion-gate'\nimport type { AgentGraph, RunGraphOptions } from './graph'\n\n/** An environment-owned check command, run outside the agent's conversation. */\nexport interface GraphCommandCheck {\n readonly command: string\n readonly timeoutMs?: number\n}\n\nexport interface GraphFromStoredOptions {\n readonly trigger?: Readonly<Record<string, unknown>>\n readonly checks?: Readonly<Record<string, AgentGraph['deliverable']['check'] | GraphCommandCheck>>\n}\n\ninterface CommandCheckReceipt {\n readonly version: 1\n readonly key: string\n readonly binding: string\n readonly checkDigest: string\n readonly nodeName: string\n readonly nodeId: string\n readonly attemptId: string\n readonly outputDigest: string\n readonly exitCode: number | null\n readonly output: string\n readonly outputTruncated: boolean\n readonly nativeValid: boolean\n readonly valid: boolean\n}\n\n/** Driver-owned journal identity. Worker output never supplies any part of this authority. */\nfunction receiptKey(receipt: Omit<CommandCheckReceipt, 'key'>): string {\n return contentAddress({\n binding: receipt.binding,\n checkDigest: receipt.checkDigest,\n nodeName: receipt.nodeName,\n nodeId: receipt.nodeId,\n attemptId: receipt.attemptId,\n outputDigest: receipt.outputDigest,\n })\n}\n\nfunction isReceipt(value: unknown): value is CommandCheckReceipt {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const row = value as Record<string, unknown>\n if (\n row.version !== 1 ||\n ![\n 'key',\n 'binding',\n 'checkDigest',\n 'nodeName',\n 'nodeId',\n 'attemptId',\n 'outputDigest',\n 'output',\n ].every((key) => typeof row[key] === 'string') ||\n !row.nodeName ||\n !row.nodeId ||\n !row.attemptId ||\n !(row.exitCode === null || Number.isSafeInteger(row.exitCode)) ||\n typeof row.outputTruncated !== 'boolean' ||\n typeof row.nativeValid !== 'boolean' ||\n typeof row.valid !== 'boolean'\n )\n return false\n const receipt = value as CommandCheckReceipt\n return (\n receipt.key === receiptKey(receipt) &&\n receipt.valid === (receipt.exitCode === 0 && receipt.nativeValid)\n )\n}\n\nfunction within(directory: string, path: string): boolean {\n const offset = relative(directory, path)\n return offset === '' || (!isAbsolute(offset) && offset !== '..' && !offset.startsWith('../'))\n}\n\n/** Lower a named check onto the local workspace, with evidence in the driver's durable state.\n * The run directory has the same trust boundary as RunContext journals: keep it outside the\n * worker workspace and do not mount it into the worker. A remote Bridge cannot run a host check.\n * Provider validators are refused because their context does not identify the admitted node.\n */\nexport function bindGraphCommand(\n graph: AgentGraph,\n options: RunGraphOptions,\n): { graph: AgentGraph; options: RunGraphOptions } {\n const { command: definition, ...deliverable } = graph.deliverable\n if (!definition) return { graph, options }\n const { command, timeoutMs = 60_000 } = definition\n if (!command.trim() || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)\n throw new ValidationError(\n 'graphFromStored: command check needs a command and positive timeoutMs',\n )\n const backend = options.backend\n if (options.makeLeafAgent || !backend)\n throw new ValidationError('runGraph: command checks require an explicit execution backend')\n const workspace =\n backend.backend === 'bridge'\n ? backend.cwd\n : backend.backend === 'cli-in-place'\n ? backend.workspacePath\n : undefined\n if (\n !workspace ||\n (backend.backend === 'bridge' &&\n !['localhost', '127.0.0.1', '[::1]'].includes(new URL(backend.bridgeUrl).hostname))\n )\n throw new ValidationError(\n 'runGraph: command checks require a loopback Bridge or local CLI workspace; provider node binding is unsupported',\n )\n if (!options.runDir)\n throw new ValidationError(\n 'runGraph: command checks require a driver-owned runDir outside the workspace',\n )\n const cwd = realpathSync(workspace)\n mkdirSync(options.runDir, { recursive: true })\n const runDir = realpathSync(options.runDir)\n if (within(cwd, runDir))\n throw new ValidationError('runGraph: command check runDir must be outside the worker workspace')\n const file = join(runDir, 'command-checks.jsonl')\n const checkDigest = contentAddress({ command, timeoutMs, cwd })\n const binding = contentAddress({\n graph: { ...graph, deliverable: { ...deliverable, check: undefined } },\n runId: options.runId ?? options.runContext?.runId,\n checkDigest,\n })\n const nodeNames = new Set(graph.nodes.map((node) => node.id))\n\n // The map is supplied by Runtime's flow finalizer. It contains terminal graph node IDs and\n // outputs, never receipt metadata. Every match must come from this run's driver journal.\n const checkFinal = async (out: unknown): Promise<boolean> => {\n if (!out || typeof out !== 'object' || Array.isArray(out)) return false\n const entries = Object.entries(out)\n if (entries.length === 0 || entries.some(([name]) => !nodeNames.has(name))) return false\n return withJsonlFileLock(file, async (canonicalPath) => {\n if (within(cwd, canonicalPath)) return false\n const latest = new Map<string, CommandCheckReceipt>()\n for await (const raw of readCommittedJsonLines<unknown>(canonicalPath, {\n allowMissing: true,\n })) {\n if (!isReceipt(raw)) return false\n if (raw.binding !== binding || raw.checkDigest !== checkDigest) continue\n latest.set(contentAddress([raw.nodeName, raw.outputDigest]), raw)\n }\n return entries.every(\n ([name, output]) =>\n latest.get(contentAddress([name, contentAddress(output)]))?.valid === true,\n )\n })\n }\n\n const checkLeaf = async (out: unknown, context: CompletionCheckContext): Promise<boolean> => {\n const node = context.node\n const nodeName = context.profile.name\n if (!node || !node.nodeId || !node.attemptId || !nodeName || !nodeNames.has(nodeName))\n return false\n // Always execute for a fresh leaf. A prior success, even for identical output, never skips\n // this check. gateFactoryOnDeliverable deduplicates only one invocation's exact artifact.\n const outputDigest = contentAddress(out)\n let result: { exitCode: number | null; output: string }\n try {\n result = await defaultRunCommand({ command, cwd, timeoutMs, signal: context.signal })\n } catch (error) {\n // An unavailable check invalidates an earlier identical output too; it cannot inherit\n // a prior success just because the current command did not reach a normal exit.\n result = { exitCode: null, output: error instanceof Error ? error.message : String(error) }\n }\n const bytes = Buffer.from(result.output)\n const limit = 64 * 1024\n const receipt: Omit<CommandCheckReceipt, 'key'> = {\n version: 1,\n binding,\n checkDigest,\n nodeName,\n nodeId: node.nodeId,\n attemptId: node.attemptId,\n outputDigest,\n exitCode: result.exitCode,\n output: bytes.subarray(0, limit).toString('utf8'),\n outputTruncated: bytes.length > limit,\n nativeValid: context.originalVerdict?.valid !== false,\n valid: result.exitCode === 0 && context.originalVerdict?.valid !== false,\n }\n await withJsonlFileLock(file, async (canonicalPath) => {\n if (within(cwd, canonicalPath))\n throw new ValidationError(\n 'runGraph: command receipt journal resolves inside worker workspace',\n )\n await appendCommittedJsonLine(canonicalPath, { ...receipt, key: receiptKey(receipt) })\n })\n return receipt.valid\n }\n return {\n graph: {\n ...graph,\n deliverable: {\n ...deliverable,\n check: (out, context) =>\n context === undefined ? checkFinal(out) : checkLeaf(out, context),\n },\n },\n options,\n }\n}\n","/**\n *\n * `runGraph` — agent graphs: profiles as nodes, registry-backed prompt directives as edges.\n *\n * A topology is PLAIN DATA an agent can author in a few lines: nodes are canonical\n * `AgentProfile`s (the ONLY way a node is described — no role-builder functions), edges are typed\n * values carrying versioned {@link PromptHandle} directives, `deliverable` (termination) and\n * `budget` (one conserved pool) are mandatory. Driver↔worker is the two-node cyclic instance;\n * \"agent 3 analyzes 1 and 2 and reports to 1\" is ONE edge, not a framework.\n *\n * NOT A SECOND SCHEDULER. `runGraph` is an interpretation layer over what already runs:\n * `supervise()` is the execution core — the same `supervisorAgent`/`driverAgent` machinery,\n * backend-derived worker path (authorized, classified, recursive), conserved-pool budget, and\n * deliverable-gated settlement every\n * supervised run uses. (`runAgentRounds` is deliberately NOT the substrate here.) What the graph\n * layer ADDS is exactly what a bespoke driver loop never\n * had:\n *\n * 1. **Node pinning** — a spawn names a node (`profile.name` = node id) and the node's canonical\n * profile is what runs; a driver cannot smuggle capabilities into a worker it did not define.\n * 2. **Observable edges** — every delegates/analyzes/maps/routes traversal lands in an EDGE LEDGER\n * (`delivered | stripped | empty | unpropagated | failed`, with byte counts), in memory on\n * the result AND as `edge` events in the run journal. The motivating incident: a filter\n * silently replaced 1,700-char steering with 241 chars of boilerplate for three rounds and\n * NO artifact said so — an unobservable edge cannot be trusted and its directive cannot be\n * optimized.\n * 3. **Directives as data** — edge text lives in the prompt registry (`<surface>/v<n>`), so every\n * edge is a versioned optimization target, never prose hardcoded in a builder function.\n * 4. **Per-edge traversal caps** — the cyclic-graph backstop. A delegates edge whose cap is\n * exhausted REFUSES further traversals (fail loud), so a cycle cannot spin the pool dry.\n * 5. **Continuity as data** — a delegates edge may declare `continuity: 'resume'`, so each spawn\n * after the node's first re-attaches to its latest SETTLED session (the spawn context hands\n * the executor seam `resume: { ofWorker, sequence }`; the kernel keeps identity, ordering,\n * ledger truth, and the one conserved pool). Every ledger row states how its hop continued:\n * `'fresh' | 'resume'` for spawns, `'steer'` for mid-run deliveries — fresh respawns, session\n * resumes, and live steers are all plain data, each a ledgered fact.\n * 6. **Fan-out over a run-time list** — a `maps` edge takes the array a JSON pointer selects in a\n * node's settled result and runs one item per element, then hands the ordered results to a\n * join node. The runtime spawns every item and the join when the source settles, so the\n * driver spends no model turn on them; each item is a spawn through the same authorized path,\n * reserving from the same conserved pool, and every expansion, item and join is a ledger row.\n * 7. **Flow graphs** — with `entry` set, no node is a root: Runtime spawns the entries and fires\n * `routes` edges on each settle (`graph-flow.ts`), so a fixed order, a branch, a bounded repair\n * loop and a stop rule are graph data. The root manager is Runtime's own and never calls a\n * model; every entry and route spawn takes the same authorized path a map item takes.\n *\n * ORACLES ARE ENVIRONMENT, NEVER WORKERS. Graders/verifiers must not be spawnable in the graph —\n * a delegates edge to them leaks the rubric. An `analyzes` edge names its analyst in one of two\n * forms: a LENS id from the environment's registry (a pure function over trace evidence), or the\n * id of a graph NODE — a tool-equipped analyst AGENT spawned on each matching settle with the\n * node's pinned profile, whose settle output IS the findings. Either way the oracle doctrine\n * holds: an analyst node can never be a delegates target (refused loudly), so no driver can hand\n * it work, and an id living in both the registry and the nodes is refused as ambiguous.\n *\n * @experimental\n */\n\nimport { resolve } from 'node:path'\nimport { type AgentProfile, canonicalCandidateDigest } from '@tangle-network/agent-interface'\nimport { ConfigError, ValidationError } from '../../errors'\nimport type { AnalystRegistry } from '../../mcp/tools/coordination-analysts'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination-contracts'\nimport type { MapItemFailurePolicy } from '../../mcp/tools/coordination-map-contracts'\nimport type { ContinuityMode } from '../../mcp/tools/coordination-messages'\nimport type {\n GateDecision,\n GateDecisionRecord,\n GateRequest,\n RouteGate,\n RouteWhen,\n} from '../../mcp/tools/coordination-route-contracts'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport { harnessRunsAgent } from '../harness-role'\nimport type { ToolLoopChat } from '../tool-loop'\nimport type { DeliverableSpec } from './completion-gate'\nimport { runtimeFlowBrain } from './flow-brain'\nimport { graphExecutionOptions } from './graph-backend'\nimport {\n createFlowRun,\n flowRootProfile,\n GraphRouteError,\n journaledGateDecider,\n routeFlowOf,\n validateFlowGraph,\n} from './graph-flow'\nimport { createGraphOverlay } from './graph-overlay'\nimport {\n graphRootProfile,\n type RootValidatedGraph,\n type ValidatedGraph,\n validateGraphTopology,\n} from './graph-topology'\nimport { kernelPromptRegistry, type PromptHandle, type PromptRegistry } from './prompt-registry'\nimport { createFileRunContext, createInMemoryRunContext, withRunContext } from './run-context'\nimport { bindGraphCommand, type GraphCommandCheck } from './stored-graph-check'\nimport {\n profileGuidanceComposer,\n type SuperviseOptions,\n supervise,\n superviseWithTestBrain,\n} from './supervise'\nimport type { Budget, NodeId, ResultBlobStore, SpawnJournal, SupervisedResult } from './types'\n\nexport type { MapItemFailurePolicy } from '../../mcp/tools/coordination-map-contracts'\nexport type {\n GateDecision,\n GateRequest,\n JsonScalar,\n RouteGate as GraphGate,\n RouteMatch,\n RouteWhen,\n} from '../../mcp/tools/coordination-route-contracts'\nexport { GraphRouteError } from './graph-flow'\nexport { defaultEdgeTraversalCap } from './graph-topology'\n\n// ── The algebra ────────────────────────────────────────────────────────────────\n\n/** A graph node: an id and a canonical `AgentProfile`. The profile is the ONLY way a node is\n * described — its `prompt.systemPrompt` is the standing role (the 0.117 canonical resolution;\n * never a legacy top-level-only reduction), its tools/mcp/resources are its capabilities. */\nexport interface GraphNode {\n readonly id: NodeId\n readonly profile: AgentProfile\n}\n\nexport type GraphEdge =\n /** Work flows down. The delegation directive is DATA → versionable, sweepable, optimizable.\n * Each spawn of `to` by `from` — and each mid-run steer from `from` to a live `to` worker —\n * is one traversal. */\n | {\n readonly kind: 'delegates'\n readonly from: NodeId\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Cyclic-graph backstop: traversals beyond this REFUSE (fail loud). Default\n * {@link defaultEdgeTraversalCap}. */\n readonly maxTraversals?: number\n /** Default continuity for this edge's SPAWN traversals. `'resume'` makes every spawn after\n * the node's first re-attach to its most recent SETTLED worker: a NEW live worker whose\n * spawn context carries `resume: { ofWorker, sequence }` for the executor seam, spending\n * from the same conserved pool — the node's first spawn is effectively `'fresh'`, and a\n * spawn while a prior worker is still live refuses loudly (steer is the live channel).\n * The driver's per-call `spawn_worker` `continuity` argument overrides either way. Omit =\n * `'fresh'` (today's behavior, byte-identical). Caps count resumes exactly like fresh\n * spawns. */\n readonly continuity?: ContinuityMode\n }\n /** Findings flow anywhere: an analyst over N nodes' settled traces, delivered to ONE node.\n * With a LENS analyst the directive wraps the findings for the recipient; with a NODE analyst\n * the directive is the analyst agent's task and the findings are its settle output. */\n | {\n readonly kind: 'analyzes'\n /** The analyst REFERENCE, in one of two forms: a lens id resolved against\n * `RunGraphOptions.analysts` (environment), or the id of a graph NODE with no delegates\n * edge pointing at it — then each matching settle spawns that node's pinned profile as a\n * tool-equipped analyst WORKER (same spawn machinery, conserved budget, trace join) whose\n * task is this edge's directive plus the settled worker's trace evidence and whose settle\n * output is the findings. An id that is both a node and a registry lens is refused. */\n readonly analyst: string\n readonly over: ReadonlyArray<NodeId>\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Observability cap: traversals beyond this are LEDGERED as exhausted (`unpropagated`).\n * Only delegates caps refuse traversal — they are what close the spawn cycle. */\n readonly maxTraversals?: number\n }\n /**\n * Fan-out over a list that exists only at run time, then one join. When `from` settles `done`,\n * the array at `pointer` in its result is expanded: each element becomes the TASK of one item\n * run, at most `concurrency` at a time, and once every item settled the `join` node runs with\n * `{ map, source, items, results: [{ index, item, result }], failures: [{ index, item, outcome,\n * reason }] }`, results in item order. The runtime spawns the items and the join (`from`'s\n * driver spends no turn on them) through the same authorized spawn path a delegates spawn\n * takes: each item reserves its budget from the one conserved pool and is pinned to the edge's\n * profile, so an item's content can never choose what runs.\n *\n * An item is either the node `to` (its pinned profile plus this edge's directive) or the nested\n * `graph`, started per item exactly as `run_graph` starts a graph. Refusals are loud and\n * ledgered, and the driver is woken with them: a pointer that does not resolve to an array, more\n * elements than `maxItems`, or a `concurrency` the run's worker-slot bound can never honor.\n * `concurrency` otherwise THROTTLES (items wait for a free place); it never refuses an item.\n *\n * An edge rather than a node-level spec, because every kernel invariant a map must keep already\n * attaches to edge traversal: pinning admits only the edge's item and join nodes (the spawn\n * context carries a runtime-authored `map` marker), each item is admitted like a spawn and\n * reserves from the conserved pool, each item settles under its own deliverable check, and each\n * expansion, item and join is a ledger row with its journal twin. Topology stays static; only the\n * traversal count is dynamic, so validation and the one-node-one-profile rule are unchanged.\n */\n | {\n readonly kind: 'maps'\n /** The source node: a delegates target, or the join of another maps edge. Each of its `done`\n * settles expands the map once. */\n readonly from: NodeId\n /** RFC 6901 JSON pointer into `from`'s settled result (`''` is the whole result). */\n readonly pointer: string\n /** The item node, run once per element with the element as its task. Exactly one of `to`\n * and `graph`. Reachable only through this edge: never a delegates target. */\n readonly to?: NodeId\n /** A graph run per element as one subtask, through the `run_graph` path. */\n readonly graph?: GraphTopology\n /** Receives the ordered results once every item settled. Reachable only through this edge. */\n readonly join: NodeId\n /** The item directive, appended to the item node's instructions per traversal. */\n readonly directive: PromptHandle\n /** Lists longer than this are refused before any item runs. */\n readonly maxItems: number\n /** How many items run at once. */\n readonly concurrency: number\n readonly onItemFailure: MapItemFailurePolicy\n /** Each item's budget, merged over the per-worker default as `spawn_worker`'s `budget` is. */\n readonly itemBudget?: Partial<Budget>\n }\n /**\n * A route in a flow graph (one with `entry`): Runtime traverses it when `from` settles, so no\n * root decides the order, the branch, the repair loop or the stop. On each usable settle of\n * `from` its outgoing routes edges are tried in declaration order and the first whose `when`\n * holds fires; an edge without `when` is the default branch and comes last. A node target is\n * spawned with `{ from: { node, result }, evidence: { [id]: latest usable result } }` (a join's\n * target with `{ from: { nodes }, evidence }`, see below) and the directive appended to its pinned instructions; `{ stop }` ends the run with no winner and\n * `GraphResult.stopped`; `{ finish }` makes this settle part of the run's output.\n *\n * A fork lists two or more nodes in `to`: one traversal spawns each of them at once, each under\n * its own key `route:<edge id>#<traversal>:<node>`. A join lists two or more nodes in `from`: it\n * fires once every member has settled usably since it last fired, and the target's task is\n * `{ from: { nodes: <members in declared order> }, evidence }` with each member's latest result\n * in `evidence`, so it does not depend on which member settled last and a resumed run derives the\n * same task. A routes edge that spawns a node with a settled worker in this flow (a back edge)\n * names that node's latest settled worker as the spawn's `successorOf`. A join carries no `when`, and it is the only routes edge\n * leaving each of its members. A route into a node that still has a running worker throws\n * {@link GraphRouteError} with reason `target-live`: converging branches use a join.\n */\n | {\n readonly kind: 'routes'\n readonly from: NodeId | ReadonlyArray<NodeId>\n readonly to:\n | NodeId\n | ReadonlyArray<NodeId>\n | { readonly stop: string }\n | { readonly finish: string }\n readonly directive: PromptHandle\n /** Absent on the default edge and on every join. A match reads `from` unless it names a node\n * in `evidence`. */\n readonly when?: RouteWhen\n /** Nodes whose latest usable result rides the target's task. */\n readonly evidence?: ReadonlyArray<NodeId>\n /** Traversals beyond this are skipped (ledgered `unpropagated`) and matching continues with\n * the next edge. Default {@link defaultEdgeTraversalCap}. Every routes cycle, each subcycle\n * included, must cross an edge that sets it. */\n readonly maxTraversals?: number\n /** `'resume'` re-attaches each spawn of the target to its latest settled session. Omit =\n * `'fresh'`. */\n readonly continuity?: ContinuityMode\n }\n\n/** A topology without the run's own budget and deliverable: the form a `maps` edge runs per item,\n * as `run_graph` runs it. With `entry` it is a flow graph. Inside a maps item, the item value is\n * the task of every entry whose task is the placeholder `{ item: true }`; a down settle inside the item ends\n * that item only, and the maps edge's `onItemFailure` decides the join. */\nexport interface GraphTopology {\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n readonly entry?: AgentGraph['entry']\n /** Refused here: a maps item's graph and a `run_graph` subtask have no `decideGate`. */\n readonly gates?: AgentGraph['gates']\n}\n\nexport interface AgentGraph {\n /** Preserve fully bound literal data when serializing a hydrated graph. */\n readonly triggerBindings?: readonly []\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n /** Termination is mandatory, not optional: the independent completion oracle. */\n readonly deliverable: DeliverableSpec<unknown> & {\n readonly checkRef?: string\n readonly command?: GraphCommandCheck\n readonly when?: RouteWhen\n }\n /** One conserved pool across the whole graph — cycles without conservation never terminate. */\n readonly budget: Budget\n /** Setting it makes this a FLOW graph: Runtime spawns every entry at once, each with its task,\n * and traverses `routes` edges itself. No node is a root and no caller brain runs; the run's\n * output is `{ [node]: latest usable result }` over its terminal nodes and `finish` sources,\n * judged by `deliverable`. A stored route check (`checkRef: 'route'`) may also name a\n * non-terminal node: its condition reads that node's latest delivered output, while the output\n * stays terminal-only. */\n readonly entry?: ReadonlyArray<{ readonly node: NodeId; readonly task: unknown }>\n /** Flow-graph vertices that are not agents: a routes edge into one awaits\n * `RunGraphOptions.decideGate`, and one edge per choice leaves it, matching\n * `{ pointer: '/choice', equals: <choice> }`. A `finish` leaving a gate outputs\n * `{ [gate]: { choice, by } }`. */\n readonly gates?: ReadonlyArray<RouteGate>\n}\n\n// ── The edge ledger ────────────────────────────────────────────────────────────\n\n/** `failed` is a maps item or join that ran and settled without a usable result (down, or\n * rejected by its deliverable check); a traversal that never reached a worker is `unpropagated`. */\nexport type EdgeDeliveryOutcome = 'delivered' | 'stripped' | 'empty' | 'unpropagated' | 'failed'\n\n/** How one ledgered hop CONTINUED: a spawn traversal stamps its effective spawn mode\n * (`'fresh'` | `'resume'`), and every mid-run delivery into an already-live recipient — a\n * driver steer leg and every analyzes delivery (routed steer or driver-destined finding) —\n * stamps `'steer'`. Zero ambiguity: every row carries exactly one of the three. */\nexport type TraversalContinuity = ContinuityMode | 'steer'\n\n/** One recorded edge traversal — the in-memory row; the journal twin is the `edge` SpawnEvent. */\nexport interface EdgeTraversal {\n /** Stable edge id: `delegates:<from>-><to>`, `analyzes:<analyst>:<over…>-><to>`,\n * `maps:<from>-><to | graph>-><join>`, `routes:<from>#<ordinal>-><to | stop:<reason> |\n * finish:<reason>>`, or `routes:entry-><node>` for an entry. */\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes' | 'maps' | 'routes'\n readonly from: string\n readonly to: string\n /** The resolved directive reference (`<surface>/v<n>`). */\n readonly directive: string\n /** 1-based per-edge ordinal. */\n readonly traversal: number\n readonly outcome: EdgeDeliveryOutcome\n /** How this hop continued — see {@link TraversalContinuity}. */\n readonly continuity: TraversalContinuity\n /** Bytes of directive + payload that actually crossed the edge. */\n readonly bytes: number\n readonly reason?: string\n /** The concrete worker node id, once known. A maps expansion names the source worker. */\n readonly workerId?: string\n /** Present on maps rows: the expansion of the source's list, one item by its index, or the\n * join. */\n readonly map?: { readonly phase: 'expand' | 'item' | 'join'; readonly index?: number }\n /** Present on a gate's decision row (`gate:<id>`, `traversal` = visit): who decided, and what. */\n readonly gate?: GateDecisionRecord\n}\n\n/** A delegates edge exhausted its traversal cap and the run produced no winner: the cap, not the\n * task, ended it. Carries the full evidence so failing loud loses nothing. */\nexport class GraphEdgeCapError extends Error {\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly ledger: ReadonlyArray<EdgeTraversal>\n readonly result: SupervisedResult<unknown>\n constructor(\n exhaustedEdges: ReadonlyArray<string>,\n ledger: ReadonlyArray<EdgeTraversal>,\n result: SupervisedResult<unknown>,\n ) {\n super(\n `runGraph: edge traversal cap exhausted on ${exhaustedEdges.join(', ')} and the run ` +\n 'delivered no winner — the cap (the cyclic-graph backstop), not the task, ended this run. ' +\n 'Raise maxTraversals on the edge or fix the cycle; the full edge ledger and the ' +\n 'supervised result ride on this error.',\n )\n this.name = 'GraphEdgeCapError'\n this.exhaustedEdges = exhaustedEdges\n this.ledger = ledger\n this.result = result\n }\n}\n\n// ── Options / result ───────────────────────────────────────────────────────────\n\n/**\n * Every `SuperviseOptions` key, partitioned by what `runGraph` does with it.\n *\n * `runGraph` starts one `supervise()` run, so every option that run honors is a graph option too\n * unless the graph itself owns the value. This used to be an opt-in list written by hand, and the\n * hand lost: 25 of 49 keys never reached `supervise()` from a graph, including `childSettleGraceMs`\n * (a root-driver failure tore down children that had ALREADY computed the deliverable) and\n * `driverRetry` (agent-runtime#963). Each absence was discovered by losing a run.\n *\n * The four lists below must cover `keyof SuperviseOptions` exactly. `everySuperviseOptionIsClassified`\n * below fails to COMPILE, naming the offender, when a key belongs to none of them — so the next\n * option added to `supervise()` cannot go missing here silently. It has to be classified, and\n * classifying it as forwarded is one word.\n */\n\n/** The graph derives these from the `AgentGraph` itself; a caller value would be overwritten. */\nconst GRAPH_OWNED_SUPERVISE_OPTIONS = [\n 'rootDriverFromBackend',\n 'resolveSpawnProfile',\n 'budget',\n 'deliverable',\n 'makeWorkerAgent',\n 'onCoordinationEvent',\n 'analyzeOnSettle',\n 'mapOnSettle',\n // A flow graph's entries and routes edges; its runtime-owned root runs them.\n 'routeFlow',\n 'continuityByProfile',\n // A graph pins every node and its delegation edges; a node never gains spawn rights it lacks.\n 'inheritSpawnRights',\n] as const\n\n/** Caller-facing on `RunGraphOptions`, but the graph wraps or defaults the value before it goes in:\n * `hooks` composes with the graph's own spawn-binding hook, `authorizeMessage` is wrapped so a\n * narrowed instruction ledgers `stripped`, `authorizeSpawn` runs AFTER the graph has pinned the\n * node (so a product sees the canonical profile, never the driver's stub), `makeLeafAgent` is the\n * caller's leaf override slotted under the graph's pinning, `analysts` rides only with analyze\n * routes, and `journal`/`blobs`/`runId` get graph defaults. */\nconst GRAPH_TRANSFORMED_SUPERVISE_OPTIONS = [\n 'hooks',\n 'authorizeMessage',\n 'authorizeSpawn',\n 'makeLeafAgent',\n 'analysts',\n 'journal',\n 'blobs',\n 'runId',\n // Replays a journaled decision before asking the caller.\n 'decideGate',\n] as const\n\n/** Not reachable from a graph, with the reason. `registry` is a NAME COLLISION, not a policy:\n * `RunGraphOptions.registry` is the directive `PromptRegistry` and `SuperviseOptions.registry` is\n * the `SuperviseRegistry` name→value table. Two different types under one name; the graph's wins.\n * Giving the supervise one a graph channel means renaming a public option, so it is recorded here\n * rather than silently dropped. */\nconst GRAPH_REFUSED_SUPERVISE_OPTIONS = ['registry'] as const\n\n/**\n * Forwarded to the root `supervise()` VERBATIM. Everything not owned, transformed, or refused\n * above belongs here — the default is \"a graph honors it\", not \"someone remembered to add it\".\n */\nconst GRAPH_FORWARDED_SUPERVISE_OPTIONS = [\n 'parking',\n 'backend',\n // Forwarded: composes guidance into the root and into profiles a manager authors. The graph also\n // composes each PINNED node profile, because pinning replaces the composed `{ name }` stub.\n 'profileGuidance',\n // Forwarded, not graph-owned: a graph pins WHICH nodes run, never who answers a question one of\n // them raises. Without it a graph run's `ask_parent` would always report `no-parent` even when\n // the caller wired an inbox.\n 'escalateQuestion',\n 'rootHandle',\n 'signal',\n 'execution',\n 'resolveDeliverable',\n 'coordination',\n 'peerMail',\n 'peerAudit',\n 'traceTools',\n 'driverBackend',\n 'profileSecurity',\n 'authorizeSpawn',\n 'router',\n 'driveHarness',\n 'selectSeat',\n 'driverRetry',\n 'onDriverAttempt',\n 'workerRetry',\n 'onWorkerRetry',\n 'continuation',\n 'childSettleGraceMs',\n 'teardownConfirmMs',\n 'retainedAtSettlement',\n 'resolveDriveHarness',\n 'driveHarnessMaterialization',\n 'resolveSupervisorTools',\n 'extraTools',\n 'executeExtraTool',\n 'recoverExecutor',\n 'perWorker',\n 'reservationPolicy',\n 'deadlineCheckIn',\n 'budgetStopHoldMs',\n 'workerSlots',\n 'watchWorkers',\n 'stallAfterMs',\n 'wake',\n 'runDir',\n 'resume',\n 'segment',\n 'runContext',\n 'steerDir',\n 'stopRule',\n 'onProgressStop',\n 'maxDepth',\n 'maxTurns',\n 'compaction',\n 'now',\n 'allowedModels',\n 'finalizer',\n 'otel',\n // Forwarded: the registry a manager's `run_graph` resolves stored graphs against. A node of this\n // graph cannot start another graph (pinning refuses it), so it matters to no node here.\n 'graphRegistry',\n] as const\n\ntype ClassifiedSuperviseOption =\n | (typeof GRAPH_OWNED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_TRANSFORMED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_REFUSED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]\n\n/**\n * Every key `RunGraphOptions` accepts, as data: the forwarded and transformed `SuperviseOptions`\n * keys, the name-colliding `registry`, and the graph's own `brain`. `GRAPH_OWNED_SUPERVISE_OPTIONS`\n * is deliberately absent — a caller value for one of those is overwritten by the graph, so it is\n * refused by name rather than discarded.\n *\n * The assignment below fails to COMPILE, naming the key, when `RunGraphOptions` declares something\n * this list does not carry.\n */\nconst runGraphOptionKeys = [\n ...GRAPH_FORWARDED_SUPERVISE_OPTIONS,\n ...GRAPH_TRANSFORMED_SUPERVISE_OPTIONS,\n ...GRAPH_REFUSED_SUPERVISE_OPTIONS,\n 'brain',\n] as const\n\ntype UnlistedRunGraphOption = Exclude<keyof RunGraphOptions, (typeof runGraphOptionKeys)[number]>\nconst everyRunGraphOptionIsListed: UnlistedRunGraphOption extends never\n ? true\n : UnlistedRunGraphOption = true\nvoid everyRunGraphOptionIsListed\n\nconst runGraphOptionKeySet: ReadonlySet<string> = new Set<string>(runGraphOptionKeys)\nconst graphOwnedOptionKeySet: ReadonlySet<string> = new Set<string>(GRAPH_OWNED_SUPERVISE_OPTIONS)\n\n/**\n * Refuse an option key the graph would not read, naming it and saying which kind it is.\n *\n * A graph-owned key is the sharper case: it type-checks against a widened `SuperviseOptions`\n * value, the graph derives its own value and overwrites the caller's, the run succeeds, and the\n * capability the caller asked for is not there. The rename of the leaf seam from `makeWorkerAgent`\n * to `makeLeafAgent` is the shape of the failure — the old name stayed a valid `SuperviseOptions`\n * key AND a graph-owned one, so a caller that kept passing it got a run with no leaf override and\n * no complaint.\n */\nfunction assertRunGraphOptionKeys(opts: RunGraphOptions): void {\n const graphOwned: string[] = []\n const unknown: string[] = []\n for (const key of Object.keys(opts)) {\n if (runGraphOptionKeySet.has(key)) continue\n if (graphOwnedOptionKeySet.has(key)) graphOwned.push(key)\n else unknown.push(key)\n }\n if (graphOwned.length > 0) {\n throw new ConfigError(\n `runGraph: ${graphOwned.sort().join(', ')} — the graph derives this from the AgentGraph ` +\n 'itself, so a caller value is overwritten and the capability it asks for would silently ' +\n 'be absent',\n )\n }\n if (unknown.length > 0) {\n throw new ConfigError(\n `runGraph: unknown option ${unknown.sort().join(', ')} — no reader consults that name, so ` +\n 'the value would be discarded and the capability it asks for would silently be absent',\n )\n }\n}\n\n/** A `SuperviseOptions` key in none of the four lists makes this assignment fail, and the compiler\n * error names the key. Classify it — `GRAPH_FORWARDED_SUPERVISE_OPTIONS` is usually the answer. */\ntype UnclassifiedSuperviseOption = Exclude<keyof SuperviseOptions, ClassifiedSuperviseOption>\nconst everySuperviseOptionIsClassified: UnclassifiedSuperviseOption extends never\n ? true\n : UnclassifiedSuperviseOption = true\nvoid everySuperviseOptionIsClassified\n\n/** `backend` and `driverBackend` keep graph-specific documentation below.\n *\n * Do not inherit and redeclare them through an indexed access type.\n * TypeScript 7 correctly treats `SuperviseOptions['backend']` as including `undefined`, which makes\n * that redeclaration wider than the exact optional property inherited from `SuperviseOptions`.\n */\ntype GraphInheritedSuperviseOption = Exclude<\n (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number],\n 'backend' | 'driverBackend'\n>\n\n/** Copy every forwarded option the caller actually set. Absent stays absent: `supervise()` and the\n * graph must not disagree about what \"unset\" means. */\nfunction forwardedSuperviseOptions(\n opts: RunGraphOptions,\n): Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\n const forwarded: Record<string, unknown> = {}\n for (const key of GRAPH_FORWARDED_SUPERVISE_OPTIONS) {\n const value = (opts as Record<string, unknown>)[key]\n if (value !== undefined) forwarded[key] = value\n }\n return forwarded as Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]>\n}\n\n/**\n * Options for one `runGraph` run.\n *\n * Extends every forwarded `SuperviseOptions` key, so a graph honors what a `supervise()` run\n * honors WITHOUT anyone restating it here. Only the graph-specific members and the ones whose\n * graph semantics differ are declared below; everything else inherits its type AND its\n * documentation from `SuperviseOptions`, which is the one owner of both.\n */\nexport interface RunGraphOptions extends Pick<SuperviseOptions, GraphInheritedSuperviseOption> {\n /** WHERE worker nodes run — the executor backend. Provide this OR `makeLeafAgent`. Forwarded to\n * `supervise()`, which derives every authorized leaf from it. A node that declares\n * `agent_runtime_coordination_spawn_worker` becomes a nested supervisor instead, whose own\n * leaves are derived the same way. */\n readonly backend?: Exclude<SuperviseOptions['backend'], undefined>\n /** WHERE the ROOT node's harness brain runs — forwarded to `supervise()` verbatim (see\n * `SuperviseOptions.driverBackend`). Needed when the root node's profile declares an external\n * harness (`codex`, `claude-code`, `opencode`): that root is driven by the harness, not by the\n * router brain, and automatic execution supports a local `bridge`. Unlike `supervise()`, this\n * does NOT default to `backend`: a graph's `backend` places WORKER nodes, so the root driver\n * is selected only by this field. Omit = no harness driver, which is correct for a root whose\n * `profile.harness` is omitted or `cli-base` (that root runs on the router brain). */\n readonly driverBackend?: Exclude<SuperviseOptions['driverBackend'], undefined>\n /** Leaf-execution override (offline tests / advanced). `runGraph` still owns node pinning,\n * directive delivery, and the edge ledger AROUND this seam — only the leaf `act` is yours.\n * Slots INSIDE the kernel's authorized path (`SuperviseOptions.makeLeafAgent`), so a node that\n * declares the spawn tool still becomes a nested supervisor even under an offline leaf. */\n readonly makeLeafAgent?: MakeWorkerAgent\n /** The ROOT driver's inference seam — a caller-owned `ToolLoopChat` that makes every root\n * model call. Use it when the root's decisions must be caller-owned orchestration (a\n * deterministic conversation driver, a persona loop with its own LLM calls) rather than a\n * router-derived model call. The graph machinery around the seam is unchanged: node pinning,\n * directive delivery, the edge ledger, and the journal twin all run the same shipped path,\n * and the root profile keeps prompt control (`prompt-control-execution` materialization —\n * `systemPrompt`/`instructions` still apply). What moves to the caller with the brain:\n * model selection and provider-identity validation (`expectedModel` cannot be enforced on a\n * call the runtime did not place) and per-turn usage reporting (a brain that reports no\n * usage meters nothing into the pool). Omit = the router brain derived from the root\n * profile — the unchanged default. Mutually exclusive with `driverBackend`, and refused\n * when the root profile declares an external harness (that root is driven BY the harness). */\n readonly brain?: ToolLoopChat\n /** Caller-side runtime hooks (telemetry, policy, product extensions). Composed AFTER the\n * graph's own spawn-binding hook on the SAME event stream — the graph never swallows the\n * seam supervise() exposes. */\n readonly hooks?: RuntimeHooks\n /** The analyst lens registry `analyzes` edges resolve against. ENVIRONMENT — needed only for\n * lens analysts; an analyzes edge naming a graph NODE as its analyst needs no registry. */\n readonly analysts?: AnalystRegistry\n /** Answers a flow gate while the process holds the run; the wait counts against its deadline.\n * ENVIRONMENT, like `analysts`; required when the graph declares gates. */\n readonly decideGate?: (request: GateRequest) => Promise<GateDecision>\n /** Directive registry. Default: the seeded kernel registry (`kernelPromptRegistry()`).\n *\n * NOT `SuperviseOptions.registry`, which is the `SuperviseRegistry` name→value table for\n * code-valued options. The two share a name and nothing else, and this one wins here — see\n * `GRAPH_REFUSED_SUPERVISE_OPTIONS`. */\n readonly registry?: PromptRegistry\n /** The run journal the edge ledger and every spawn/settle ride. Default: in-memory. */\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly runId?: string\n /** Product authority over every steer/answer instruction (the filter seam). `runGraph` observes\n * what it CHANGES: a narrowed instruction ledgers its steer traversal as `stripped`. */\n readonly authorizeMessage?: SuperviseOptions['authorizeMessage']\n}\n\nexport interface GraphResult<Out = unknown> {\n readonly result: SupervisedResult<Out>\n /** Every edge traversal, in occurrence order — the observable-edge contract. */\n readonly ledger: ReadonlyArray<EdgeTraversal>\n /** Edge ids whose traversal cap was hit — analyzes exhaustion included (observable here, never\n * a refusal). A DELEGATES cap paired with a `no-winner` result THROWS\n * ({@link GraphEdgeCapError}) instead of returning: only delegates caps refuse spawns, so only\n * they can have ended the run. A LIFECYCLE no-winner (`aborted` / `budget-exhausted`) returns\n * normally even with an exhausted delegates cap — the abort or the pool, not the cap, ended\n * that run, and the exhaustion stays observable here. */\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly runId: string\n /** Why a flow graph ended early: a `stop` edge fired (`edge` names it), or a flow node settled\n * down (no `edge`; `reason` is `down: <worker reason>`) or, where a route was needed, without a\n * usable result (no `edge`; `reason` is `unusable: <why>`). Live flow workers are aborted. */\n readonly stopped?: {\n readonly code?: string\n readonly edge?: string\n readonly at: NodeId\n readonly workerId: string\n readonly reason: string\n }\n}\n\n/** `RunGraphOptions` with the brain REQUIRED — the shape the `/testing` entry's\n * `runGraphWithTestBrain` keeps accepting now that `brain` is a production option. */\nexport interface RunGraphTestOptions extends RunGraphOptions {\n readonly brain: ToolLoopChat\n}\n\n// ── Validation ─────────────────────────────────────────────────────────────────\n\n/** Validate the graph and resolve every directive BEFORE any compute is spent — an invalid\n * topology or an unknown directive is a configuration fault, never a mid-run surprise. */\nfunction validateGraph(\n graph: AgentGraph,\n registry: PromptRegistry,\n analysts: AnalystRegistry | undefined,\n): ValidatedGraph {\n if (graph.entry === undefined) {\n if (!Array.isArray(graph.nodes) || graph.nodes.length === 0) {\n throw new ValidationError('runGraph: graph.nodes must be a non-empty array')\n }\n if (!Array.isArray(graph.edges) || graph.edges.length === 0) {\n throw new ValidationError('runGraph: graph.edges must be a non-empty array')\n }\n }\n if (typeof graph.deliverable?.check !== 'function') {\n throw new ValidationError('runGraph: graph.deliverable is mandatory (termination oracle)')\n }\n if (typeof graph.budget !== 'object' || graph.budget === null) {\n throw new ValidationError('runGraph: graph.budget is mandatory (the conserved pool)')\n }\n if (graph.entry !== undefined) return validateFlowGraph(graph, registry, analysts)\n if (graph.gates !== undefined)\n throw new ValidationError('runGraph: graph.gates needs graph.entry')\n return validateGraphTopology(graph.nodes, graph.edges, registry, analysts)\n}\n\n// ── The runner ─────────────────────────────────────────────────────────────────\n\n/**\n * Execute an {@link AgentGraph}. A flow graph (`entry` set) runs from its entries and routes edges\n * under a runtime-owned root that places no model call. Otherwise the root node becomes the\n * supervisor (`supervise()` — the execution core), each worker node is spawnable BY NODE ID\n * (`spawn_worker` with `profile: { name: '<node id>' }`; the node's canonical profile is pinned by\n * the graph), each\n * delegates directive is appended to the worker profile's `prompt.instructions` per traversal,\n * and each analyzes edge becomes an analyst-on-settle route with a real DESTINATION. Every\n * traversal is ledgered and journaled.\n */\nexport function runGraph(graph: AgentGraph, opts: RunGraphOptions): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = graphExecutionOptions(opts)\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/** Alias for graph tests written before `RunGraphOptions.brain` was production. The production\n * entry accepts the same shape; this wrapper only keeps the `/testing` import path working. */\nexport function runGraphWithTestBrain(\n graph: AgentGraph,\n opts: RunGraphTestOptions,\n): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/**\n * The graph supervise run, as its own entry: the engine's `run-graph` preset node executes exactly\n * this, so the preset and `runGraph` are the same code path by construction (agent-runtime#982).\n */\n/**\n * Every refusal a graph earns before any compute, in one place: the authoring contract. `runGraph`\n * calls it FIRST so a malformed graph throws synchronously, exactly as it did before the engine\n * preset (agent-runtime#982) moved execution behind a promise.\n */\nexport function assertRunGraphAuthoring(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): ReturnType<typeof validateGraph> {\n assertRunGraphOptionKeys(opts)\n const registry = opts.registry ?? kernelPromptRegistry()\n const validated = validateGraph(graph, registry, opts.analysts)\n const requireLeaves = (): void => {\n if (!opts.backend && !opts.makeLeafAgent) {\n throw new ValidationError(\n 'runGraph: provide opts.backend (where nodes run) or opts.makeLeafAgent',\n )\n }\n }\n if (validated.flow !== undefined) {\n // A flow's root is Runtime's own: nothing a caller sets for a root manager has a reader.\n const rootOptions = [\n ...(brain ? ['brain'] : []),\n ...(['driverBackend', 'finalizer', 'maxTurns', 'compaction'] as const).filter(\n (key) => opts[key] !== undefined,\n ),\n ]\n if (rootOptions.length > 0) {\n throw new ValidationError(\n `runGraph: ${rootOptions.join(', ')} with graph.entry — a flow graph has no root ` +\n 'manager: Runtime spawns its entries and traverses its routes edges, and the graph ' +\n \"owns the run's output\",\n )\n }\n if ((graph.gates?.length ?? 0) > 0 && opts.decideGate === undefined) {\n throw new ValidationError('runGraph: graph.gates needs opts.decideGate to answer them')\n }\n requireLeaves()\n return validated\n }\n const { root } = validated as RootValidatedGraph\n // A caller brain and a harness driver are two answers to WHO makes the root's calls: refuse the\n // contradiction before any compute, and refuse a harness-driven root outright — the harness IS\n // that root's brain, so a supplied one would be silently ignored downstream.\n if (brain && opts.driverBackend) {\n throw new ValidationError(\n 'runGraph: brain and driverBackend are mutually exclusive — a caller brain makes the root model calls, a driverBackend places a harness that makes its own',\n )\n }\n if (brain && harnessRunsAgent(root.profile.harness)) {\n throw new ValidationError(\n `runGraph: root node '${root.id}' declares harness '${root.profile.harness}', so the harness drives it — a caller brain applies only to a router-brained root (profile.harness omitted or 'cli-base')`,\n )\n }\n requireLeaves()\n return validated\n}\n\nexport function superviseAgentGraph(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): Promise<GraphResult> {\n if (graph.deliverable.command !== undefined) {\n const bound = bindGraphCommand(graph, opts)\n return superviseAgentGraph(bound.graph, bound.options, brain)\n }\n const registry = opts.registry ?? kernelPromptRegistry()\n if (opts.runContext?.acquire !== undefined) {\n return withRunContext(opts.runContext, opts.signal, (runContext, signal) =>\n superviseAgentGraph(\n graph,\n {\n ...opts,\n runContext,\n ...(signal === undefined ? {} : { signal }),\n },\n brain,\n ),\n )\n }\n const validated = assertRunGraphAuthoring(graph, opts, brain)\n const context =\n opts.runContext ??\n (opts.runDir === undefined\n ? createInMemoryRunContext()\n : createFileRunContext(resolve(opts.runDir)))\n const journal = opts.journal ?? context.journal\n const blobs = opts.blobs ?? context.blobs\n const runId =\n opts.runId ??\n opts.runContext?.runId ??\n `graph-${canonicalCandidateDigest(graph.nodes.map((n) => n.id)).slice('sha256:'.length, 'sha256:'.length + 12)}`\n const now = opts.now ?? Date.now\n\n // The graph layer: node pinning, analyst routes, continuity defaults and the edge ledger. A\n // `run_graph` subtask builds the same overlay around its nested manager.\n // `profileGuidance` composes the profile a manager authors, but a graph then swaps that\n // `{ name }` stub for the pinned node profile. Compose the pinned profile too, so every node\n // that runs carries its harness and model guidance. Composition is idempotent.\n const guidance = profileGuidanceComposer(opts.profileGuidance)\n const overlay = createGraphOverlay(validated, {\n registry,\n journal,\n runId,\n now,\n ...(guidance ? { guidance } : {}),\n ...(opts.authorizeSpawn ? { authorizeSpawn: opts.authorizeSpawn } : {}),\n })\n // A flow graph: Runtime schedules its nodes, and its root manager is Runtime's own.\n const flow = validated.flow === undefined ? undefined : createFlowRun(overlay.nodeOfWorker)\n // Always present: the kernel refuses steer/answer whenever spawn authorization is on (the\n // graph's pinning IS spawn authorization), so a graph with no caller filter passes instructions\n // through unchanged rather than losing its steer channel. Only a caller filter can strip.\n const callerAuthorizeMessage = opts.authorizeMessage\n const authorizeMessage = overlay.observeMessages<\n Parameters<NonNullable<SuperviseOptions['authorizeMessage']>>[0]\n >((input) =>\n callerAuthorizeMessage ? callerAuthorizeMessage(input) : { instruction: input.instruction },\n )\n\n // ── Spawn-hook: bind ledger rows to concrete worker ids, then journal them ──\n const graphHooks: RuntimeHooks = {\n onEvent: (event) => {\n if (event.target !== 'agent.spawn' || event.phase !== 'after') return\n const payload = event.payload as { childId?: unknown; assignmentId?: unknown } | undefined\n if (typeof payload?.childId !== 'string' || typeof payload.assignmentId !== 'string') return\n return overlay.bindSpawn(event.parentId, payload.assignmentId, payload.childId)\n },\n }\n const hooks = composeRuntimeHooks(graphHooks, opts.hooks)\n const rootProfile =\n flow === undefined\n ? graphRootProfile(validated as RootValidatedGraph, registry)\n : flowRootProfile\n const rootBrain = flow === undefined ? brain : runtimeFlowBrain()\n const task =\n flow === undefined\n ? (graph.deliverable.describe ??\n `Deliver the graph's deliverable by driving your worker nodes (root: '${(validated as RootValidatedGraph).root.id}').`)\n : (graph.deliverable.describe ?? 'Runtime runs this flow graph from its entries.')\n\n // Every configuration fault above throws SYNCHRONOUSLY (matching `supervise()`'s own\n // contract); only the run itself is asynchronous.\n const start = async (): Promise<GraphResult> => {\n const superviseOptions = {\n // The backend also drives seat-bearing flow nodes, which use the managed driver lifecycle.\n // A flow's root keeps Runtime's deterministic brain; deriving its child driver adds no root\n // inference. Rooted graphs keep driverBackend explicit rather than inheriting backend.\n ...forwardedSuperviseOptions(opts),\n rootDriverFromBackend: flow !== undefined,\n // Graph-owned values come after the spread: the graph, not the caller, decides these.\n budget: graph.budget,\n deliverable: flow?.routeCheck(graph.deliverable) ?? graph.deliverable,\n authorizeSpawn: overlay.authorizeSpawn,\n resolveSpawnProfile: overlay.resolveSpawnProfile,\n inheritSpawnRights: false,\n ...(opts.makeLeafAgent ? { makeLeafAgent: opts.makeLeafAgent } : {}),\n journal,\n blobs,\n runId,\n hooks,\n onCoordinationEvent: async (\n context: { readonly depth: number },\n _eventId: unknown,\n record: { readonly event: Parameters<typeof overlay.onCoordinationEvent>[0] },\n ) => {\n // A route event belongs to the flow of the manager that published it: a flow inside a\n // maps item or a run_graph subtask ledgers and concludes its own.\n if (record.event.type === 'route' && context.depth !== 0) return\n overlay.onCoordinationEvent(record.event)\n flow?.observe(record.event)\n },\n // Lens routes resolve against the registry; agent routes carry their own analyst profile,\n // so a graph whose only analysts are nodes needs no registry at all.\n ...(overlay.routes.length > 0\n ? {\n analyzeOnSettle: overlay.routes,\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n }\n : {}),\n ...(overlay.maps.length > 0 ? { mapOnSettle: overlay.maps } : {}),\n ...(Object.keys(overlay.continuityByProfile).length > 0\n ? { continuityByProfile: overlay.continuityByProfile }\n : {}),\n // A flow root's wake batches nothing for a decision, so it ends its turn on the first event.\n ...(flow === undefined\n ? {}\n : {\n routeFlow: routeFlowOf(validated),\n ...(opts.decideGate && {\n decideGate: journaledGateDecider(opts.decideGate, journal, runId),\n }),\n finalizer: flow.finalizer,\n wake: { debounceMs: 0, ...opts.wake },\n }),\n authorizeMessage,\n } satisfies SuperviseOptions\n // The flow root reaches supervise through the same brain seam a caller brain takes.\n const supervised =\n rootBrain === undefined\n ? await supervise(rootProfile, task, superviseOptions)\n : await superviseWithTestBrain(rootProfile, task, { ...superviseOptions, brain: rootBrain })\n\n const { ledger, exhaustedEdges, exhaustedDelegates } = await overlay.settle()\n const concluded = flow?.conclude(supervised)\n if (concluded?.kind === 'unrouted') {\n throw new GraphRouteError(concluded.unrouted, ledger, supervised)\n }\n const result = concluded?.result ?? supervised\n const stopped = concluded?.stopped\n // A LIFECYCLE ending (caller abort, exhausted budget, deadline) is its own complete explanation: the\n // cap did not end that run even when it was exhausted along the way, and blaming it would\n // misattribute the ending (and turn a caller-initiated abort into a throw). The exhaustion\n // stays observable in `exhaustedEdges` either way.\n const lifecycleEnded =\n result.kind === 'no-winner' &&\n (result.reason === 'aborted' ||\n result.reason === 'cancelled' ||\n result.reason === 'budget-exhausted' ||\n result.reason === 'deadline')\n if (result.kind !== 'winner' && !lifecycleEnded && exhaustedDelegates.length > 0) {\n // Fail LOUD: the backstop, not the task, ended this run. The evidence rides on the error.\n // Only DELEGATES caps refuse spawns, so only they can be the cause named here.\n throw new GraphEdgeCapError(exhaustedDelegates, ledger, result)\n }\n return { result, ledger, exhaustedEdges, runId, ...(stopped ? { stopped } : {}) }\n }\n\n return start()\n}\n"],"mappings":";;;;;;;;;;;;;AAIA,SAAgB,sBAAsB,SAA2C;CAC/E,IAAI,QAAQ,eAAe,OAAO;CAClC,MAAM,UAAU,QAAQ;CACxB,IAAI,SACF,OAAO,QA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;GAAO,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAAG;CAClF;CAEA,OAAO,MAAM;AACf"}
1
+ {"version":3,"file":"graph-DSVXDbSf.js","names":[],"sources":["../src/runtime/supervise/graph-backend.ts","../src/runtime/supervise/stored-graph-check.ts","../src/runtime/supervise/graph.ts"],"sourcesContent":["import { ValidationError } from '../../errors'\nimport type { RunGraphOptions } from './graph'\n\n/** Graph nodes expose JSON outputs through Runtime's resumable execution transports. */\nexport function graphExecutionOptions(options: RunGraphOptions): RunGraphOptions {\n if (options.makeLeafAgent) return options\n const backend = options.backend\n if (backend)\n return backend.backend === 'bridge' || backend.backend === 'provider'\n ? { ...options, backend: { ...backend, outputFormat: 'json' } }\n : options\n const bridgeUrl = process.env.CLI_BRIDGE_URL\n const bridgeBearer = process.env.BRIDGE_BEARER ?? process.env.CLI_BRIDGE_BEARER\n if (!bridgeUrl || !bridgeBearer)\n throw new ValidationError(\n 'runGraph: start CLI Bridge and supply backend: { backend: \"bridge\", bridgeUrl, bridgeBearer, cwd }, or configure CLI_BRIDGE_URL and BRIDGE_BEARER',\n )\n return {\n ...options,\n backend: {\n backend: 'bridge',\n bridgeUrl,\n bridgeBearer,\n cwd: process.cwd(),\n outputFormat: 'json',\n },\n }\n}\n","import { mkdirSync, realpathSync } from 'node:fs'\nimport { isAbsolute, join, relative } from 'node:path'\nimport { contentAddress } from '../../durable/content-address'\nimport {\n appendCommittedJsonLine,\n readCommittedJsonLines,\n withJsonlFileLock,\n} from '../../durable/jsonl-file'\nimport { ValidationError } from '../../errors'\nimport { defaultRunCommand } from '../../mcp/worktree-harness'\nimport type { CompletionCheckContext } from './completion-gate'\nimport type { AgentGraph, RunGraphOptions } from './graph'\n\n/** An environment-owned check command, run outside the agent's conversation. */\nexport interface GraphCommandCheck {\n readonly command: string\n readonly timeoutMs?: number\n}\n\nexport interface GraphFromStoredOptions {\n readonly trigger?: Readonly<Record<string, unknown>>\n readonly checks?: Readonly<Record<string, AgentGraph['deliverable']['check'] | GraphCommandCheck>>\n}\n\ninterface CommandCheckReceipt {\n readonly version: 1\n readonly key: string\n readonly binding: string\n readonly checkDigest: string\n readonly nodeName: string\n readonly nodeId: string\n readonly attemptId: string\n readonly outputDigest: string\n readonly exitCode: number | null\n readonly output: string\n readonly outputTruncated: boolean\n readonly nativeValid: boolean\n readonly valid: boolean\n}\n\n/** Driver-owned journal identity. Worker output never supplies any part of this authority. */\nfunction receiptKey(receipt: Omit<CommandCheckReceipt, 'key'>): string {\n return contentAddress({\n binding: receipt.binding,\n checkDigest: receipt.checkDigest,\n nodeName: receipt.nodeName,\n nodeId: receipt.nodeId,\n attemptId: receipt.attemptId,\n outputDigest: receipt.outputDigest,\n })\n}\n\nfunction isReceipt(value: unknown): value is CommandCheckReceipt {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const row = value as Record<string, unknown>\n if (\n row.version !== 1 ||\n ![\n 'key',\n 'binding',\n 'checkDigest',\n 'nodeName',\n 'nodeId',\n 'attemptId',\n 'outputDigest',\n 'output',\n ].every((key) => typeof row[key] === 'string') ||\n !row.nodeName ||\n !row.nodeId ||\n !row.attemptId ||\n !(row.exitCode === null || Number.isSafeInteger(row.exitCode)) ||\n typeof row.outputTruncated !== 'boolean' ||\n typeof row.nativeValid !== 'boolean' ||\n typeof row.valid !== 'boolean'\n )\n return false\n const receipt = value as CommandCheckReceipt\n return (\n receipt.key === receiptKey(receipt) &&\n receipt.valid === (receipt.exitCode === 0 && receipt.nativeValid)\n )\n}\n\nfunction within(directory: string, path: string): boolean {\n const offset = relative(directory, path)\n return offset === '' || (!isAbsolute(offset) && offset !== '..' && !offset.startsWith('../'))\n}\n\n/** Lower a named check onto the local workspace, with evidence in the driver's durable state.\n * The run directory has the same trust boundary as RunContext journals: keep it outside the\n * worker workspace and do not mount it into the worker. A remote Bridge cannot run a host check.\n * Provider validators are refused because their context does not identify the admitted node.\n */\nexport function bindGraphCommand(\n graph: AgentGraph,\n options: RunGraphOptions,\n): { graph: AgentGraph; options: RunGraphOptions } {\n const { command: definition, ...deliverable } = graph.deliverable\n if (!definition) return { graph, options }\n const { command, timeoutMs = 60_000 } = definition\n if (!command.trim() || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)\n throw new ValidationError(\n 'graphFromStored: command check needs a command and positive timeoutMs',\n )\n const backend = options.backend\n if (options.makeLeafAgent || !backend)\n throw new ValidationError('runGraph: command checks require an explicit execution backend')\n const workspace =\n backend.backend === 'bridge'\n ? backend.cwd\n : backend.backend === 'cli-in-place'\n ? backend.workspacePath\n : undefined\n if (\n !workspace ||\n (backend.backend === 'bridge' &&\n !['localhost', '127.0.0.1', '[::1]'].includes(new URL(backend.bridgeUrl).hostname))\n )\n throw new ValidationError(\n 'runGraph: command checks require a loopback Bridge or local CLI workspace; provider node binding is unsupported',\n )\n if (!options.runDir)\n throw new ValidationError(\n 'runGraph: command checks require a driver-owned runDir outside the workspace',\n )\n const cwd = realpathSync(workspace)\n mkdirSync(options.runDir, { recursive: true })\n const runDir = realpathSync(options.runDir)\n if (within(cwd, runDir))\n throw new ValidationError('runGraph: command check runDir must be outside the worker workspace')\n const file = join(runDir, 'command-checks.jsonl')\n const checkDigest = contentAddress({ command, timeoutMs, cwd })\n const binding = contentAddress({\n graph: { ...graph, deliverable: { ...deliverable, check: undefined } },\n runId: options.runId ?? options.runContext?.runId,\n checkDigest,\n })\n const nodeNames = new Set(graph.nodes.map((node) => node.id))\n\n // The map is supplied by Runtime's flow finalizer. It contains terminal graph node IDs and\n // outputs, never receipt metadata. Every match must come from this run's driver journal.\n const checkFinal = async (out: unknown): Promise<boolean> => {\n if (!out || typeof out !== 'object' || Array.isArray(out)) return false\n const entries = Object.entries(out)\n if (entries.length === 0 || entries.some(([name]) => !nodeNames.has(name))) return false\n return withJsonlFileLock(file, async (canonicalPath) => {\n if (within(cwd, canonicalPath)) return false\n const latest = new Map<string, CommandCheckReceipt>()\n for await (const raw of readCommittedJsonLines<unknown>(canonicalPath, {\n allowMissing: true,\n })) {\n if (!isReceipt(raw)) return false\n if (raw.binding !== binding || raw.checkDigest !== checkDigest) continue\n latest.set(contentAddress([raw.nodeName, raw.outputDigest]), raw)\n }\n return entries.every(\n ([name, output]) =>\n latest.get(contentAddress([name, contentAddress(output)]))?.valid === true,\n )\n })\n }\n\n const checkLeaf = async (out: unknown, context: CompletionCheckContext): Promise<boolean> => {\n const node = context.node\n const nodeName = context.profile.name\n if (!node || !node.nodeId || !node.attemptId || !nodeName || !nodeNames.has(nodeName))\n return false\n // Always execute for a fresh leaf. A prior success, even for identical output, never skips\n // this check. gateFactoryOnDeliverable deduplicates only one invocation's exact artifact.\n const outputDigest = contentAddress(out)\n let result: { exitCode: number | null; output: string }\n try {\n result = await defaultRunCommand({ command, cwd, timeoutMs, signal: context.signal })\n } catch (error) {\n // An unavailable check invalidates an earlier identical output too; it cannot inherit\n // a prior success just because the current command did not reach a normal exit.\n result = { exitCode: null, output: error instanceof Error ? error.message : String(error) }\n }\n const bytes = Buffer.from(result.output)\n const limit = 64 * 1024\n const receipt: Omit<CommandCheckReceipt, 'key'> = {\n version: 1,\n binding,\n checkDigest,\n nodeName,\n nodeId: node.nodeId,\n attemptId: node.attemptId,\n outputDigest,\n exitCode: result.exitCode,\n output: bytes.subarray(0, limit).toString('utf8'),\n outputTruncated: bytes.length > limit,\n nativeValid: context.originalVerdict?.valid !== false,\n valid: result.exitCode === 0 && context.originalVerdict?.valid !== false,\n }\n await withJsonlFileLock(file, async (canonicalPath) => {\n if (within(cwd, canonicalPath))\n throw new ValidationError(\n 'runGraph: command receipt journal resolves inside worker workspace',\n )\n await appendCommittedJsonLine(canonicalPath, { ...receipt, key: receiptKey(receipt) })\n })\n return receipt.valid\n }\n return {\n graph: {\n ...graph,\n deliverable: {\n ...deliverable,\n check: (out, context) =>\n context === undefined ? checkFinal(out) : checkLeaf(out, context),\n },\n },\n options,\n }\n}\n","/**\n *\n * `runGraph` — agent graphs: profiles as nodes, registry-backed prompt directives as edges.\n *\n * A topology is PLAIN DATA an agent can author in a few lines: nodes are canonical\n * `AgentProfile`s (the ONLY way a node is described — no role-builder functions), edges are typed\n * values carrying versioned {@link PromptHandle} directives, `deliverable` (termination) and\n * `budget` (one conserved pool) are mandatory. Driver↔worker is the two-node cyclic instance;\n * \"agent 3 analyzes 1 and 2 and reports to 1\" is ONE edge, not a framework.\n *\n * NOT A SECOND SCHEDULER. `runGraph` is an interpretation layer over what already runs:\n * `supervise()` is the execution core — the same `supervisorAgent`/`driverAgent` machinery,\n * backend-derived worker path (authorized, classified, recursive), conserved-pool budget, and\n * deliverable-gated settlement every\n * supervised run uses. (`runAgentRounds` is deliberately NOT the substrate here.) What the graph\n * layer ADDS is exactly what a bespoke driver loop never\n * had:\n *\n * 1. **Node pinning** — a spawn names a node (`profile.name` = node id) and the node's canonical\n * profile is what runs; a driver cannot smuggle capabilities into a worker it did not define.\n * 2. **Observable edges** — every delegates/analyzes/maps/routes traversal lands in an EDGE LEDGER\n * (`delivered | stripped | empty | unpropagated | failed`, with byte counts), in memory on\n * the result AND as `edge` events in the run journal. The motivating incident: a filter\n * silently replaced 1,700-char steering with 241 chars of boilerplate for three rounds and\n * NO artifact said so — an unobservable edge cannot be trusted and its directive cannot be\n * optimized.\n * 3. **Directives as data** — edge text lives in the prompt registry (`<surface>/v<n>`), so every\n * edge is a versioned optimization target, never prose hardcoded in a builder function.\n * 4. **Per-edge traversal caps** — the cyclic-graph backstop. A delegates edge whose cap is\n * exhausted REFUSES further traversals (fail loud), so a cycle cannot spin the pool dry.\n * 5. **Continuity as data** — a delegates edge may declare `continuity: 'resume'`, so each spawn\n * after the node's first re-attaches to its latest SETTLED session (the spawn context hands\n * the executor seam `resume: { ofWorker, sequence }`; the kernel keeps identity, ordering,\n * ledger truth, and the one conserved pool). Every ledger row states how its hop continued:\n * `'fresh' | 'resume'` for spawns, `'steer'` for mid-run deliveries — fresh respawns, session\n * resumes, and live steers are all plain data, each a ledgered fact.\n * 6. **Fan-out over a run-time list** — a `maps` edge takes the array a JSON pointer selects in a\n * node's settled result and runs one item per element, then hands the ordered results to a\n * join node. The runtime spawns every item and the join when the source settles, so the\n * driver spends no model turn on them; each item is a spawn through the same authorized path,\n * reserving from the same conserved pool, and every expansion, item and join is a ledger row.\n * 7. **Flow graphs** — with `entry` set, no node is a root: Runtime spawns the entries and fires\n * `routes` edges on each settle (`graph-flow.ts`), so a fixed order, a branch, a bounded repair\n * loop and a stop rule are graph data. The root manager is Runtime's own and never calls a\n * model; every entry and route spawn takes the same authorized path a map item takes.\n *\n * ORACLES ARE ENVIRONMENT, NEVER WORKERS. Graders/verifiers must not be spawnable in the graph —\n * a delegates edge to them leaks the rubric. An `analyzes` edge names its analyst in one of two\n * forms: a LENS id from the environment's registry (a pure function over trace evidence), or the\n * id of a graph NODE — a tool-equipped analyst AGENT spawned on each matching settle with the\n * node's pinned profile, whose settle output IS the findings. Either way the oracle doctrine\n * holds: an analyst node can never be a delegates target (refused loudly), so no driver can hand\n * it work, and an id living in both the registry and the nodes is refused as ambiguous.\n *\n * @experimental\n */\n\nimport { resolve } from 'node:path'\nimport { type AgentProfile, canonicalCandidateDigest } from '@tangle-network/agent-interface'\nimport { ConfigError, ValidationError } from '../../errors'\nimport type { AnalystRegistry } from '../../mcp/tools/coordination-analysts'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination-contracts'\nimport type { MapItemFailurePolicy } from '../../mcp/tools/coordination-map-contracts'\nimport type { ContinuityMode } from '../../mcp/tools/coordination-messages'\nimport type {\n GateDecision,\n GateDecisionRecord,\n GateRequest,\n RouteGate,\n RouteWhen,\n} from '../../mcp/tools/coordination-route-contracts'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport { harnessRunsAgent } from '../harness-role'\nimport type { ToolLoopChat } from '../tool-loop'\nimport type { DeliverableSpec } from './completion-gate'\nimport { runtimeFlowBrain } from './flow-brain'\nimport { graphExecutionOptions } from './graph-backend'\nimport {\n createFlowRun,\n flowRootProfile,\n GraphRouteError,\n journaledGateDecider,\n routeFlowOf,\n validateFlowGraph,\n} from './graph-flow'\nimport { createGraphOverlay } from './graph-overlay'\nimport {\n graphRootProfile,\n type RootValidatedGraph,\n type ValidatedGraph,\n validateGraphTopology,\n} from './graph-topology'\nimport { kernelPromptRegistry, type PromptHandle, type PromptRegistry } from './prompt-registry'\nimport { createFileRunContext, createInMemoryRunContext, withRunContext } from './run-context'\nimport { bindGraphCommand, type GraphCommandCheck } from './stored-graph-check'\nimport {\n profileGuidanceComposer,\n type SuperviseOptions,\n supervise,\n superviseWithTestBrain,\n} from './supervise'\nimport type { Budget, NodeId, ResultBlobStore, SpawnJournal, SupervisedResult } from './types'\n\nexport type { MapItemFailurePolicy } from '../../mcp/tools/coordination-map-contracts'\nexport type {\n GateDecision,\n GateRequest,\n JsonScalar,\n RouteGate as GraphGate,\n RouteMatch,\n RouteWhen,\n} from '../../mcp/tools/coordination-route-contracts'\nexport { GraphRouteError } from './graph-flow'\nexport { defaultEdgeTraversalCap } from './graph-topology'\n\n// ── The algebra ────────────────────────────────────────────────────────────────\n\n/** A graph node: an id and a canonical `AgentProfile`. The profile is the ONLY way a node is\n * described — its `prompt.systemPrompt` is the standing role (the 0.117 canonical resolution;\n * never a legacy top-level-only reduction), its tools/mcp/resources are its capabilities. */\nexport interface GraphNode {\n readonly id: NodeId\n readonly profile: AgentProfile\n}\n\nexport type GraphEdge =\n /** Work flows down. The delegation directive is DATA → versionable, sweepable, optimizable.\n * Each spawn of `to` by `from` — and each mid-run steer from `from` to a live `to` worker —\n * is one traversal. */\n | {\n readonly kind: 'delegates'\n readonly from: NodeId\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Cyclic-graph backstop: traversals beyond this REFUSE (fail loud). Default\n * {@link defaultEdgeTraversalCap}. */\n readonly maxTraversals?: number\n /** Default continuity for this edge's SPAWN traversals. `'resume'` makes every spawn after\n * the node's first re-attach to its most recent SETTLED worker: a NEW live worker whose\n * spawn context carries `resume: { ofWorker, sequence }` for the executor seam, spending\n * from the same conserved pool — the node's first spawn is effectively `'fresh'`, and a\n * spawn while a prior worker is still live refuses loudly (steer is the live channel).\n * The driver's per-call `spawn_worker` `continuity` argument overrides either way. Omit =\n * `'fresh'` (today's behavior, byte-identical). Caps count resumes exactly like fresh\n * spawns. */\n readonly continuity?: ContinuityMode\n }\n /** Findings flow anywhere: an analyst over N nodes' settled traces, delivered to ONE node.\n * With a LENS analyst the directive wraps the findings for the recipient; with a NODE analyst\n * the directive is the analyst agent's task and the findings are its settle output. */\n | {\n readonly kind: 'analyzes'\n /** The analyst REFERENCE, in one of two forms: a lens id resolved against\n * `RunGraphOptions.analysts` (environment), or the id of a graph NODE with no delegates\n * edge pointing at it — then each matching settle spawns that node's pinned profile as a\n * tool-equipped analyst WORKER (same spawn machinery, conserved budget, trace join) whose\n * task is this edge's directive plus the settled worker's trace evidence and whose settle\n * output is the findings. An id that is both a node and a registry lens is refused. */\n readonly analyst: string\n readonly over: ReadonlyArray<NodeId>\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Observability cap: traversals beyond this are LEDGERED as exhausted (`unpropagated`).\n * Only delegates caps refuse traversal — they are what close the spawn cycle. */\n readonly maxTraversals?: number\n }\n /**\n * Fan-out over a list that exists only at run time, then one join. When `from` settles `done`,\n * the array at `pointer` in its result is expanded: each element becomes the TASK of one item\n * run, at most `concurrency` at a time, and once every item settled the `join` node runs with\n * `{ map, source, items, results: [{ index, item, result }], failures: [{ index, item, outcome,\n * reason }] }`, results in item order. The runtime spawns the items and the join (`from`'s\n * driver spends no turn on them) through the same authorized spawn path a delegates spawn\n * takes: each item reserves its budget from the one conserved pool and is pinned to the edge's\n * profile, so an item's content can never choose what runs.\n *\n * An item is either the node `to` (its pinned profile plus this edge's directive) or the nested\n * `graph`, started per item exactly as `run_graph` starts a graph. Refusals are loud and\n * ledgered, and the driver is woken with them: a pointer that does not resolve to an array, more\n * elements than `maxItems`, or a `concurrency` the run's worker-slot bound can never honor.\n * `concurrency` otherwise THROTTLES (items wait for a free place); it never refuses an item.\n *\n * An edge rather than a node-level spec, because every kernel invariant a map must keep already\n * attaches to edge traversal: pinning admits only the edge's item and join nodes (the spawn\n * context carries a runtime-authored `map` marker), each item is admitted like a spawn and\n * reserves from the conserved pool, each item settles under its own deliverable check, and each\n * expansion, item and join is a ledger row with its journal twin. Topology stays static; only the\n * traversal count is dynamic, so validation and the one-node-one-profile rule are unchanged.\n */\n | {\n readonly kind: 'maps'\n /** The source node: a delegates target, or the join of another maps edge. Each of its `done`\n * settles expands the map once. */\n readonly from: NodeId\n /** RFC 6901 JSON pointer into `from`'s settled result (`''` is the whole result). */\n readonly pointer: string\n /** The item node, run once per element with the element as its task. Exactly one of `to`\n * and `graph`. Reachable only through this edge: never a delegates target. */\n readonly to?: NodeId\n /** A graph run per element as one subtask, through the `run_graph` path. */\n readonly graph?: GraphTopology\n /** Receives the ordered results once every item settled. Reachable only through this edge. */\n readonly join: NodeId\n /** The item directive, appended to the item node's instructions per traversal. */\n readonly directive: PromptHandle\n /** Lists longer than this are refused before any item runs. */\n readonly maxItems: number\n /** How many items run at once. */\n readonly concurrency: number\n readonly onItemFailure: MapItemFailurePolicy\n /** Each item's budget, merged over the per-worker default as `spawn_worker`'s `budget` is. */\n readonly itemBudget?: Partial<Budget>\n }\n /**\n * A route in a flow graph (one with `entry`): Runtime traverses it when `from` settles, so no\n * root decides the order, the branch, the repair loop or the stop. On each usable settle of\n * `from` its outgoing routes edges are tried in declaration order and the first whose `when`\n * holds fires; an edge without `when` is the default branch and comes last. A node target is\n * spawned with `{ from: { node, result }, evidence: { [id]: latest usable result } }` (a join's\n * target with `{ from: { nodes }, evidence }`, see below) and the directive appended to its pinned instructions; `{ stop }` ends the run with no winner and\n * `GraphResult.stopped`; `{ finish }` makes this settle part of the run's output.\n *\n * A fork lists two or more nodes in `to`: one traversal spawns each of them at once, each under\n * its own key `route:<edge id>#<traversal>:<node>`. A join lists two or more nodes in `from`: it\n * fires once every member has settled usably since it last fired, and the target's task is\n * `{ from: { nodes: <members in declared order> }, evidence }` with each member's latest result\n * in `evidence`, so it does not depend on which member settled last and a resumed run derives the\n * same task. A routes edge that spawns a node with a settled worker in this flow (a back edge)\n * names that node's latest settled worker as the spawn's `successorOf`. A join carries no `when`, and it is the only routes edge\n * leaving each of its members. A route into a node that still has a running worker throws\n * {@link GraphRouteError} with reason `target-live`: converging branches use a join.\n */\n | {\n readonly kind: 'routes'\n readonly from: NodeId | ReadonlyArray<NodeId>\n readonly to:\n | NodeId\n | ReadonlyArray<NodeId>\n | { readonly stop: string }\n | { readonly finish: string }\n readonly directive: PromptHandle\n /** Absent on the default edge and on every join. A match reads `from` unless it names a node\n * in `evidence`. */\n readonly when?: RouteWhen\n /** Nodes whose latest usable result rides the target's task. */\n readonly evidence?: ReadonlyArray<NodeId>\n /** Traversals beyond this are skipped (ledgered `unpropagated`) and matching continues with\n * the next edge. Default {@link defaultEdgeTraversalCap}. Every routes cycle, each subcycle\n * included, must cross an edge that sets it. */\n readonly maxTraversals?: number\n /** `'resume'` re-attaches each spawn of the target to its latest settled session. Omit =\n * `'fresh'`. */\n readonly continuity?: ContinuityMode\n }\n\n/** A topology without the run's own budget and deliverable: the form a `maps` edge runs per item,\n * as `run_graph` runs it. With `entry` it is a flow graph. Inside a maps item, the item value is\n * the task of every entry whose task is the placeholder `{ item: true }`; a down settle inside the item ends\n * that item only, and the maps edge's `onItemFailure` decides the join. */\nexport interface GraphTopology {\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n readonly entry?: AgentGraph['entry']\n /** Refused here: a maps item's graph and a `run_graph` subtask have no `decideGate`. */\n readonly gates?: AgentGraph['gates']\n}\n\nexport interface AgentGraph {\n /** Preserve fully bound literal data when serializing a hydrated graph. */\n readonly triggerBindings?: readonly []\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n /** Termination is mandatory, not optional: the independent completion oracle. */\n readonly deliverable: DeliverableSpec<unknown> & {\n readonly checkRef?: string\n readonly command?: GraphCommandCheck\n readonly when?: RouteWhen\n }\n /** One conserved pool across the whole graph — cycles without conservation never terminate. */\n readonly budget: Budget\n /** Setting it makes this a FLOW graph: Runtime spawns every entry at once, each with its task,\n * and traverses `routes` edges itself. No node is a root and no caller brain runs; the run's\n * output is `{ [node]: latest usable result }` over its terminal nodes and `finish` sources,\n * judged by `deliverable`. A stored route check (`checkRef: 'route'`) may also name a\n * non-terminal node: its condition reads that node's latest delivered output, while the output\n * stays terminal-only. */\n readonly entry?: ReadonlyArray<{ readonly node: NodeId; readonly task: unknown }>\n /** Flow-graph vertices that are not agents: a routes edge into one awaits\n * `RunGraphOptions.decideGate`, and one edge per choice leaves it, matching\n * `{ pointer: '/choice', equals: <choice> }`. A `finish` leaving a gate outputs\n * `{ [gate]: { choice, by } }`. */\n readonly gates?: ReadonlyArray<RouteGate>\n}\n\n// ── The edge ledger ────────────────────────────────────────────────────────────\n\n/** `failed` is a maps item or join that ran and settled without a usable result (down, or\n * rejected by its deliverable check); a traversal that never reached a worker is `unpropagated`. */\nexport type EdgeDeliveryOutcome = 'delivered' | 'stripped' | 'empty' | 'unpropagated' | 'failed'\n\n/** How one ledgered hop CONTINUED: a spawn traversal stamps its effective spawn mode\n * (`'fresh'` | `'resume'`), and every mid-run delivery into an already-live recipient — a\n * driver steer leg and every analyzes delivery (routed steer or driver-destined finding) —\n * stamps `'steer'`. Zero ambiguity: every row carries exactly one of the three. */\nexport type TraversalContinuity = ContinuityMode | 'steer'\n\n/** One recorded edge traversal — the in-memory row; the journal twin is the `edge` SpawnEvent. */\nexport interface EdgeTraversal {\n /** Stable edge id: `delegates:<from>-><to>`, `analyzes:<analyst>:<over…>-><to>`,\n * `maps:<from>-><to | graph>-><join>`, `routes:<from>#<ordinal>-><to | stop:<reason> |\n * finish:<reason>>`, or `routes:entry-><node>` for an entry. */\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes' | 'maps' | 'routes'\n readonly from: string\n readonly to: string\n /** The resolved directive reference (`<surface>/v<n>`). */\n readonly directive: string\n /** 1-based per-edge ordinal. */\n readonly traversal: number\n readonly outcome: EdgeDeliveryOutcome\n /** How this hop continued — see {@link TraversalContinuity}. */\n readonly continuity: TraversalContinuity\n /** Bytes of directive + payload that actually crossed the edge. */\n readonly bytes: number\n readonly reason?: string\n /** The concrete worker node id, once known. A maps expansion names the source worker. */\n readonly workerId?: string\n /** Present on maps rows: the expansion of the source's list, one item by its index, or the\n * join. */\n readonly map?: { readonly phase: 'expand' | 'item' | 'join'; readonly index?: number }\n /** Present on a gate's decision row (`gate:<id>`, `traversal` = visit): who decided, and what. */\n readonly gate?: GateDecisionRecord\n}\n\n/** A delegates edge exhausted its traversal cap and the run produced no winner: the cap, not the\n * task, ended it. Carries the full evidence so failing loud loses nothing. */\nexport class GraphEdgeCapError extends Error {\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly ledger: ReadonlyArray<EdgeTraversal>\n readonly result: SupervisedResult<unknown>\n constructor(\n exhaustedEdges: ReadonlyArray<string>,\n ledger: ReadonlyArray<EdgeTraversal>,\n result: SupervisedResult<unknown>,\n ) {\n super(\n `runGraph: edge traversal cap exhausted on ${exhaustedEdges.join(', ')} and the run ` +\n 'delivered no winner — the cap (the cyclic-graph backstop), not the task, ended this run. ' +\n 'Raise maxTraversals on the edge or fix the cycle; the full edge ledger and the ' +\n 'supervised result ride on this error.',\n )\n this.name = 'GraphEdgeCapError'\n this.exhaustedEdges = exhaustedEdges\n this.ledger = ledger\n this.result = result\n }\n}\n\n// ── Options / result ───────────────────────────────────────────────────────────\n\n/**\n * Every `SuperviseOptions` key, partitioned by what `runGraph` does with it.\n *\n * `runGraph` starts one `supervise()` run, so every option that run honors is a graph option too\n * unless the graph itself owns the value. This used to be an opt-in list written by hand, and the\n * hand lost: 25 of 49 keys never reached `supervise()` from a graph, including `childSettleGraceMs`\n * (a root-driver failure tore down children that had ALREADY computed the deliverable) and\n * `driverRetry` (agent-runtime#963). Each absence was discovered by losing a run.\n *\n * The four lists below must cover `keyof SuperviseOptions` exactly. `everySuperviseOptionIsClassified`\n * below fails to COMPILE, naming the offender, when a key belongs to none of them — so the next\n * option added to `supervise()` cannot go missing here silently. It has to be classified, and\n * classifying it as forwarded is one word.\n */\n\n/** The graph derives these from the `AgentGraph` itself; a caller value would be overwritten. */\nconst GRAPH_OWNED_SUPERVISE_OPTIONS = [\n 'rootDriverFromBackend',\n 'resolveSpawnProfile',\n 'budget',\n 'deliverable',\n 'makeWorkerAgent',\n 'onCoordinationEvent',\n 'analyzeOnSettle',\n 'mapOnSettle',\n // A flow graph's entries and routes edges; its runtime-owned root runs them.\n 'routeFlow',\n 'continuityByProfile',\n // A graph pins every node and its delegation edges; a node never gains spawn rights it lacks.\n 'inheritSpawnRights',\n] as const\n\n/** Caller-facing on `RunGraphOptions`, but the graph wraps or defaults the value before it goes in:\n * `hooks` composes with the graph's own spawn-binding hook, `authorizeMessage` is wrapped so a\n * narrowed instruction ledgers `stripped`, `authorizeSpawn` runs AFTER the graph has pinned the\n * node (so a product sees the canonical profile, never the driver's stub), `makeLeafAgent` is the\n * caller's leaf override slotted under the graph's pinning, `analysts` rides only with analyze\n * routes, and `journal`/`blobs`/`runId` get graph defaults. */\nconst GRAPH_TRANSFORMED_SUPERVISE_OPTIONS = [\n 'hooks',\n 'authorizeMessage',\n 'authorizeSpawn',\n 'makeLeafAgent',\n 'analysts',\n 'journal',\n 'blobs',\n 'runId',\n // Replays a journaled decision before asking the caller.\n 'decideGate',\n] as const\n\n/** Not reachable from a graph, with the reason. `registry` is a NAME COLLISION, not a policy:\n * `RunGraphOptions.registry` is the directive `PromptRegistry` and `SuperviseOptions.registry` is\n * the `SuperviseRegistry` name→value table. Two different types under one name; the graph's wins.\n * Giving the supervise one a graph channel means renaming a public option, so it is recorded here\n * rather than silently dropped. */\nconst GRAPH_REFUSED_SUPERVISE_OPTIONS = ['registry'] as const\n\n/**\n * Forwarded to the root `supervise()` VERBATIM. Everything not owned, transformed, or refused\n * above belongs here — the default is \"a graph honors it\", not \"someone remembered to add it\".\n */\nconst GRAPH_FORWARDED_SUPERVISE_OPTIONS = [\n 'parking',\n 'backend',\n // Forwarded: composes guidance into the root and into profiles a manager authors. The graph also\n // composes each PINNED node profile, because pinning replaces the composed `{ name }` stub.\n 'profileGuidance',\n // Forwarded, not graph-owned: a graph pins WHICH nodes run, never who answers a question one of\n // them raises. Without it a graph run's `ask_parent` would always report `no-parent` even when\n // the caller wired an inbox.\n 'escalateQuestion',\n 'rootHandle',\n 'signal',\n 'execution',\n 'resolveDeliverable',\n 'coordination',\n 'peerMail',\n 'peerAudit',\n 'traceTools',\n 'driverBackend',\n 'profileSecurity',\n 'authorizeSpawn',\n 'router',\n 'driveHarness',\n 'selectSeat',\n 'driverRetry',\n 'onDriverAttempt',\n 'workerRetry',\n 'onWorkerRetry',\n 'continuation',\n 'childSettleGraceMs',\n 'teardownConfirmMs',\n 'retainedAtSettlement',\n 'resolveDriveHarness',\n 'driveHarnessMaterialization',\n 'resolveSupervisorTools',\n 'extraTools',\n 'executeExtraTool',\n 'recoverExecutor',\n 'perWorker',\n 'reservationPolicy',\n 'deadlineCheckIn',\n 'budgetStopHoldMs',\n 'workerSlots',\n 'watchWorkers',\n 'stallAfterMs',\n 'wake',\n 'runDir',\n 'resume',\n 'segment',\n 'runContext',\n 'steerDir',\n 'stopRule',\n 'onProgressStop',\n 'maxDepth',\n 'maxTurns',\n 'compaction',\n 'now',\n 'allowedModels',\n 'finalizer',\n 'otel',\n // Forwarded: the registry a manager's `run_graph` resolves stored graphs against. A node of this\n // graph cannot start another graph (pinning refuses it), so it matters to no node here.\n 'graphRegistry',\n] as const\n\ntype ClassifiedSuperviseOption =\n | (typeof GRAPH_OWNED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_TRANSFORMED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_REFUSED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]\n\n/**\n * Every key `RunGraphOptions` accepts, as data: the forwarded and transformed `SuperviseOptions`\n * keys, the name-colliding `registry`, and the graph's own `brain`. `GRAPH_OWNED_SUPERVISE_OPTIONS`\n * is deliberately absent — a caller value for one of those is overwritten by the graph, so it is\n * refused by name rather than discarded.\n *\n * The assignment below fails to COMPILE, naming the key, when `RunGraphOptions` declares something\n * this list does not carry.\n */\nconst runGraphOptionKeys = [\n ...GRAPH_FORWARDED_SUPERVISE_OPTIONS,\n ...GRAPH_TRANSFORMED_SUPERVISE_OPTIONS,\n ...GRAPH_REFUSED_SUPERVISE_OPTIONS,\n 'brain',\n] as const\n\ntype UnlistedRunGraphOption = Exclude<keyof RunGraphOptions, (typeof runGraphOptionKeys)[number]>\nconst everyRunGraphOptionIsListed: UnlistedRunGraphOption extends never\n ? true\n : UnlistedRunGraphOption = true\nvoid everyRunGraphOptionIsListed\n\nconst runGraphOptionKeySet: ReadonlySet<string> = new Set<string>(runGraphOptionKeys)\nconst graphOwnedOptionKeySet: ReadonlySet<string> = new Set<string>(GRAPH_OWNED_SUPERVISE_OPTIONS)\n\n/**\n * Refuse an option key the graph would not read, naming it and saying which kind it is.\n *\n * A graph-owned key is the sharper case: it type-checks against a widened `SuperviseOptions`\n * value, the graph derives its own value and overwrites the caller's, the run succeeds, and the\n * capability the caller asked for is not there. The rename of the leaf seam from `makeWorkerAgent`\n * to `makeLeafAgent` is the shape of the failure — the old name stayed a valid `SuperviseOptions`\n * key AND a graph-owned one, so a caller that kept passing it got a run with no leaf override and\n * no complaint.\n */\nfunction assertRunGraphOptionKeys(opts: RunGraphOptions): void {\n const graphOwned: string[] = []\n const unknown: string[] = []\n for (const key of Object.keys(opts)) {\n if (runGraphOptionKeySet.has(key)) continue\n if (graphOwnedOptionKeySet.has(key)) graphOwned.push(key)\n else unknown.push(key)\n }\n if (graphOwned.length > 0) {\n throw new ConfigError(\n `runGraph: ${graphOwned.sort().join(', ')} — the graph derives this from the AgentGraph ` +\n 'itself, so a caller value is overwritten and the capability it asks for would silently ' +\n 'be absent',\n )\n }\n if (unknown.length > 0) {\n throw new ConfigError(\n `runGraph: unknown option ${unknown.sort().join(', ')} — no reader consults that name, so ` +\n 'the value would be discarded and the capability it asks for would silently be absent',\n )\n }\n}\n\n/** A `SuperviseOptions` key in none of the four lists makes this assignment fail, and the compiler\n * error names the key. Classify it — `GRAPH_FORWARDED_SUPERVISE_OPTIONS` is usually the answer. */\ntype UnclassifiedSuperviseOption = Exclude<keyof SuperviseOptions, ClassifiedSuperviseOption>\nconst everySuperviseOptionIsClassified: UnclassifiedSuperviseOption extends never\n ? true\n : UnclassifiedSuperviseOption = true\nvoid everySuperviseOptionIsClassified\n\n/** `backend` and `driverBackend` keep graph-specific documentation below.\n *\n * Do not inherit and redeclare them through an indexed access type.\n * TypeScript 7 correctly treats `SuperviseOptions['backend']` as including `undefined`, which makes\n * that redeclaration wider than the exact optional property inherited from `SuperviseOptions`.\n */\ntype GraphInheritedSuperviseOption = Exclude<\n (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number],\n 'backend' | 'driverBackend'\n>\n\n/** Copy every forwarded option the caller actually set. Absent stays absent: `supervise()` and the\n * graph must not disagree about what \"unset\" means. */\nfunction forwardedSuperviseOptions(\n opts: RunGraphOptions,\n): Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\n const forwarded: Record<string, unknown> = {}\n for (const key of GRAPH_FORWARDED_SUPERVISE_OPTIONS) {\n const value = (opts as Record<string, unknown>)[key]\n if (value !== undefined) forwarded[key] = value\n }\n return forwarded as Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]>\n}\n\n/**\n * Options for one `runGraph` run.\n *\n * Extends every forwarded `SuperviseOptions` key, so a graph honors what a `supervise()` run\n * honors WITHOUT anyone restating it here. Only the graph-specific members and the ones whose\n * graph semantics differ are declared below; everything else inherits its type AND its\n * documentation from `SuperviseOptions`, which is the one owner of both.\n */\nexport interface RunGraphOptions extends Pick<SuperviseOptions, GraphInheritedSuperviseOption> {\n /** WHERE worker nodes run — the executor backend. Provide this OR `makeLeafAgent`. Forwarded to\n * `supervise()`, which derives every authorized leaf from it. A node that declares\n * `agent_runtime_coordination_spawn_worker` becomes a nested supervisor instead, whose own\n * leaves are derived the same way. */\n readonly backend?: Exclude<SuperviseOptions['backend'], undefined>\n /** WHERE the ROOT node's harness brain runs — forwarded to `supervise()` verbatim (see\n * `SuperviseOptions.driverBackend`). Needed when the root node's profile declares an external\n * harness (`codex`, `claude-code`, `opencode`): that root is driven by the harness, not by the\n * router brain, and automatic execution supports a local `bridge`. Unlike `supervise()`, this\n * does NOT default to `backend`: a graph's `backend` places WORKER nodes, so the root driver\n * is selected only by this field. Omit = no harness driver, which is correct for a root whose\n * `profile.harness` is omitted or `cli-base` (that root runs on the router brain). */\n readonly driverBackend?: Exclude<SuperviseOptions['driverBackend'], undefined>\n /** Leaf-execution override (offline tests / advanced). `runGraph` still owns node pinning,\n * directive delivery, and the edge ledger AROUND this seam — only the leaf `act` is yours.\n * Slots INSIDE the kernel's authorized path (`SuperviseOptions.makeLeafAgent`), so a node that\n * declares the spawn tool still becomes a nested supervisor even under an offline leaf. */\n readonly makeLeafAgent?: MakeWorkerAgent\n /** The ROOT driver's inference seam — a caller-owned `ToolLoopChat` that makes every root\n * model call. Use it when the root's decisions must be caller-owned orchestration (a\n * deterministic conversation driver, a persona loop with its own LLM calls) rather than a\n * router-derived model call. The graph machinery around the seam is unchanged: node pinning,\n * directive delivery, the edge ledger, and the journal twin all run the same shipped path,\n * and the root profile keeps prompt control (`prompt-control-execution` materialization —\n * `systemPrompt`/`instructions` still apply). What moves to the caller with the brain:\n * model selection and provider-identity validation (`expectedModel` cannot be enforced on a\n * call the runtime did not place) and per-turn usage reporting (a brain that reports no\n * usage meters nothing into the pool). Omit = the router brain derived from the root\n * profile — the unchanged default. Mutually exclusive with `driverBackend`, and refused\n * when the root profile declares an external harness (that root is driven BY the harness). */\n readonly brain?: ToolLoopChat\n /** Caller-side runtime hooks (telemetry, policy, product extensions). Composed AFTER the\n * graph's own spawn-binding hook on the SAME event stream — the graph never swallows the\n * seam supervise() exposes. */\n readonly hooks?: RuntimeHooks\n /** The analyst lens registry `analyzes` edges resolve against. ENVIRONMENT — needed only for\n * lens analysts; an analyzes edge naming a graph NODE as its analyst needs no registry. */\n readonly analysts?: AnalystRegistry\n /** Answers a flow gate while the process holds the run; the wait counts against its deadline.\n * ENVIRONMENT, like `analysts`; required when the graph declares gates. */\n readonly decideGate?: (request: GateRequest) => Promise<GateDecision>\n /** Directive registry. Default: the seeded kernel registry (`kernelPromptRegistry()`).\n *\n * NOT `SuperviseOptions.registry`, which is the `SuperviseRegistry` name→value table for\n * code-valued options. The two share a name and nothing else, and this one wins here — see\n * `GRAPH_REFUSED_SUPERVISE_OPTIONS`. */\n readonly registry?: PromptRegistry\n /** The run journal the edge ledger and every spawn/settle ride. Default: in-memory. */\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly runId?: string\n /** Product authority over every steer/answer instruction (the filter seam). `runGraph` observes\n * what it CHANGES: a narrowed instruction ledgers its steer traversal as `stripped`. */\n readonly authorizeMessage?: SuperviseOptions['authorizeMessage']\n}\n\nexport interface GraphResult<Out = unknown> {\n readonly result: SupervisedResult<Out>\n /** Every edge traversal, in occurrence order — the observable-edge contract. */\n readonly ledger: ReadonlyArray<EdgeTraversal>\n /** Edge ids whose traversal cap was hit — analyzes exhaustion included (observable here, never\n * a refusal). A DELEGATES cap paired with a `no-winner` result THROWS\n * ({@link GraphEdgeCapError}) instead of returning: only delegates caps refuse spawns, so only\n * they can have ended the run. A LIFECYCLE no-winner (`aborted` / `budget-exhausted`) returns\n * normally even with an exhausted delegates cap — the abort or the pool, not the cap, ended\n * that run, and the exhaustion stays observable here. */\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly runId: string\n /** Why a flow graph ended early: a `stop` edge fired (`edge` names it), or a flow node settled\n * down (no `edge`; `reason` is `down: <worker reason>`) or, where a route was needed, without a\n * usable result (no `edge`; `reason` is `unusable: <why>`). Live flow workers are aborted. */\n readonly stopped?: {\n readonly code?: string\n readonly edge?: string\n readonly at: NodeId\n readonly workerId: string\n readonly reason: string\n }\n}\n\n/** `RunGraphOptions` with the brain REQUIRED — the shape the `/testing` entry's\n * `runGraphWithTestBrain` keeps accepting now that `brain` is a production option. */\nexport interface RunGraphTestOptions extends RunGraphOptions {\n readonly brain: ToolLoopChat\n}\n\n// ── Validation ─────────────────────────────────────────────────────────────────\n\n/** Validate the graph and resolve every directive BEFORE any compute is spent — an invalid\n * topology or an unknown directive is a configuration fault, never a mid-run surprise. */\nfunction validateGraph(\n graph: AgentGraph,\n registry: PromptRegistry,\n analysts: AnalystRegistry | undefined,\n): ValidatedGraph {\n if (graph.entry === undefined) {\n if (!Array.isArray(graph.nodes) || graph.nodes.length === 0) {\n throw new ValidationError('runGraph: graph.nodes must be a non-empty array')\n }\n if (!Array.isArray(graph.edges) || graph.edges.length === 0) {\n throw new ValidationError('runGraph: graph.edges must be a non-empty array')\n }\n }\n if (typeof graph.deliverable?.check !== 'function') {\n throw new ValidationError('runGraph: graph.deliverable is mandatory (termination oracle)')\n }\n if (typeof graph.budget !== 'object' || graph.budget === null) {\n throw new ValidationError('runGraph: graph.budget is mandatory (the conserved pool)')\n }\n if (graph.entry !== undefined) return validateFlowGraph(graph, registry, analysts)\n if (graph.gates !== undefined)\n throw new ValidationError('runGraph: graph.gates needs graph.entry')\n return validateGraphTopology(graph.nodes, graph.edges, registry, analysts)\n}\n\n// ── The runner ─────────────────────────────────────────────────────────────────\n\n/**\n * Execute an {@link AgentGraph}. A flow graph (`entry` set) runs from its entries and routes edges\n * under a runtime-owned root that places no model call. Otherwise the root node becomes the\n * supervisor (`supervise()` — the execution core), each worker node is spawnable BY NODE ID\n * (`spawn_worker` with `profile: { name: '<node id>' }`; the node's canonical profile is pinned by\n * the graph), each\n * delegates directive is appended to the worker profile's `prompt.instructions` per traversal,\n * and each analyzes edge becomes an analyst-on-settle route with a real DESTINATION. Every\n * traversal is ledgered and journaled.\n */\nexport function runGraph(graph: AgentGraph, opts: RunGraphOptions): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = graphExecutionOptions(opts)\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/** Alias for graph tests written before `RunGraphOptions.brain` was production. The production\n * entry accepts the same shape; this wrapper only keeps the `/testing` import path working. */\nexport function runGraphWithTestBrain(\n graph: AgentGraph,\n opts: RunGraphTestOptions,\n): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/**\n * The graph supervise run, as its own entry: the engine's `run-graph` preset node executes exactly\n * this, so the preset and `runGraph` are the same code path by construction (agent-runtime#982).\n */\n/**\n * Every refusal a graph earns before any compute, in one place: the authoring contract. `runGraph`\n * calls it FIRST so a malformed graph throws synchronously, exactly as it did before the engine\n * preset (agent-runtime#982) moved execution behind a promise.\n */\nexport function assertRunGraphAuthoring(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): ReturnType<typeof validateGraph> {\n assertRunGraphOptionKeys(opts)\n const registry = opts.registry ?? kernelPromptRegistry()\n const validated = validateGraph(graph, registry, opts.analysts)\n const requireLeaves = (): void => {\n if (!opts.backend && !opts.makeLeafAgent) {\n throw new ValidationError(\n 'runGraph: provide opts.backend (where nodes run) or opts.makeLeafAgent',\n )\n }\n }\n if (validated.flow !== undefined) {\n // A flow's root is Runtime's own: nothing a caller sets for a root manager has a reader.\n const rootOptions = [\n ...(brain ? ['brain'] : []),\n ...(['driverBackend', 'finalizer', 'maxTurns', 'compaction'] as const).filter(\n (key) => opts[key] !== undefined,\n ),\n ]\n if (rootOptions.length > 0) {\n throw new ValidationError(\n `runGraph: ${rootOptions.join(', ')} with graph.entry — a flow graph has no root ` +\n 'manager: Runtime spawns its entries and traverses its routes edges, and the graph ' +\n \"owns the run's output\",\n )\n }\n if ((graph.gates?.length ?? 0) > 0 && opts.decideGate === undefined) {\n throw new ValidationError('runGraph: graph.gates needs opts.decideGate to answer them')\n }\n requireLeaves()\n return validated\n }\n const { root } = validated as RootValidatedGraph\n // A caller brain and a harness driver are two answers to WHO makes the root's calls: refuse the\n // contradiction before any compute, and refuse a harness-driven root outright — the harness IS\n // that root's brain, so a supplied one would be silently ignored downstream.\n if (brain && opts.driverBackend) {\n throw new ValidationError(\n 'runGraph: brain and driverBackend are mutually exclusive — a caller brain makes the root model calls, a driverBackend places a harness that makes its own',\n )\n }\n if (brain && harnessRunsAgent(root.profile.harness)) {\n throw new ValidationError(\n `runGraph: root node '${root.id}' declares harness '${root.profile.harness}', so the harness drives it — a caller brain applies only to a router-brained root (profile.harness omitted or 'cli-base')`,\n )\n }\n requireLeaves()\n return validated\n}\n\nexport function superviseAgentGraph(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): Promise<GraphResult> {\n if (graph.deliverable.command !== undefined) {\n const bound = bindGraphCommand(graph, opts)\n return superviseAgentGraph(bound.graph, bound.options, brain)\n }\n const registry = opts.registry ?? kernelPromptRegistry()\n if (opts.runContext?.acquire !== undefined) {\n return withRunContext(opts.runContext, opts.signal, (runContext, signal) =>\n superviseAgentGraph(\n graph,\n {\n ...opts,\n runContext,\n ...(signal === undefined ? {} : { signal }),\n },\n brain,\n ),\n )\n }\n const validated = assertRunGraphAuthoring(graph, opts, brain)\n const context =\n opts.runContext ??\n (opts.runDir === undefined\n ? createInMemoryRunContext()\n : createFileRunContext(resolve(opts.runDir)))\n const journal = opts.journal ?? context.journal\n const blobs = opts.blobs ?? context.blobs\n const runId =\n opts.runId ??\n opts.runContext?.runId ??\n `graph-${canonicalCandidateDigest(graph.nodes.map((n) => n.id)).slice('sha256:'.length, 'sha256:'.length + 12)}`\n const now = opts.now ?? Date.now\n\n // The graph layer: node pinning, analyst routes, continuity defaults and the edge ledger. A\n // `run_graph` subtask builds the same overlay around its nested manager.\n // `profileGuidance` composes the profile a manager authors, but a graph then swaps that\n // `{ name }` stub for the pinned node profile. Compose the pinned profile too, so every node\n // that runs carries its harness and model guidance. Composition is idempotent.\n const guidance = profileGuidanceComposer(opts.profileGuidance)\n const overlay = createGraphOverlay(validated, {\n registry,\n journal,\n runId,\n now,\n ...(guidance ? { guidance } : {}),\n ...(opts.authorizeSpawn ? { authorizeSpawn: opts.authorizeSpawn } : {}),\n })\n // A flow graph: Runtime schedules its nodes, and its root manager is Runtime's own.\n const flow = validated.flow === undefined ? undefined : createFlowRun(overlay.nodeOfWorker)\n // Always present: the kernel refuses steer/answer whenever spawn authorization is on (the\n // graph's pinning IS spawn authorization), so a graph with no caller filter passes instructions\n // through unchanged rather than losing its steer channel. Only a caller filter can strip.\n const callerAuthorizeMessage = opts.authorizeMessage\n const authorizeMessage = overlay.observeMessages<\n Parameters<NonNullable<SuperviseOptions['authorizeMessage']>>[0]\n >((input) =>\n callerAuthorizeMessage ? callerAuthorizeMessage(input) : { instruction: input.instruction },\n )\n\n // ── Spawn-hook: bind ledger rows to concrete worker ids, then journal them ──\n const graphHooks: RuntimeHooks = {\n onEvent: (event) => {\n if (event.target !== 'agent.spawn' || event.phase !== 'after') return\n const payload = event.payload as { childId?: unknown; assignmentId?: unknown } | undefined\n if (typeof payload?.childId !== 'string' || typeof payload.assignmentId !== 'string') return\n return overlay.bindSpawn(event.parentId, payload.assignmentId, payload.childId)\n },\n }\n const hooks = composeRuntimeHooks(graphHooks, opts.hooks)\n const rootProfile =\n flow === undefined\n ? graphRootProfile(validated as RootValidatedGraph, registry)\n : flowRootProfile\n const rootBrain = flow === undefined ? brain : runtimeFlowBrain()\n const task =\n flow === undefined\n ? (graph.deliverable.describe ??\n `Deliver the graph's deliverable by driving your worker nodes (root: '${(validated as RootValidatedGraph).root.id}').`)\n : (graph.deliverable.describe ?? 'Runtime runs this flow graph from its entries.')\n\n // Every configuration fault above throws SYNCHRONOUSLY (matching `supervise()`'s own\n // contract); only the run itself is asynchronous.\n const start = async (): Promise<GraphResult> => {\n const superviseOptions = {\n // The backend also drives seat-bearing flow nodes, which use the managed driver lifecycle.\n // A flow's root keeps Runtime's deterministic brain; deriving its child driver adds no root\n // inference. Rooted graphs keep driverBackend explicit rather than inheriting backend.\n ...forwardedSuperviseOptions(opts),\n rootDriverFromBackend: flow !== undefined,\n // Graph-owned values come after the spread: the graph, not the caller, decides these.\n budget: graph.budget,\n deliverable: flow?.routeCheck(graph.deliverable) ?? graph.deliverable,\n authorizeSpawn: overlay.authorizeSpawn,\n resolveSpawnProfile: overlay.resolveSpawnProfile,\n inheritSpawnRights: false,\n ...(opts.makeLeafAgent ? { makeLeafAgent: opts.makeLeafAgent } : {}),\n journal,\n blobs,\n runId,\n hooks,\n onCoordinationEvent: async (\n context: { readonly depth: number },\n _eventId: unknown,\n record: { readonly event: Parameters<typeof overlay.onCoordinationEvent>[0] },\n ) => {\n // A route event belongs to the flow of the manager that published it: a flow inside a\n // maps item or a run_graph subtask ledgers and concludes its own.\n if (record.event.type === 'route' && context.depth !== 0) return\n overlay.onCoordinationEvent(record.event)\n flow?.observe(record.event)\n },\n // Lens routes resolve against the registry; agent routes carry their own analyst profile,\n // so a graph whose only analysts are nodes needs no registry at all.\n ...(overlay.routes.length > 0\n ? {\n analyzeOnSettle: overlay.routes,\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n }\n : {}),\n ...(overlay.maps.length > 0 ? { mapOnSettle: overlay.maps } : {}),\n ...(Object.keys(overlay.continuityByProfile).length > 0\n ? { continuityByProfile: overlay.continuityByProfile }\n : {}),\n // A flow root's wake batches nothing for a decision, so it ends its turn on the first event.\n ...(flow === undefined\n ? {}\n : {\n routeFlow: routeFlowOf(validated),\n ...(opts.decideGate && {\n decideGate: journaledGateDecider(opts.decideGate, journal, runId),\n }),\n finalizer: flow.finalizer,\n wake: { debounceMs: 0, ...opts.wake },\n }),\n authorizeMessage,\n } satisfies SuperviseOptions\n // The flow root reaches supervise through the same brain seam a caller brain takes.\n const supervised =\n rootBrain === undefined\n ? await supervise(rootProfile, task, superviseOptions)\n : await superviseWithTestBrain(rootProfile, task, { ...superviseOptions, brain: rootBrain })\n\n const { ledger, exhaustedEdges, exhaustedDelegates } = await overlay.settle()\n const concluded = flow?.conclude(supervised)\n if (concluded?.kind === 'unrouted') {\n throw new GraphRouteError(concluded.unrouted, ledger, supervised)\n }\n const result = concluded?.result ?? supervised\n const stopped = concluded?.stopped\n // A LIFECYCLE ending (caller abort, exhausted budget, deadline) is its own complete explanation: the\n // cap did not end that run even when it was exhausted along the way, and blaming it would\n // misattribute the ending (and turn a caller-initiated abort into a throw). The exhaustion\n // stays observable in `exhaustedEdges` either way.\n const lifecycleEnded =\n result.kind === 'no-winner' &&\n (result.reason === 'aborted' ||\n result.reason === 'cancelled' ||\n result.reason === 'budget-exhausted' ||\n result.reason === 'deadline')\n if (result.kind !== 'winner' && !lifecycleEnded && exhaustedDelegates.length > 0) {\n // Fail LOUD: the backstop, not the task, ended this run. The evidence rides on the error.\n // Only DELEGATES caps refuse spawns, so only they can be the cause named here.\n throw new GraphEdgeCapError(exhaustedDelegates, ledger, result)\n }\n return { result, ledger, exhaustedEdges, runId, ...(stopped ? { stopped } : {}) }\n }\n\n return start()\n}\n"],"mappings":";;;;;;;;;;;;;AAIA,SAAgB,sBAAsB,SAA2C;CAC/E,IAAI,QAAQ,eAAe,OAAO;CAClC,MAAM,UAAU,QAAQ;CACxB,IAAI,SACF,OAAO,QAAQ,YAAY,YAAY,QAAQ,YAAY,aACvD;EAAE,GAAG;EAAS,SAAS;GAAE,GAAG;GAAS,cAAc;EAAO;CAAE,IAC5D;CACN,MAAM,YAAY,QAAQ,IAAI;CAC9B,MAAM,eAAe,QAAQ,IAAI,iBAAiB,QAAQ,IAAI;CAC9D,IAAI,CAAC,aAAa,CAAC,cACjB,MAAM,IAAI,gBACR,qJACF;CACF,OAAO;EACL,GAAG;EACH,SAAS;GACP,SAAS;GACT;GACA;GACA,KAAK,QAAQ,IAAI;GACjB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,aAAa,GAC3B,MAAM,IAAI,gBACR,oEACF;GACF,MAAM,wBAAwB,eAAe;IAAE,GAAG;IAAS,KAAK,WAAW,OAAO;GAAE,CAAC;EACvF,CAAC;EACD,OAAO,QAAQ;CACjB;CACA,OAAO;EACL,OAAO;GACL,GAAG;GACH,aAAa;IACX,GAAG;IACH,QAAQ,KAAK,YACX,YAAY,KAAA,IAAY,WAAW,GAAG,IAAI,UAAU,KAAK,OAAO;GACpE;EACF;EACA;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC0HA,IAAa,oBAAb,cAAuC,MAAM;CAC3C;CACA;CACA;CACA,YACE,gBACA,QACA,QACA;EACA,MACE,6CAA6C,eAAe,KAAK,IAAI,EAAE,2NAIzE;EACA,KAAK,OAAO;EACZ,KAAK,iBAAiB;EACtB,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;AACF;;;;;;;;;;;;;;;;AAoBA,MAAM,gCAAgC;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CAEA;AACF;;;;;;;AAQA,MAAM,sCAAsC;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;AACF;;;;;;AAOA,MAAM,kCAAkC,CAAC,UAAU;;;;;AAMnD,MAAM,oCAAoC;CACxC;CACA;CAGA;CAIA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;AACF;;;;;;;;;;AAiBA,MAAM,qBAAqB;CACzB,GAAG;CACH,GAAG;CACH,GAAG;CACH;AACF;AAQA,MAAM,uBAA4C,IAAI,IAAY,kBAAkB;AACpF,MAAM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CAAC,SAAS,IAClD,EAAE,qBAAqB,QAAQ,oBAAoB,IACnD,CAAC;GAEL,GAAI,SAAS,KAAA,IACT,CAAC,IACD;IACE,WAAW,YAAY,SAAS;IAChC,GAAI,KAAK,cAAc,EACrB,YAAY,qBAAqB,KAAK,YAAY,SAAS,KAAK,EAClE;IACA,WAAW,KAAK;IAChB,MAAM;KAAE,YAAY;KAAG,GAAG,KAAK;IAAK;GACtC;GACJ;EACF;EAEA,MAAM,aACJ,cAAc,KAAA,IACV,MAAM,UAAU,aAAa,MAAM,gBAAgB,IACnD,MAAM,uBAAuB,aAAa,MAAM;GAAE,GAAG;GAAkB,OAAO;EAAU,CAAC;EAE/F,MAAM,EAAE,QAAQ,gBAAgB,uBAAuB,MAAM,QAAQ,OAAO;EAC5E,MAAM,YAAY,MAAM,SAAS,UAAU;EAC3C,IAAI,WAAW,SAAS,YACtB,MAAM,IAAI,gBAAgB,UAAU,UAAU,QAAQ,UAAU;EAElE,MAAM,SAAS,WAAW,UAAU;EACpC,MAAM,UAAU,WAAW;EAK3B,MAAM,iBACJ,OAAO,SAAS,gBACf,OAAO,WAAW,aACjB,OAAO,WAAW,eAClB,OAAO,WAAW,sBAClB,OAAO,WAAW;EACtB,IAAI,OAAO,SAAS,YAAY,CAAC,kBAAkB,mBAAmB,SAAS,GAG7E,MAAM,IAAI,kBAAkB,oBAAoB,QAAQ,MAAM;EAEhE,OAAO;GAAE;GAAQ;GAAQ;GAAgB;GAAO,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAAG;CAClF;CAEA,OAAO,MAAM;AACf"}
@@ -1,13 +1,13 @@
1
- import { _r as runAbortable, gr as linkAbort } from "./scope-BeI3tmVX.js";
1
+ import { _r as runAbortable, gr as linkAbort } from "./scope-CwhYLg6s.js";
2
2
  import { i as ConfigError } from "./errors-AzSuGI23.js";
3
- import { F as collectAgentTurn, I as streamAgentTurn } from "./structural-rollout-DHdmB9MR.js";
4
- import { L as immutableCandidateValue, N as canonicalCandidateDigest$1, St as armDeadlineTimer, z as sha256Bytes$1 } from "./workspace-streams-BSEkDu3H.js";
3
+ import { F as collectAgentTurn, I as streamAgentTurn } from "./structural-rollout-Dk0NlRpZ.js";
4
+ import { L as immutableCandidateValue, N as canonicalCandidateDigest$1, St as armDeadlineTimer, z as sha256Bytes$1 } from "./workspace-streams-COSTjQLW.js";
5
5
  import { d as detachedSnapshot, l as sha256 } from "./jsonl-file-BBP9Dz9w.js";
6
- import { C as createExecutor, Ut as terminateProcessTreeAndConfirm, zt as runSettledCommand } from "./supervisor-REUnT7iX.js";
6
+ import { C as createExecutor, Ut as terminateProcessTreeAndConfirm, zt as runSettledCommand } from "./supervisor-CORJv7-r.js";
7
7
  import { a as concreteProfileModel, t as assertExecutableAgentProfile } from "./model-policy-C-RGAUW4.js";
8
8
  import { i as syncDurableDirectory, r as publishExclusiveDurableFile } from "./durable-file-DstVeHcj.js";
9
- import { C as serializeRolloutPolicy, S as normalizeRolloutPolicy, w as structuralRolloutPolicyFromProfile, x as applyRolloutPolicyToProfile } from "./activation-BE0duxMf.js";
10
- import { a as reconcileInterruptedSearchCalls, b as improveSearchCost, c as searchExecutor, d as taggedLedger, i as isSearchEnvironmentFault, n as assertSearchLanes, s as searchCallTags, v as decideClosedSearch } from "./search-executor-C-E-umcI.js";
9
+ import { C as serializeRolloutPolicy, S as normalizeRolloutPolicy, w as structuralRolloutPolicyFromProfile, x as applyRolloutPolicyToProfile } from "./activation-DJsJdvb7.js";
10
+ import { a as reconcileInterruptedSearchCalls, b as improveSearchCost, c as searchExecutor, d as taggedLedger, i as isSearchEnvironmentFault, n as assertSearchLanes, s as searchCallTags, v as decideClosedSearch } from "./search-executor-5d-avuUt.js";
11
11
  import { agentProfileEnvironmentSchema, agentProfileSchema, agentProfileTrainingSchema, agentTrainingDatasetIdentitySchema, agentTrainingParametersSchema, agentTrainingReceiptSchema, agentTrainingTaskKey, agentTrainingTaskSchema, applyAgentProfileDiff, canonicalAgentProfileDigest, canonicalCandidateBytes, diffAgentProfiles, sha256DigestSchema, snapshotAgentProfile, trainedModelIdForArtifact } from "@tangle-network/agent-interface";
12
12
  import { canonicalJson, makeProposalFinding } from "@tangle-network/agent-eval";
13
13
  import { redact } from "@tangle-network/agent-eval/traces";
@@ -3034,4 +3034,4 @@ async function improve(profileOrCode, opts) {
3034
3034
  }
3035
3035
  export { assertProfileTrainingIsHeldOut as a, withMethodRuntimeControls as c, commandVerifier as d, addRuntimeUsage as f, assertCandidateValidator as i, rethrowAfterCleanup as l, isUsageAmount as m, createCommandProfileTrainer as n, parseExecutionRef as o, createRuntimeUsageTotals as p, searchMethod as r, privateValuePaths as s, improve as t, agenticGenerator as u };
3036
3036
 
3037
- //# sourceMappingURL=improve-BZdFdcUC.js.map
3037
+ //# sourceMappingURL=improve-CMSrJ22U.js.map