@tangle-network/agent-runtime 0.170.0 → 0.171.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -1
- package/dist/{authored-code-C2TGxNtf.js → authored-code-DzYtiflw.js} +9 -16
- package/dist/authored-code-DzYtiflw.js.map +1 -0
- package/dist/{authoring-CUTgAxxE.js → authoring-U8BvENNa.js} +2 -2
- package/dist/{authoring-CUTgAxxE.js.map → authoring-U8BvENNa.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +1 -1
- package/dist/{graph-ZDMygFIo.js → graph-DK_za3yj.js} +2 -2
- package/dist/{graph-ZDMygFIo.js.map → graph-DK_za3yj.js.map} +1 -1
- package/dist/graph.d.ts +25 -85
- package/dist/graph.js +4 -157
- package/dist/graph.js.map +1 -1
- package/dist/{index-BgptUCKl.d.ts → index-C38CMh7Y.d.ts} +2 -2
- package/dist/{index-BGQtpQuJ.d.ts → index-CTIWK6cQ.d.ts} +59 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -4
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +5 -5
- package/dist/{knowledge-D3211Z_x.js → knowledge-CbSzAeP-.js} +2 -2
- package/dist/{knowledge-D3211Z_x.js.map → knowledge-CbSzAeP-.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-B_g5JOKA.js → loop-runner-bin-CglWRAZs.js} +2 -2
- package/dist/{loop-runner-bin-B_g5JOKA.js.map → loop-runner-bin-CglWRAZs.js.map} +1 -1
- package/dist/{loop-runner-bin-C2NXQK7J.d.ts → loop-runner-bin-CxXDdDd8.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +2 -2
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +3 -3
- package/dist/{openai-tools-UyXVO0kd.js → openai-tools-B_zjkAey.js} +2 -2
- package/dist/{openai-tools-UyXVO0kd.js.map → openai-tools-B_zjkAey.js.map} +1 -1
- package/dist/{runtime-C-7uhhFs.js → runtime-DWs-CucB.js} +246 -6
- package/dist/runtime-DWs-CucB.js.map +1 -0
- package/dist/{supervise-rEE46ruH.js → supervise-CG7JDcEG.js} +11 -2
- package/dist/{supervise-rEE46ruH.js.map → supervise-CG7JDcEG.js.map} +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +10 -10
- package/package.json +1 -1
- package/skills/codemode/SKILL.md +5 -4
- package/dist/authored-code-C2TGxNtf.js.map +0 -1
- package/dist/runtime-C-7uhhFs.js.map +0 -1
package/dist/agent.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { E as SandboxClient, at as RuntimeStreamEvent, t as AgentRunSpec, w as OutputAdapter } from "./types-DpdfZoQ3.js";
|
|
2
2
|
import { a as createSurfaceImprovementProposer, c as SurfaceValidationIssue, d as validateSurfaces, i as SurfaceImprovementEdit, l as renderSurfaceIssues, n as DraftPatchInput, o as AgentSurfaces, r as DraftPatchOutput, s as ResolvedSurface, t as CreateSurfaceImprovementProposerOptions, u as resolveSubjectPath } from "./improvement-adapter-D5gwwoXQ.js";
|
|
3
|
-
import {
|
|
3
|
+
import { Cp as promptResourceProfileMaterialization, Dp as worktreeCliProfileMaterialization, Ep as validateProfileMaterialization, Sp as promptOnlyProfileMaterialization, Tp as sandboxActProfileMaterialization, _p as defineProfileMaterializationContract, bp as promptControlProfileMaterialization, cp as AssertProfileMaterializationOptions, dp as KnownAgentProfileMaterializationAxis, fp as ProfileMaterializationContract, gp as controlProfileMaterialization, hp as assertProfileMaterialization, lp as CanonicalAgentProfileMaterializationAxis, mp as ValidateProfileMaterializationOptions, op as AGENT_PROFILE_MATERIALIZATION_AXES, pp as ProfileMaterializationIssue, sp as AgentProfileMaterializationAxis, up as DefineProfileMaterializationContractOptions, vp as fullProfileMaterialization, wp as renderProfileMaterializationIssues, xp as promptModelProfileMaterialization, yp as profileMaterializationAxes } from "./index-CTIWK6cQ.js";
|
|
4
4
|
import { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer } from "@tangle-network/agent-interface";
|
|
5
5
|
import { TraceAnalystDefinition } from "@tangle-network/agent-eval";
|
|
6
6
|
import { SandboxEvent } from "@tangle-network/sandbox";
|
package/dist/agent.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { o as mapSandboxEvent } from "./sandbox-events-BVjstFgb.js";
|
|
2
2
|
import { Sn as worktreeCliProfileMaterialization, _n as renderProfileMaterializationIssues, _t as createSandboxForSpec, cn as assertProfileMaterialization, dn as fullProfileMaterialization, fn as profileMaterializationAxes, gn as promptResourceProfileMaterialization, hn as promptOnlyProfileMaterialization, ln as controlProfileMaterialization, mn as promptModelProfileMaterialization, pn as promptControlProfileMaterialization, sn as AGENT_PROFILE_MATERIALIZATION_AXES, un as defineProfileMaterializationContract, xn as validateProfileMaterialization, yn as sandboxActProfileMaterialization } from "./supervisor-B-mmmiOU.js";
|
|
3
|
-
import "./runtime-
|
|
3
|
+
import "./runtime-DWs-CucB.js";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
6
6
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
@@ -1,17 +1,16 @@
|
|
|
1
1
|
import { m as ValidationError } from "./errors-CDZ8XsVj.js";
|
|
2
2
|
//#region src/runtime/authored-code.ts
|
|
3
3
|
/**
|
|
4
|
-
* The ONE lint over model-authored source
|
|
4
|
+
* The ONE lint over model-authored source.
|
|
5
5
|
*
|
|
6
6
|
* Two features have a model write code the runtime then runs: `authorStrategy` (an authored
|
|
7
|
-
* optimization strategy, since 0.60) and
|
|
8
|
-
* the same refusals;
|
|
9
|
-
* which an audit flagged. This module is the single copy both import.
|
|
7
|
+
* optimization strategy, since 0.60) and code mode's `execute` (a program over the coordination
|
|
8
|
+
* verbs). Both need the same refusals; this module is the single copy both import.
|
|
10
9
|
*
|
|
11
|
-
* A LINT, NOT A SANDBOX — it reads text and cannot constrain what running code does
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
10
|
+
* A LINT, NOT A SANDBOX — it reads text and cannot constrain what running code does, and trivial
|
|
11
|
+
* concatenation defeats any token match. Its only job is refusing the obvious escapes so a typo or
|
|
12
|
+
* a lazy model does not run; it is never the security boundary. Isolation, where required, is the
|
|
13
|
+
* execution boundary's job (a jailed runner, a sandboxed loader), never this check's.
|
|
15
14
|
*/
|
|
16
15
|
/** Refuse the obvious escapes in authored source. See the module doc for what this is NOT. */
|
|
17
16
|
function assertAuthoredCode(code, options = {}) {
|
|
@@ -32,13 +31,7 @@ function assertAuthoredCode(code, options = {}) {
|
|
|
32
31
|
[/child_process|node:fs|node:net|node:http|worker_threads/, "node builtin access"]
|
|
33
32
|
]) if (pattern.test(code)) throw new ValidationError(`${context} rejected: ${what}`);
|
|
34
33
|
}
|
|
35
|
-
/** Pull the first fenced block out of a model reply; the whole reply if it carries no fence. */
|
|
36
|
-
function extractCodeBlock(reply) {
|
|
37
|
-
const code = (/```(?:[a-zA-Z]*)\n([\s\S]*?)```/u.exec(reply)?.[1] ?? reply).trim();
|
|
38
|
-
if (code.length === 0) throw new ValidationError("authored code: the model returned no code");
|
|
39
|
-
return code;
|
|
40
|
-
}
|
|
41
34
|
//#endregion
|
|
42
|
-
export {
|
|
35
|
+
export { assertAuthoredCode as t };
|
|
43
36
|
|
|
44
|
-
//# sourceMappingURL=authored-code-
|
|
37
|
+
//# sourceMappingURL=authored-code-DzYtiflw.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authored-code-DzYtiflw.js","names":[],"sources":["../src/runtime/authored-code.ts"],"sourcesContent":["/**\n * The ONE lint over model-authored source.\n *\n * Two features have a model write code the runtime then runs: `authorStrategy` (an authored\n * optimization strategy, since 0.60) and code mode's `execute` (a program over the coordination\n * verbs). Both need the same refusals; this module is the single copy both import.\n *\n * A LINT, NOT A SANDBOX — it reads text and cannot constrain what running code does, and trivial\n * concatenation defeats any token match. Its only job is refusing the obvious escapes so a typo or\n * a lazy model does not run; it is never the security boundary. Isolation, where required, is the\n * execution boundary's job (a jailed runner, a sandboxed loader), never this check's.\n */\nimport { ValidationError } from '../errors'\n\nexport interface AuthoredCodeOptions {\n /** Import specifiers an authored module may name. Empty (the default) bans every import. A\n * specifier admits ANY import form of that module (named, namespace, default) — the lint\n * gates WHICH module, not the syntax used to reach it. */\n readonly allowedImports?: ReadonlyArray<string>\n /** Names the refusal, e.g. `code mode (node-1)`. Defaults to `authored code`. */\n readonly context?: string\n}\n\n/** Refuse the obvious escapes in authored source. See the module doc for what this is NOT. */\nexport function assertAuthoredCode(code: string, options: AuthoredCodeOptions = {}): void {\n const context = options.context ?? 'authored code'\n const allowed = options.allowedImports ?? []\n for (const line of code.split('\\n')) {\n if (!/^\\s*import\\s/.test(line)) continue\n const named = allowed.some(\n (specifier) => line.includes(`'${specifier}'`) || line.includes(`\"${specifier}\"`),\n )\n if (!named) {\n throw new ValidationError(\n `${context} rejected: foreign import — ${line.trim().slice(0, 120)}${\n allowed.length === 0\n ? ' (no import is allowed here)'\n : ` (allowed: ${allowed.join(', ')})`\n }`,\n )\n }\n }\n const banned: ReadonlyArray<readonly [RegExp, string]> = [\n [/\\brequire\\s*\\(/, 'require()'],\n [/\\bimport\\s*\\(/, 'dynamic import()'],\n [/\\beval\\s*\\(/, 'eval()'],\n [/new\\s+Function\\s*\\(/, 'new Function()'],\n [/\\bprocess\\s*[.[]/, 'process access'],\n [/\\bglobalThis\\s*[.[]/, 'globalThis access'],\n [/\\bfetch\\s*\\(/, 'network access'],\n [/child_process|node:fs|node:net|node:http|worker_threads/, 'node builtin access'],\n ]\n for (const [pattern, what] of banned) {\n if (pattern.test(code)) throw new ValidationError(`${context} rejected: ${what}`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,SAAgB,mBAAmB,MAAc,UAA+B,CAAC,GAAS;CACxF,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,UAAU,QAAQ,kBAAkB,CAAC;CAC3C,KAAK,MAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;EACnC,IAAI,CAAC,eAAe,KAAK,IAAI,GAAG;EAIhC,IAAI,CAHU,QAAQ,MACnB,cAAc,KAAK,SAAS,IAAI,UAAU,EAAE,KAAK,KAAK,SAAS,IAAI,UAAU,EAAE,CAEzE,GACP,MAAM,IAAI,gBACR,GAAG,QAAQ,8BAA8B,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,GAAG,IAC/D,QAAQ,WAAW,IACf,iCACA,cAAc,QAAQ,KAAK,IAAI,EAAE,IAEzC;CAEJ;CAWA,KAAK,MAAM,CAAC,SAAS,SAAS;EAT5B,CAAC,kBAAkB,WAAW;EAC9B,CAAC,iBAAiB,kBAAkB;EACpC,CAAC,eAAe,QAAQ;EACxB,CAAC,uBAAuB,gBAAgB;EACxC,CAAC,oBAAoB,gBAAgB;EACrC,CAAC,uBAAuB,mBAAmB;EAC3C,CAAC,gBAAgB,gBAAgB;EACjC,CAAC,2DAA2D,qBAAqB;CAEhD,GACjC,IAAI,QAAQ,KAAK,IAAI,GAAG,MAAM,IAAI,gBAAgB,GAAG,QAAQ,aAAa,MAAM;AAEpF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { v as supervisorPolicyPrompt } from "./supervise-
|
|
1
|
+
import { v as supervisorPolicyPrompt } from "./supervise-CG7JDcEG.js";
|
|
2
2
|
import { agentProfileSchema } from "@tangle-network/agent-interface";
|
|
3
3
|
import { computeFindingId, makeFinding } from "@tangle-network/agent-eval";
|
|
4
4
|
//#region src/runtime/supervise/authoring.ts
|
|
@@ -160,4 +160,4 @@ function profileRichnessFinding(richness, opts) {
|
|
|
160
160
|
//#endregion
|
|
161
161
|
export { supervisorInstructions as a, profileRichnessFinding as i, assessAuthoredProfile as n, defaultProfileRichnessThresholds as r, asAuthoredProfile as t };
|
|
162
162
|
|
|
163
|
-
//# sourceMappingURL=authoring-
|
|
163
|
+
//# sourceMappingURL=authoring-U8BvENNa.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authoring-CUTgAxxE.js","names":[],"sources":["../src/runtime/supervise/authoring.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 (system prompt), 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'\nimport { supervisorPolicyPrompt } from './prompt-registry'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific system prompt are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt & { readonly systemPrompt: string }\n}\n\n/** Narrow an untyped `spawn_agent` 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 const systemPrompt = parsed.data.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string' || systemPrompt.trim().length === 0) 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, systemPrompt },\n }\n}\n\n/** The supervisor SKILL — the how-to the supervisor reads (its system prompt). THE optimizable\n * surface: editing this changes how the supervisor designs every agent it spawns.\n *\n * The POLICY paragraph is the registry's one `supervisor/policy` entry — the same stance\n * `defaultSupervisorPrompt` carries — so both front doors run the same work-vs-delegate rule;\n * this function ADDS the profile-authoring skill (how to WRITE the workers it spawns), which is\n * additive craft, not a different policy. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n supervisorPolicyPrompt.text,\n '',\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_agent with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.systemPrompt: rich 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 ' • metadata.role=\"driver\" when this child should be a sub-supervisor that may author and drive its own children.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n \"3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.\",\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n '5. Stop (reply with no tool call) once the work is delivered.',\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// `await_event({kinds:['finding']})` — 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 /** The resolved system prompt (canonical `prompt.systemPrompt`, the sandbox `prompt.system`\n * convention, or a bare-string prompt — whichever the author used). */\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 the system prompt from any authored shape: canonical `prompt.systemPrompt`, the sandbox\n * `prompt.system` convention, or a bare-string `prompt`. */\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 if (typeof o.systemPrompt === 'string') return o.systemPrompt\n if (typeof o.system === 'string') return o.system\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,kBAAkB,KAAsC;CACtE,MAAM,SAAS,mBAAmB,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AChB,MAAM,aAAa,MAAM,aAAa;CACtC,MAAM,UAAU,SAAS;CACzB,MAAM,QAAQ,SAAS,OACnB,WAAW,SAAS,KAAK,oCAAoC,SAAS,QAAQ,KAAK,IAAI,EAAE,KACzF,WAAW,SAAS,KAAK,8CAA8C,SAAS,WAAW,IAAA,CAAK,QAAQ,CAAC,EAAE;CAM/G,OAAO,YAAY;EACjB;EACA,UAP2C,SAAS,OAClD,SAAS,WAAW,MAClB,SACA,WACF;EAIF,MAAM;EACN;EACA;EACA,YAAY;EACZ,eAAe,CACb;GACE,MAAM;GACN,KAAK,WAAW;GAChB,SAAS,SAAS,SAAS,kBAAkB,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"}
|
|
1
|
+
{"version":3,"file":"authoring-U8BvENNa.js","names":[],"sources":["../src/runtime/supervise/authoring.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 (system prompt), 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'\nimport { supervisorPolicyPrompt } from './prompt-registry'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific system prompt are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt & { readonly systemPrompt: string }\n}\n\n/** Narrow an untyped `spawn_agent` 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 const systemPrompt = parsed.data.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string' || systemPrompt.trim().length === 0) 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, systemPrompt },\n }\n}\n\n/** The supervisor SKILL — the how-to the supervisor reads (its system prompt). THE optimizable\n * surface: editing this changes how the supervisor designs every agent it spawns.\n *\n * The POLICY paragraph is the registry's one `supervisor/policy` entry — the same stance\n * `defaultSupervisorPrompt` carries — so both front doors run the same work-vs-delegate rule;\n * this function ADDS the profile-authoring skill (how to WRITE the workers it spawns), which is\n * additive craft, not a different policy. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n supervisorPolicyPrompt.text,\n '',\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_agent with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.systemPrompt: rich 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 ' • metadata.role=\"driver\" when this child should be a sub-supervisor that may author and drive its own children.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n \"3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.\",\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n '5. Stop (reply with no tool call) once the work is delivered.',\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// `await_event({kinds:['finding']})` — 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 /** The resolved system prompt (canonical `prompt.systemPrompt`, the sandbox `prompt.system`\n * convention, or a bare-string prompt — whichever the author used). */\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 the system prompt from any authored shape: canonical `prompt.systemPrompt`, the sandbox\n * `prompt.system` convention, or a bare-string `prompt`. */\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 if (typeof o.systemPrompt === 'string') return o.systemPrompt\n if (typeof o.system === 'string') return o.system\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,kBAAkB,KAAsC;CACtE,MAAM,SAAS,mBAAmB,UAAU,GAAG;CAC/C,IAAI,CAAC,OAAO,SAAS,OAAO;CAC5B,MAAM,eAAe,OAAO,KAAK,QAAQ;CACzC,IAAI,OAAO,iBAAiB,YAAY,aAAa,KAAK,CAAC,CAAC,WAAW,GAAG,OAAO;CACjF,OAAO;EACL,GAAG,OAAO;EACV,MACE,OAAO,OAAO,KAAK,SAAS,YAAY,OAAO,KAAK,KAAK,SAAS,IAC9D,OAAO,KAAK,OACZ;EACN,QAAQ;GAAE,GAAG,OAAO,KAAK;GAAQ;EAAa;CAChD;AACF;;;;;;;;AASA,SAAgB,uBAAuB,MAAkC;CACvE,OAAO;EACL,uBAAuB;EACvB;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,mCAA8D;CACzE,sBAAsB;CACtB,sBAAsB;AACxB;;;AA0BA,SAAS,oBAAoB,SAA+B;C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M;GACN;GACA,OAAO,YAAY,SAAS,OAAO,SAAS;EAC9C,CAAC;CACH,CAAC;AACH"}
|
package/dist/durable.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ko as SupervisorProfile, lo as SuperviseOptions, po as supervise } from "./index-CTIWK6cQ.js";
|
|
2
2
|
import { l as RuntimeHooks, o as RuntimeHookEvent, r as RuntimeDecisionPoint } from "./runtime-hooks-Bj6wJHlH.js";
|
|
3
3
|
import { A as ProviderModelExecutionEvidence, J as SpendGap, K as Spend, O as ProfileMaterializationReceipt, T as NodeId, o as ExecutionBindingReceipt, st as WorkerTraceEvidence } from "./types-DjVO-p7R.js";
|
|
4
4
|
//#region src/durable/chat-engine.d.ts
|
package/dist/durable.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { i as cloneSpend, t as addSpend, y as zeroSpend } from "./util-D6ZEuBMi.js";
|
|
2
2
|
import { i as writeAllBytes, n as parseCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError } from "./jsonl-file-CDfsCI5s.js";
|
|
3
3
|
import { a as withPursuitContext, t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
|
|
4
|
-
import { n as supervise } from "./supervise-
|
|
4
|
+
import { n as supervise } from "./supervise-CG7JDcEG.js";
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
6
6
|
import { resolve } from "node:path";
|
|
7
7
|
import { readFile } from "node:fs/promises";
|
|
@@ -2,7 +2,7 @@ import { m as ValidationError } from "./errors-CDZ8XsVj.js";
|
|
|
2
2
|
import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore } from "./spawn-journal-Tgvp5VS5.js";
|
|
3
3
|
import { f as harnessRunsAgent } from "./model-policy-Sw4ywhtL.js";
|
|
4
4
|
import { t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
|
|
5
|
-
import { h as kernelPromptRegistry, m as formatPromptHandle, n as supervise, r as superviseWithTestBrain } from "./supervise-
|
|
5
|
+
import { h as kernelPromptRegistry, m as formatPromptHandle, n as supervise, r as superviseWithTestBrain } from "./supervise-CG7JDcEG.js";
|
|
6
6
|
import { agentProfileSchema, canonicalCandidateDigest } from "@tangle-network/agent-interface";
|
|
7
7
|
//#region src/runtime/supervise/graph.ts
|
|
8
8
|
/**
|
|
@@ -543,4 +543,4 @@ function graphTask(graph, root) {
|
|
|
543
543
|
//#endregion
|
|
544
544
|
export { runGraphWithTestBrain as i, defaultEdgeTraversalCap as n, runGraph as r, GraphEdgeCapError as t };
|
|
545
545
|
|
|
546
|
-
//# sourceMappingURL=graph-
|
|
546
|
+
//# sourceMappingURL=graph-DK_za3yj.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-ZDMygFIo.js","names":[],"sources":["../src/runtime/supervise/graph.ts"],"sourcesContent":["/**\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 traversal lands in an EDGE LEDGER\n * (`delivered | stripped | empty | unpropagated`, 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 *\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 {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport type {\n AnalystRegistry,\n AnalyzeOnSettleRoute,\n ContinuityMode,\n CoordinationEvent,\n MakeWorkerAgent,\n} from '../../mcp/tools/coordination'\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 {\n formatPromptHandle,\n kernelPromptRegistry,\n type PromptHandle,\n type PromptRegistry,\n} from './prompt-registry'\nimport { type SuperviseOptions, supervise, superviseWithTestBrain } from './supervise'\nimport type { Budget, NodeId, ResultBlobStore, SpawnJournal, SupervisedResult } from './types'\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_agent` `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\nexport interface AgentGraph {\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 /** One conserved pool across the whole graph — cycles without conservation never terminate. */\n readonly budget: Budget\n}\n\n// ── The edge ledger ────────────────────────────────────────────────────────────\n\nexport type EdgeDeliveryOutcome = 'delivered' | 'stripped' | 'empty' | 'unpropagated'\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>` or `analyzes:<analyst>:<over…>-><to>`. */\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes'\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. */\n readonly workerId?: string\n}\n\n/** Default per-edge traversal cap — the cyclic-graph backstop when an edge names none. */\nexport const defaultEdgeTraversalCap = 32\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 'continuityByProfile',\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] 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 'backend',\n 'rootHandle',\n 'signal',\n 'execution',\n 'resolveDeliverable',\n 'coordination',\n 'peerMail',\n 'driverBackend',\n 'profileSecurity',\n 'authorizeSpawn',\n 'isDriverProfile',\n 'router',\n 'driveHarness',\n 'driverRetry',\n 'onDriverAttempt',\n 'childSettleGraceMs',\n 'resolveDriveHarness',\n 'driveHarnessMaterialization',\n 'resolveSupervisorTools',\n 'extraTools',\n 'executeExtraTool',\n 'perWorker',\n 'maxLiveWorkers',\n 'watchWorkers',\n 'stallAfterMs',\n 'runDir',\n 'probes',\n 'stopRule',\n 'onProgressStop',\n 'maxDepth',\n 'maxTurns',\n 'compaction',\n 'now',\n 'allowedModels',\n 'finalizer',\n 'otel',\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/** 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/** 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\n extends Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\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 declared `role: 'driver'`\n * becomes a nested supervisor instead, whose own leaves are derived the same way. */\n readonly backend?: SuperviseOptions['backend']\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?: SuperviseOptions['driverBackend']\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\n * declared `role: 'driver'` 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 /** 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}\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\ninterface ValidatedGraph {\n readonly root: GraphNode\n readonly workers: ReadonlyMap<NodeId, GraphNode>\n readonly delegatesByWorker: ReadonlyMap<NodeId, Extract<GraphEdge, { kind: 'delegates' }>>\n readonly analyzes: ReadonlyArray<Extract<GraphEdge, { kind: 'analyzes' }>>\n /** Nodes referenced as an analyzes edge's ANALYST (the analyst-agent form): reachable through\n * their analyzes edge (spawned on settle), never through a delegates edge. */\n readonly analystNodes: ReadonlyMap<NodeId, GraphNode>\n}\n\nfunction edgeId(edge: GraphEdge): string {\n return edge.kind === 'delegates'\n ? `delegates:${edge.from}->${edge.to}`\n : `analyzes:${edge.analyst}:${edge.over.join('+')}->${edge.to}`\n}\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 (!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 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 const byId = new Map<NodeId, GraphNode>()\n for (const node of graph.nodes) {\n if (typeof node.id !== 'string' || node.id.length === 0) {\n throw new ValidationError('runGraph: every node needs a non-empty string id')\n }\n if (byId.has(node.id)) throw new ValidationError(`runGraph: duplicate node id '${node.id}'`)\n const parsed = agentProfileSchema.safeParse(node.profile)\n if (!parsed.success) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has an invalid AgentProfile: ${parsed.error.message}`,\n )\n }\n // The profile NAME is the node identity everywhere downstream: node pinning resolves a\n // spawn's `profile.name` against node ids, and the coordination layer matches analyst\n // routes (`over`/`to`) against the settled worker's PROFILE NAME. A divergent name would\n // make every analyzes edge touching this node silently never match — refuse it up front.\n if (node.profile.name !== node.id) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has profile.name ${JSON.stringify(node.profile.name)} — ` +\n 'profile.name IS the node identity (node pinning and analyst routing match on it) and ' +\n 'must equal the node id',\n )\n }\n byId.set(node.id, node)\n }\n const requireNode = (id: NodeId, where: string): GraphNode => {\n const node = byId.get(id)\n if (!node) throw new ValidationError(`runGraph: ${where} references unknown node '${id}'`)\n return node\n }\n const delegates = graph.edges.filter(\n (edge): edge is Extract<GraphEdge, { kind: 'delegates' }> => edge.kind === 'delegates',\n )\n const analyzes = graph.edges.filter(\n (edge): edge is Extract<GraphEdge, { kind: 'analyzes' }> => edge.kind === 'analyzes',\n )\n if (delegates.length === 0) {\n throw new ValidationError('runGraph: at least one delegates edge is required (who spawns whom)')\n }\n for (const edge of graph.edges) registry.resolve(edge.directive)\n for (const edge of delegates) {\n requireNode(edge.from, edgeId(edge))\n requireNode(edge.to, edgeId(edge))\n if (edge.from === edge.to) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} delegates to itself — the driver↔worker cycle is the ` +\n 'settle-return loop, not a self-edge',\n )\n }\n // The type admits only 'fresh' | 'resume', but a graph is plain data that often arrives\n // through JSON — refuse a nonsense mode here, never let it reach the spawn tool as a string.\n if (\n edge.continuity !== undefined &&\n edge.continuity !== 'fresh' &&\n edge.continuity !== 'resume'\n ) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} has invalid continuity ${JSON.stringify(edge.continuity)} — ` +\n \"a delegates edge's continuity is 'fresh' or 'resume'\",\n )\n }\n }\n // Root: the one node that delegates and is never delegated TO. P0 executes the star/2-node\n // cyclic family (one driver, N workers); nested driver graphs are the recorded P3 absorption.\n const delegatedTo = new Set(delegates.map((edge) => edge.to))\n const roots = [...new Set(delegates.map((edge) => edge.from))].filter(\n (id) => !delegatedTo.has(id),\n )\n if (roots.length !== 1) {\n throw new ValidationError(\n `runGraph: expected exactly ONE root (a node that delegates and is never delegated to), ` +\n `found ${roots.length === 0 ? 'none — delegates edges form a cycle with no entry' : roots.join(', ')}. ` +\n 'P0 executes driver↔worker(s); nested driver graphs are P3.',\n )\n }\n const root = requireNode(roots[0] as string, 'root resolution')\n for (const edge of delegates) {\n if (edge.from !== root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} delegates from a non-root node — P0 executes one driver over ` +\n 'its workers (the 2-node cyclic case, star-generalized); deeper delegation is P3',\n )\n }\n }\n const analystIds = new Set<string>()\n const analystNodes = new Map<NodeId, GraphNode>()\n for (const edge of analyzes) {\n // Continuity is a delegates-edge axis ONLY: analysts (lens or node) are spawned by the\n // analyst-on-settle machinery, each run a fresh session over settled evidence — an analyzes\n // edge carrying continuity would silently mean nothing, so it is refused as data.\n if ((edge as { continuity?: unknown }).continuity !== undefined) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} carries continuity — analysts are spawned by the analyst ` +\n 'machinery (every analyst run is a fresh session over settled evidence), so ' +\n 'continuity is a delegates-edge axis only',\n )\n }\n // The runner's traversal ledger resolves a finding/steer back to its edge BY ANALYST ID\n // alone, so a second edge sharing an analyst would silently absorb the first edge's\n // traversals (last-registered wins). Multi-edge-per-analyst is not yet supported; refuse it\n // rather than mis-ledger it.\n if (analystIds.has(edge.analyst)) {\n throw new ValidationError(\n `runGraph: two analyzes edges share analyst '${edge.analyst}' — one analyzes edge per ` +\n 'analyst lens (traversals are ledgered by analyst id; a second edge would silently ' +\n \"absorb the first's). Register the lens under a second id for a second edge.\",\n )\n }\n analystIds.add(edge.analyst)\n // The analyst REFERENCE has two forms — a registry lens id or a graph node id — and the id\n // itself is what distinguishes them, so an id living in both is refused as ambiguous rather\n // than silently resolved by precedence.\n const analystNode = byId.get(edge.analyst)\n const inRegistry = analysts?.kinds.some((kind) => kind.id === edge.analyst) === true\n if (analystNode !== undefined && inRegistry) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is BOTH a graph node and a lens in ` +\n 'the analysts registry — the id alone distinguishes the two analyst forms, so this is ' +\n 'ambiguous; rename the node or register the lens under another id',\n )\n }\n if (analystNode !== undefined) {\n // The analyst-AGENT form. Oracle doctrine holds structurally: the analyst node can never\n // receive work — not from the root (a delegates edge to it is refused) and not by being\n // the root (the root delegates by definition).\n if (analystNode.id === root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} names the ROOT as its analyst — the root is the driver; ` +\n 'give the analyst its own node with no delegates edge pointing at it',\n )\n }\n if (delegatedTo.has(analystNode.id)) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} names node '${edge.analyst}' as its analyst, but that node ` +\n 'is a delegates target — oracle doctrine: an analyst is never delegated to. An ' +\n 'analyst NODE is legal only with NO delegates edge pointing at it; give the analyst ' +\n 'its own delegates-free node or pass a lens id from RunGraphOptions.analysts.',\n )\n }\n analystNodes.set(analystNode.id, analystNode)\n } else if (!analysts) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is not a graph node, and no ` +\n 'RunGraphOptions.analysts registry was provided to resolve it as a lens',\n )\n } else if (!inRegistry) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is neither a graph node nor in the ` +\n `analysts registry (known lenses: ${analysts.kinds.map((kind) => kind.id).join(', ') || 'none'})`,\n )\n }\n if (edge.over.length === 0) {\n throw new ValidationError(`runGraph: ${edgeId(edge)} must analyze at least one node`)\n }\n for (const over of edge.over) {\n requireNode(over, edgeId(edge))\n // Analysts observe SETTLED WORKERS, matched by profile name — the root drives and never\n // settles as a worker, so an edge over the root would silently never fire; refuse it.\n if (over === root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyzes the ROOT — analysts observe settled workers, and ` +\n 'the root never settles as one, so this edge would silently never fire; list ' +\n 'delegates-target nodes only',\n )\n }\n }\n requireNode(edge.to, edgeId(edge))\n }\n // Second pass, once every analyst NODE is known: an analyst run's settlement is a FINDING,\n // never a worker settle, so an analyzes edge OVER an analyst node would silently never fire —\n // refuse it rather than let it rot unobserved.\n for (const edge of analyzes) {\n for (const over of edge.over) {\n if (analystNodes.has(over)) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyzes '${over}', which is an analyst node — an analyst ` +\n 'run settles as a finding, never as a worker, so this edge would silently never ' +\n 'fire; analyst nodes are not analyzable',\n )\n }\n }\n }\n const workers = new Map<NodeId, GraphNode>()\n const delegatesByWorker = new Map<NodeId, Extract<GraphEdge, { kind: 'delegates' }>>()\n for (const edge of delegates) {\n if (delegatesByWorker.has(edge.to)) {\n throw new ValidationError(\n `runGraph: node '${edge.to}' is the target of two delegates edges — one delegation ` +\n 'directive per worker node (version the directive instead of forking the edge)',\n )\n }\n delegatesByWorker.set(edge.to, edge)\n workers.set(edge.to, requireNode(edge.to, edgeId(edge)))\n }\n // Every non-root node must be reachable by SOME edge, or it can never run. A worker node is\n // reached by its delegates edge; an analyst node by its analyzes edge (spawned on settle).\n for (const node of graph.nodes) {\n if (node.id !== root.id && !workers.has(node.id) && !analystNodes.has(node.id)) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has no delegates edge to it — an unreachable node never runs`,\n )\n }\n }\n return { root, workers, delegatesByWorker, analyzes, analystNodes }\n}\n\n// ── The runner ─────────────────────────────────────────────────────────────────\n\nconst byteLength = (text: string): number => Buffer.byteLength(text, 'utf8')\n\nfunction stringifyPayload(payload: unknown): string {\n if (typeof payload === 'string') return payload\n try {\n return JSON.stringify(payload) ?? String(payload)\n } catch {\n return String(payload)\n }\n}\n\n/**\n * Execute an {@link AgentGraph}. The root node becomes the supervisor (`supervise()` — the\n * execution core), each worker node is spawnable BY NODE ID (`spawn_agent` with\n * `profile: { name: '<node id>' }`; the node's canonical profile is pinned by 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 } = 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 const registry = opts.registry ?? kernelPromptRegistry()\n const validated = validateGraph(graph, registry, opts.analysts)\n const { root } = validated\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 if (!opts.backend && !opts.makeLeafAgent) {\n throw new ValidationError(\n 'runGraph: provide opts.backend (where nodes run) or opts.makeLeafAgent',\n )\n }\n return validated\n}\n\nexport function superviseAgentGraph(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): Promise<GraphResult> {\n const registry = opts.registry ?? kernelPromptRegistry()\n const { root, workers, delegatesByWorker, analyzes, analystNodes } = assertRunGraphAuthoring(\n graph,\n opts,\n brain,\n )\n const journal = opts.journal ?? new InMemorySpawnJournal()\n const blobs = opts.blobs ?? new InMemoryResultBlobStore()\n const runId =\n opts.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 // ── Ledger state ──\n const ledger: EdgeTraversal[] = []\n const journaled = new Set<EdgeTraversal>()\n const traversalCounts = new Map<string, number>()\n const exhausted = new Set<string>()\n // The subset of `exhausted` that REFUSED work. Only a delegates cap closes the spawn cycle, so\n // only it can be the reason a run ended winnerless — an analyzes cap refuses nothing.\n const exhaustedDelegates = new Set<string>()\n const journalWrites: Promise<void>[] = []\n let ledgerSeq = 0\n const appendJournal = (entry: EdgeTraversal, nodeIdForEvent: string): Promise<void> => {\n if (journaled.has(entry)) return Promise.resolve()\n journaled.add(entry)\n const write = journal.appendEvent(runId, {\n kind: 'edge',\n id: nodeIdForEvent,\n edge: { kind: entry.kind, from: entry.from, to: entry.to, directive: entry.directive },\n traversal: entry.traversal,\n outcome: entry.outcome,\n continuity: entry.continuity,\n bytes: entry.bytes,\n ...(entry.reason !== undefined ? { reason: entry.reason } : {}),\n seq: ledgerSeq++,\n at: new Date(now()).toISOString(),\n })\n journalWrites.push(write)\n return write\n }\n const record = (entry: Omit<EdgeTraversal, 'traversal'>, journalNow: boolean): EdgeTraversal => {\n const count = (traversalCounts.get(entry.edge) ?? 0) + 1\n traversalCounts.set(entry.edge, count)\n const row: EdgeTraversal = { ...entry, traversal: count }\n ledger.push(row)\n if (journalNow) void appendJournal(row, row.workerId ?? `graph:${row.to}`)\n return row\n }\n\n // ── Node pinning + delegates spawn traversals (the authorizeSpawn wrapper) ──\n // Pinning lives in `authorizeSpawn`, which the kernel runs BEFORE it decides whether a child is\n // a leaf or a nested supervisor. That is what lets a node declared `role: 'driver'` become a real\n // supervisor carrying its canonical profile: the kernel's `isDriver` reads the PINNED profile,\n // not the driver-authored `{ name }` stub. (It used to live in `makeWorkerAgent`, a leaf-only\n // seam, which made every node a leaf no matter what its profile declared — #965.)\n const nodeByWorkerId = new Map<string, NodeId>()\n const pendingByAssignment = new Map<string, EdgeTraversal>()\n type SpawnAuthorizationInput = Parameters<NonNullable<SuperviseOptions['authorizeSpawn']>>[0]\n const pinNode = (input: SpawnAuthorizationInput): AgentProfile => {\n const requested =\n typeof (input.profile as { name?: unknown } | undefined)?.name === 'string'\n ? (input.profile as { name: string }).name\n : undefined\n // An analyst-AGENT run: the coordination settle hook — never the driver; the marker is\n // authored by the runtime, not accepted from model arguments — spawns the analyst NODE.\n // Pin the node's canonical profile; the analysis directive travels as the TASK (composed by\n // the coordination layer with the settled worker's trace evidence), so nothing is appended\n // to the profile's instructions here. Its traversal is ledgered on the finding/steer it\n // produces, exactly like a registry analyst's.\n if (input.analyst !== undefined) {\n const analystNode = analystNodes.get(input.analyst)\n if (!analystNode || requested !== analystNode.id) {\n throw new ValidationError(\n `runGraph: analyst run for ${JSON.stringify(input.analyst)} does not name an ` +\n `analyst node of this graph (analyst nodes: ${[...analystNodes.keys()].join(', ') || 'none'})`,\n )\n }\n return analystNode.profile\n }\n const node = requested !== undefined ? workers.get(requested) : undefined\n if (!node) {\n throw new ValidationError(\n `runGraph: spawn_agent named profile ${JSON.stringify(requested)} which is not a worker ` +\n `node of this graph (nodes: ${[...workers.keys()].join(', ')}). Spawn by node id: ` +\n 'profile.name selects the node; the node profile itself is pinned by the graph.',\n )\n }\n const edge = delegatesByWorker.get(node.id) as Extract<GraphEdge, { kind: 'delegates' }>\n const id = edgeId(edge)\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const used = traversalCounts.get(id) ?? 0\n // The EFFECTIVE spawn mode the coordination layer resolved (per-call override, else this\n // edge's declared default, else fresh) — stamped on the row so the ledger states how each\n // hop continued, never how it was merely configured to.\n const spawnContinuity = input.continuity ?? 'fresh'\n if (used >= cap) {\n exhausted.add(id)\n exhaustedDelegates.add(id)\n record(\n {\n edge: id,\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: 'unpropagated',\n continuity: spawnContinuity,\n bytes: 0,\n reason: `traversal-cap-exhausted (max ${cap})`,\n },\n true,\n )\n throw new ValidationError(\n `runGraph: delegates edge ${id} exhausted its traversal cap (${cap}) — the ` +\n 'cyclic-graph backstop refused this spawn',\n )\n }\n const directiveText = registry.resolve(edge.directive).text\n const taskText = stringifyPayload(input.task)\n const bytes = byteLength(directiveText) + byteLength(taskText)\n const row = record(\n {\n edge: id,\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: bytes === 0 ? 'empty' : 'delivered',\n continuity: spawnContinuity,\n bytes,\n ...(bytes === 0 ? { reason: 'no directive text and no task payload' } : {}),\n },\n false,\n )\n pendingByAssignment.set(input.assignmentId, row)\n // The delegation directive is a STANDING instruction of this traversal: appended to the\n // node's canonical prompt instructions, so the worker runs under node profile + edge\n // directive, and the driver-authored profile contributes ONLY the node selection.\n return directiveText.length === 0\n ? node.profile\n : {\n ...node.profile,\n prompt: {\n ...(node.profile.prompt ?? {}),\n instructions: [\n ...((node.profile.prompt?.instructions as readonly string[] | undefined) ?? []),\n directiveText,\n ],\n },\n }\n }\n // The pre-journal gate (a bridge backend's route/admission check) must judge the profile that\n // will run, not the `{ name }` stub — otherwise every graph spawn over a bridge is refused\n // `model-route` before the graph ever pins it. This resolver is PURE: it answers \"which node\"\n // without ledgering, because the gate may refuse and nothing may be journaled for a refusal.\n const resolveSpawnProfile = (authored: AgentProfile): AgentProfile => {\n const requested = typeof authored.name === 'string' ? authored.name : undefined\n const node =\n (requested !== undefined ? workers.get(requested) : undefined) ??\n (requested !== undefined ? analystNodes.get(requested) : undefined)\n // Unknown names fall through to authorizeSpawn, which refuses them with the full message and\n // a ledger row; the gate just sees the stub and lets that later refusal speak.\n return node?.profile ?? authored\n }\n // Graph authority first, then the caller's: a product authorizing spawns sees the CANONICAL\n // node profile (what will actually run), never the driver's `{ name }` stub.\n const graphAuthorizeSpawn: NonNullable<SuperviseOptions['authorizeSpawn']> = (input) => {\n const pinned = pinNode(input)\n if (!opts.authorizeSpawn) return { profile: pinned }\n return opts.authorizeSpawn({ ...input, profile: pinned })\n }\n\n // ── Analyzes edges → analyst-on-settle routes with destinations ──\n // A LENS edge's directive wraps the findings for the recipient (so a driver-destined lens\n // route carries no directive — it becomes the driver brief below). A NODE edge's directive is\n // the analyst AGENT's task, so it always rides the route, wherever the findings go.\n const routes: Array<string | AnalyzeOnSettleRoute> = analyzes.map((edge) => {\n const analystNode = analystNodes.get(edge.analyst)\n if (analystNode) {\n return {\n kind: edge.analyst,\n over: edge.over,\n agent: analystNode.profile,\n directive: registry.resolve(edge.directive).text,\n ...(edge.to === root.id ? {} : { to: edge.to }),\n }\n }\n return edge.to === root.id\n ? { kind: edge.analyst, over: edge.over }\n : {\n kind: edge.analyst,\n over: edge.over,\n to: edge.to,\n directive: registry.resolve(edge.directive).text,\n }\n })\n // Driver-destined analyzes findings are standing knowledge for the ROOT: the findings arrive\n // as bus events. For a lens edge the directive tells the driver what to do with them; for a\n // node edge the directive already went to the analyst agent as its task.\n const driverAnalyzesBriefs = analyzes\n .filter((edge) => edge.to === root.id)\n .map((edge) =>\n analystNodes.has(edge.analyst)\n ? `Findings from analyst '${edge.analyst}' (a tool-equipped analyst agent node, over: ` +\n `${edge.over.join(', ')}) will arrive as finding events.`\n : `Findings from analyst '${edge.analyst}' (over: ${edge.over.join(', ')}) will arrive as ` +\n `finding events.\\n${registry.resolve(edge.directive).text}`,\n )\n\n // ── Edge continuity defaults, threaded to the spawn tool by node id (= profile name) ──\n const continuityByProfile: Record<string, ContinuityMode> = {}\n for (const [nodeId, edge] of delegatesByWorker) {\n if (edge.continuity !== undefined) continuityByProfile[nodeId] = edge.continuity\n }\n\n // ── The driver graph brief: which nodes it may spawn, by exact name ──\n const workerLines = [...workers.values()].map((node) => {\n const edge = delegatesByWorker.get(node.id) as Extract<GraphEdge, { kind: 'delegates' }>\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const description =\n typeof node.profile.description === 'string' && node.profile.description.length > 0\n ? ` — ${node.profile.description}`\n : ''\n const continuityNote =\n edge.continuity === 'resume'\n ? \"; continuity: resume — each spawn after the first re-attaches to this node's latest \" +\n 'settled session (spawn again to continue it; steer while it is live)'\n : ''\n return `- '${node.id}'${description} (delegation cap: ${cap} traversals${continuityNote})`\n })\n const graphBrief = [\n 'AGENT GRAPH: you are the driver node of a fixed topology. You may spawn ONLY these worker',\n \"nodes, by EXACT name (spawn_agent with profile: { name: '<node id>' }; the node's full\",\n 'profile is pinned by the graph — any other profile fields you author are ignored):',\n ...workerLines,\n ...(driverAnalyzesBriefs.length > 0 ? ['', ...driverAnalyzesBriefs] : []),\n ].join('\\n')\n const rootProfile: AgentProfile = {\n ...root.profile,\n prompt: {\n ...(root.profile.prompt ?? {}),\n instructions: [\n ...((root.profile.prompt?.instructions as readonly string[] | undefined) ?? []),\n graphBrief,\n ],\n },\n }\n\n // ── Steer + finding observation (delegates steers, analyzes traversals) ──\n // The filter seam: when the caller's authorizeMessage NARROWS an instruction, the delivered\n // bytes differ from the composed bytes — that steer traversal is `stripped` (the VB incident:\n // authored steering silently replaced by boilerplate, byte-indistinguishable downstream).\n const strippedByDigest = new Map<string, { composedBytes: number }>()\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 authorizeMessage: NonNullable<SuperviseOptions['authorizeMessage']> = (input) => {\n if (!opts.authorizeMessage) return { instruction: input.instruction }\n const decision = opts.authorizeMessage(input)\n if (decision.instruction !== input.instruction) {\n strippedByDigest.set(canonicalCandidateDigest(decision.instruction), {\n composedBytes: byteLength(input.instruction),\n })\n }\n return decision\n }\n\n const routedAnalyzesByAnalyst = new Map<string, Extract<GraphEdge, { kind: 'analyzes' }>>()\n const driverAnalyzesByAnalyst = new Map<string, Extract<GraphEdge, { kind: 'analyzes' }>>()\n for (const edge of analyzes) {\n ;(edge.to === root.id ? driverAnalyzesByAnalyst : routedAnalyzesByAnalyst).set(\n edge.analyst,\n edge,\n )\n }\n const analyzesCapReached = (edge: Extract<GraphEdge, { kind: 'analyzes' }>): boolean => {\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const used = traversalCounts.get(edgeId(edge)) ?? 0\n if (used < cap) return false\n exhausted.add(edgeId(edge))\n return true\n }\n const ledgerAnalyzes = (\n edge: Extract<GraphEdge, { kind: 'analyzes' }>,\n outcome: EdgeDeliveryOutcome,\n bytes: number,\n reason: string | undefined,\n workerId: string | undefined,\n ): void => {\n const capped = analyzesCapReached(edge)\n record(\n {\n edge: edgeId(edge),\n kind: 'analyzes',\n from: edge.over.join('+'),\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: capped ? 'unpropagated' : outcome,\n // Every analyzes traversal is a mid-run delivery into an already-live recipient (a\n // routed steer leg, or the finding reaching the live driver) — never a spawn.\n continuity: 'steer',\n bytes,\n ...(capped\n ? {\n reason: `traversal-cap-exhausted (max ${edge.maxTraversals ?? defaultEdgeTraversalCap})`,\n }\n : reason !== undefined\n ? { reason }\n : {}),\n ...(workerId !== undefined ? { workerId } : {}),\n },\n true,\n )\n }\n\n const onCoordinationEvent = async (\n _context: unknown,\n _eventId: unknown,\n recordEnvelope: { readonly event: CoordinationEvent },\n ): Promise<void> => {\n const event = recordEnvelope.event\n if (event.type === 'finding') {\n // A routed edge's traversal is ledgered on its STEER (the delivery); the finding event is\n // its audit copy. A driver-destined edge's traversal IS the finding reaching the bus.\n const edge = driverAnalyzesByAnalyst.get(event.finding.analyst)\n if (!edge) return\n const sourceNode = nodeByWorkerId.get(event.finding.fromWorker)\n if (sourceNode === undefined || !edge.over.includes(sourceNode)) return\n // Absent findings (the analyst returned `undefined` — the producer omits the key so the\n // event stays digestable) contribute ZERO bytes, never the text \"undefined\".\n const findingsText =\n event.finding.findings === undefined ? '' : stringifyPayload(event.finding.findings)\n const directiveBytes = byteLength(registry.resolve(edge.directive).text)\n const empty = findingsText.length === 0\n ledgerAnalyzes(\n edge,\n empty ? 'empty' : 'delivered',\n directiveBytes + byteLength(findingsText),\n empty ? 'analyst returned no findings' : undefined,\n event.finding.fromWorker,\n )\n return\n }\n if (event.type === 'steer') {\n const down = event.down\n if (event.analyst !== undefined) {\n const edge = routedAnalyzesByAnalyst.get(event.analyst)\n if (!edge) return\n ledgerAnalyzes(\n edge,\n down.delivered ? 'delivered' : 'unpropagated',\n byteLength(down.instruction),\n down.delivered ? undefined : down.outcome,\n down.toWorker,\n )\n return\n }\n // A driver-authored steer to a live worker node is a delegates traversal too — the\n // mid-run leg of the same edge (the leg the motivating incident lost).\n const nodeId = nodeByWorkerId.get(down.toWorker)\n if (nodeId === undefined) return\n const edge = delegatesByWorker.get(nodeId)\n if (!edge) return\n const stripped = strippedByDigest.get(down.instructionDigest)\n record(\n {\n edge: edgeId(edge),\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: !down.delivered ? 'unpropagated' : stripped ? 'stripped' : 'delivered',\n // The mid-run leg of the edge: a delivery into the LIVE worker, never a spawn.\n continuity: 'steer',\n bytes: byteLength(down.instruction),\n ...(!down.delivered\n ? { reason: down.outcome }\n : stripped\n ? { reason: `authorization narrowed ${stripped.composedBytes} composed bytes` }\n : {}),\n workerId: down.toWorker,\n },\n true,\n )\n }\n }\n\n // ── Spawn-hook: bind ledger rows to concrete worker ids, then journal them ──\n const graphHooks = {\n onEvent: (event: {\n target?: string\n phase?: string\n payload?: unknown\n }): void | Promise<void> => {\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 const pending = pendingByAssignment.get(payload.assignmentId)\n if (!pending) return\n pendingByAssignment.delete(payload.assignmentId)\n const bound: EdgeTraversal = { ...pending, workerId: payload.childId }\n ledger[ledger.indexOf(pending)] = bound\n nodeByWorkerId.set(payload.childId, bound.to)\n return appendJournal(bound, payload.childId)\n },\n }\n const hooks = composeRuntimeHooks(graphHooks, opts.hooks)\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 // Every forwarded option the caller set, including the ones nobody thought to list here.\n // `backend` rides along: the kernel derives every authorized LEAF from it, under the graph's\n // pinning. The root driver stays an explicit `driverBackend` choice: `rootDriverFromBackend:\n // false` stops supervise() defaulting one from the other, so where workers run never selects\n // where the root runs (the axis split every graph caller relies on).\n ...forwardedSuperviseOptions(opts),\n rootDriverFromBackend: false,\n // Graph-owned values come after the spread: the graph, not the caller, decides these.\n budget: graph.budget,\n deliverable: graph.deliverable,\n authorizeSpawn: graphAuthorizeSpawn,\n resolveSpawnProfile,\n ...(opts.makeLeafAgent ? { makeLeafAgent: opts.makeLeafAgent } : {}),\n journal,\n blobs,\n runId,\n hooks,\n onCoordinationEvent,\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 ...(routes.length > 0\n ? { analyzeOnSettle: routes, ...(opts.analysts ? { analysts: opts.analysts } : {}) }\n : {}),\n ...(Object.keys(continuityByProfile).length > 0 ? { continuityByProfile } : {}),\n authorizeMessage,\n } satisfies SuperviseOptions\n const result =\n brain === undefined\n ? await supervise(rootProfile, graphTask(graph, root), superviseOptions)\n : await superviseWithTestBrain(rootProfile, graphTask(graph, root), {\n ...superviseOptions,\n brain,\n })\n\n // A spawn row is PROVISIONAL until the `agent.spawn` hook (fired synchronously once a worker\n // exists) binds it to a live worker id. A row still unbound here means the factory ran but no\n // NEW worker went live: the spawn was refused after the factory (identity conflict, runtime\n // floor) or a keyed re-spawn deduplicated to an already-completed result (prepare() runs the\n // factory, no hook fires). Both state the same truth every unpropagated row states — the\n // directive never reached a live worker — so rewrite rather than mint a new outcome. Then\n // settle every journal write, so the ledger's journal twin is complete when this returns.\n for (const pending of pendingByAssignment.values()) {\n const refused: EdgeTraversal = {\n ...pending,\n outcome: 'unpropagated',\n bytes: 0,\n reason: `no-live-worker-bound (spawn refused after the factory, or a keyed re-spawn deduplicated to a completed result; ${pending.bytes} composed bytes never crossed)`,\n }\n ledger[ledger.indexOf(pending)] = refused\n await appendJournal(refused, `graph:${refused.to}`)\n }\n pendingByAssignment.clear()\n await Promise.all(journalWrites)\n\n const exhaustedEdges = Object.freeze([...exhausted])\n const frozenLedger = Object.freeze(ledger.map((row) => Object.freeze({ ...row })))\n // A LIFECYCLE ending (caller abort, exhausted budget) 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' || result.reason === 'budget-exhausted')\n if (result.kind !== 'winner' && !lifecycleEnded && exhaustedDelegates.size > 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(Object.freeze([...exhaustedDelegates]), frozenLedger, result)\n }\n return { result, ledger: frozenLedger, exhaustedEdges, runId }\n }\n\n return start()\n}\n\n/** The root task: the graph's own framing. The deliverable (mandatory) is the termination; the\n * task names what the topology exists to produce. */\nfunction graphTask(graph: AgentGraph, root: GraphNode): string {\n const describe = graph.deliverable.describe\n return (\n describe ?? `Deliver the graph's deliverable by driving your worker nodes (root: '${root.id}').`\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwKA,MAAa,0BAA0B;;;AAIvC,IAAa,oBAAb,cAAuC,MAAM;CAC3C;CACA;CACA;CACA,YACE,gBACA,QACA,QACA;EACA,MACE,6CAA6C,eAAe,KAAK,IAAI,EAAE,2NAIzE;EACA,KAAK,OAAO;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O,OAAO,QAAQ,OAAO,KAAK;GAClC,MAAM,cAAc,SAAS,SAAS,QAAQ,IAAI;EACpD;EACA,oBAAoB,MAAM;EAC1B,MAAM,QAAQ,IAAI,aAAa;EAE/B,MAAM,iBAAiB,OAAO,OAAO,CAAC,GAAG,SAAS,CAAC;EACnD,MAAM,eAAe,OAAO,OAAO,OAAO,KAAK,QAAQ,OAAO,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;EAKjF,MAAM,iBACJ,OAAO,SAAS,gBACf,OAAO,WAAW,aAAa,OAAO,WAAW;EACpD,IAAI,OAAO,SAAS,YAAY,CAAC,kBAAkB,mBAAmB,OAAO,GAG3E,MAAM,IAAI,kBAAkB,OAAO,OAAO,CAAC,GAAG,kBAAkB,CAAC,GAAG,cAAc,MAAM;EAE1F,OAAO;GAAE;GAAQ,QAAQ;GAAc;GAAgB;EAAM;CAC/D;CAEA,OAAO,MAAM;AACf;;;AAIA,SAAS,UAAU,OAAmB,MAAyB;CAE7D,OADiB,MAAM,YAAY,YAErB,wEAAwE,KAAK,GAAG;AAEhG"}
|
|
1
|
+
{"version":3,"file":"graph-DK_za3yj.js","names":[],"sources":["../src/runtime/supervise/graph.ts"],"sourcesContent":["/**\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 traversal lands in an EDGE LEDGER\n * (`delivered | stripped | empty | unpropagated`, 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 *\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 {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport type {\n AnalystRegistry,\n AnalyzeOnSettleRoute,\n ContinuityMode,\n CoordinationEvent,\n MakeWorkerAgent,\n} from '../../mcp/tools/coordination'\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 {\n formatPromptHandle,\n kernelPromptRegistry,\n type PromptHandle,\n type PromptRegistry,\n} from './prompt-registry'\nimport { type SuperviseOptions, supervise, superviseWithTestBrain } from './supervise'\nimport type { Budget, NodeId, ResultBlobStore, SpawnJournal, SupervisedResult } from './types'\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_agent` `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\nexport interface AgentGraph {\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 /** One conserved pool across the whole graph — cycles without conservation never terminate. */\n readonly budget: Budget\n}\n\n// ── The edge ledger ────────────────────────────────────────────────────────────\n\nexport type EdgeDeliveryOutcome = 'delivered' | 'stripped' | 'empty' | 'unpropagated'\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>` or `analyzes:<analyst>:<over…>-><to>`. */\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes'\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. */\n readonly workerId?: string\n}\n\n/** Default per-edge traversal cap — the cyclic-graph backstop when an edge names none. */\nexport const defaultEdgeTraversalCap = 32\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 'continuityByProfile',\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] 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 'backend',\n 'rootHandle',\n 'signal',\n 'execution',\n 'resolveDeliverable',\n 'coordination',\n 'peerMail',\n 'driverBackend',\n 'profileSecurity',\n 'authorizeSpawn',\n 'isDriverProfile',\n 'router',\n 'driveHarness',\n 'driverRetry',\n 'onDriverAttempt',\n 'childSettleGraceMs',\n 'resolveDriveHarness',\n 'driveHarnessMaterialization',\n 'resolveSupervisorTools',\n 'extraTools',\n 'executeExtraTool',\n 'perWorker',\n 'maxLiveWorkers',\n 'watchWorkers',\n 'stallAfterMs',\n 'runDir',\n 'probes',\n 'stopRule',\n 'onProgressStop',\n 'maxDepth',\n 'maxTurns',\n 'compaction',\n 'now',\n 'allowedModels',\n 'finalizer',\n 'otel',\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/** 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/** 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\n extends Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\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 declared `role: 'driver'`\n * becomes a nested supervisor instead, whose own leaves are derived the same way. */\n readonly backend?: SuperviseOptions['backend']\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?: SuperviseOptions['driverBackend']\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\n * declared `role: 'driver'` 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 /** 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}\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\ninterface ValidatedGraph {\n readonly root: GraphNode\n readonly workers: ReadonlyMap<NodeId, GraphNode>\n readonly delegatesByWorker: ReadonlyMap<NodeId, Extract<GraphEdge, { kind: 'delegates' }>>\n readonly analyzes: ReadonlyArray<Extract<GraphEdge, { kind: 'analyzes' }>>\n /** Nodes referenced as an analyzes edge's ANALYST (the analyst-agent form): reachable through\n * their analyzes edge (spawned on settle), never through a delegates edge. */\n readonly analystNodes: ReadonlyMap<NodeId, GraphNode>\n}\n\nfunction edgeId(edge: GraphEdge): string {\n return edge.kind === 'delegates'\n ? `delegates:${edge.from}->${edge.to}`\n : `analyzes:${edge.analyst}:${edge.over.join('+')}->${edge.to}`\n}\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 (!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 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 const byId = new Map<NodeId, GraphNode>()\n for (const node of graph.nodes) {\n if (typeof node.id !== 'string' || node.id.length === 0) {\n throw new ValidationError('runGraph: every node needs a non-empty string id')\n }\n if (byId.has(node.id)) throw new ValidationError(`runGraph: duplicate node id '${node.id}'`)\n const parsed = agentProfileSchema.safeParse(node.profile)\n if (!parsed.success) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has an invalid AgentProfile: ${parsed.error.message}`,\n )\n }\n // The profile NAME is the node identity everywhere downstream: node pinning resolves a\n // spawn's `profile.name` against node ids, and the coordination layer matches analyst\n // routes (`over`/`to`) against the settled worker's PROFILE NAME. A divergent name would\n // make every analyzes edge touching this node silently never match — refuse it up front.\n if (node.profile.name !== node.id) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has profile.name ${JSON.stringify(node.profile.name)} — ` +\n 'profile.name IS the node identity (node pinning and analyst routing match on it) and ' +\n 'must equal the node id',\n )\n }\n byId.set(node.id, node)\n }\n const requireNode = (id: NodeId, where: string): GraphNode => {\n const node = byId.get(id)\n if (!node) throw new ValidationError(`runGraph: ${where} references unknown node '${id}'`)\n return node\n }\n const delegates = graph.edges.filter(\n (edge): edge is Extract<GraphEdge, { kind: 'delegates' }> => edge.kind === 'delegates',\n )\n const analyzes = graph.edges.filter(\n (edge): edge is Extract<GraphEdge, { kind: 'analyzes' }> => edge.kind === 'analyzes',\n )\n if (delegates.length === 0) {\n throw new ValidationError('runGraph: at least one delegates edge is required (who spawns whom)')\n }\n for (const edge of graph.edges) registry.resolve(edge.directive)\n for (const edge of delegates) {\n requireNode(edge.from, edgeId(edge))\n requireNode(edge.to, edgeId(edge))\n if (edge.from === edge.to) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} delegates to itself — the driver↔worker cycle is the ` +\n 'settle-return loop, not a self-edge',\n )\n }\n // The type admits only 'fresh' | 'resume', but a graph is plain data that often arrives\n // through JSON — refuse a nonsense mode here, never let it reach the spawn tool as a string.\n if (\n edge.continuity !== undefined &&\n edge.continuity !== 'fresh' &&\n edge.continuity !== 'resume'\n ) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} has invalid continuity ${JSON.stringify(edge.continuity)} — ` +\n \"a delegates edge's continuity is 'fresh' or 'resume'\",\n )\n }\n }\n // Root: the one node that delegates and is never delegated TO. P0 executes the star/2-node\n // cyclic family (one driver, N workers); nested driver graphs are the recorded P3 absorption.\n const delegatedTo = new Set(delegates.map((edge) => edge.to))\n const roots = [...new Set(delegates.map((edge) => edge.from))].filter(\n (id) => !delegatedTo.has(id),\n )\n if (roots.length !== 1) {\n throw new ValidationError(\n `runGraph: expected exactly ONE root (a node that delegates and is never delegated to), ` +\n `found ${roots.length === 0 ? 'none — delegates edges form a cycle with no entry' : roots.join(', ')}. ` +\n 'P0 executes driver↔worker(s); nested driver graphs are P3.',\n )\n }\n const root = requireNode(roots[0] as string, 'root resolution')\n for (const edge of delegates) {\n if (edge.from !== root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} delegates from a non-root node — P0 executes one driver over ` +\n 'its workers (the 2-node cyclic case, star-generalized); deeper delegation is P3',\n )\n }\n }\n const analystIds = new Set<string>()\n const analystNodes = new Map<NodeId, GraphNode>()\n for (const edge of analyzes) {\n // Continuity is a delegates-edge axis ONLY: analysts (lens or node) are spawned by the\n // analyst-on-settle machinery, each run a fresh session over settled evidence — an analyzes\n // edge carrying continuity would silently mean nothing, so it is refused as data.\n if ((edge as { continuity?: unknown }).continuity !== undefined) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} carries continuity — analysts are spawned by the analyst ` +\n 'machinery (every analyst run is a fresh session over settled evidence), so ' +\n 'continuity is a delegates-edge axis only',\n )\n }\n // The runner's traversal ledger resolves a finding/steer back to its edge BY ANALYST ID\n // alone, so a second edge sharing an analyst would silently absorb the first edge's\n // traversals (last-registered wins). Multi-edge-per-analyst is not yet supported; refuse it\n // rather than mis-ledger it.\n if (analystIds.has(edge.analyst)) {\n throw new ValidationError(\n `runGraph: two analyzes edges share analyst '${edge.analyst}' — one analyzes edge per ` +\n 'analyst lens (traversals are ledgered by analyst id; a second edge would silently ' +\n \"absorb the first's). Register the lens under a second id for a second edge.\",\n )\n }\n analystIds.add(edge.analyst)\n // The analyst REFERENCE has two forms — a registry lens id or a graph node id — and the id\n // itself is what distinguishes them, so an id living in both is refused as ambiguous rather\n // than silently resolved by precedence.\n const analystNode = byId.get(edge.analyst)\n const inRegistry = analysts?.kinds.some((kind) => kind.id === edge.analyst) === true\n if (analystNode !== undefined && inRegistry) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is BOTH a graph node and a lens in ` +\n 'the analysts registry — the id alone distinguishes the two analyst forms, so this is ' +\n 'ambiguous; rename the node or register the lens under another id',\n )\n }\n if (analystNode !== undefined) {\n // The analyst-AGENT form. Oracle doctrine holds structurally: the analyst node can never\n // receive work — not from the root (a delegates edge to it is refused) and not by being\n // the root (the root delegates by definition).\n if (analystNode.id === root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} names the ROOT as its analyst — the root is the driver; ` +\n 'give the analyst its own node with no delegates edge pointing at it',\n )\n }\n if (delegatedTo.has(analystNode.id)) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} names node '${edge.analyst}' as its analyst, but that node ` +\n 'is a delegates target — oracle doctrine: an analyst is never delegated to. An ' +\n 'analyst NODE is legal only with NO delegates edge pointing at it; give the analyst ' +\n 'its own delegates-free node or pass a lens id from RunGraphOptions.analysts.',\n )\n }\n analystNodes.set(analystNode.id, analystNode)\n } else if (!analysts) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is not a graph node, and no ` +\n 'RunGraphOptions.analysts registry was provided to resolve it as a lens',\n )\n } else if (!inRegistry) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is neither a graph node nor in the ` +\n `analysts registry (known lenses: ${analysts.kinds.map((kind) => kind.id).join(', ') || 'none'})`,\n )\n }\n if (edge.over.length === 0) {\n throw new ValidationError(`runGraph: ${edgeId(edge)} must analyze at least one node`)\n }\n for (const over of edge.over) {\n requireNode(over, edgeId(edge))\n // Analysts observe SETTLED WORKERS, matched by profile name — the root drives and never\n // settles as a worker, so an edge over the root would silently never fire; refuse it.\n if (over === root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyzes the ROOT — analysts observe settled workers, and ` +\n 'the root never settles as one, so this edge would silently never fire; list ' +\n 'delegates-target nodes only',\n )\n }\n }\n requireNode(edge.to, edgeId(edge))\n }\n // Second pass, once every analyst NODE is known: an analyst run's settlement is a FINDING,\n // never a worker settle, so an analyzes edge OVER an analyst node would silently never fire —\n // refuse it rather than let it rot unobserved.\n for (const edge of analyzes) {\n for (const over of edge.over) {\n if (analystNodes.has(over)) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyzes '${over}', which is an analyst node — an analyst ` +\n 'run settles as a finding, never as a worker, so this edge would silently never ' +\n 'fire; analyst nodes are not analyzable',\n )\n }\n }\n }\n const workers = new Map<NodeId, GraphNode>()\n const delegatesByWorker = new Map<NodeId, Extract<GraphEdge, { kind: 'delegates' }>>()\n for (const edge of delegates) {\n if (delegatesByWorker.has(edge.to)) {\n throw new ValidationError(\n `runGraph: node '${edge.to}' is the target of two delegates edges — one delegation ` +\n 'directive per worker node (version the directive instead of forking the edge)',\n )\n }\n delegatesByWorker.set(edge.to, edge)\n workers.set(edge.to, requireNode(edge.to, edgeId(edge)))\n }\n // Every non-root node must be reachable by SOME edge, or it can never run. A worker node is\n // reached by its delegates edge; an analyst node by its analyzes edge (spawned on settle).\n for (const node of graph.nodes) {\n if (node.id !== root.id && !workers.has(node.id) && !analystNodes.has(node.id)) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has no delegates edge to it — an unreachable node never runs`,\n )\n }\n }\n return { root, workers, delegatesByWorker, analyzes, analystNodes }\n}\n\n// ── The runner ─────────────────────────────────────────────────────────────────\n\nconst byteLength = (text: string): number => Buffer.byteLength(text, 'utf8')\n\nfunction stringifyPayload(payload: unknown): string {\n if (typeof payload === 'string') return payload\n try {\n return JSON.stringify(payload) ?? String(payload)\n } catch {\n return String(payload)\n }\n}\n\n/**\n * Execute an {@link AgentGraph}. The root node becomes the supervisor (`supervise()` — the\n * execution core), each worker node is spawnable BY NODE ID (`spawn_agent` with\n * `profile: { name: '<node id>' }`; the node's canonical profile is pinned by 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 } = 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 const registry = opts.registry ?? kernelPromptRegistry()\n const validated = validateGraph(graph, registry, opts.analysts)\n const { root } = validated\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 if (!opts.backend && !opts.makeLeafAgent) {\n throw new ValidationError(\n 'runGraph: provide opts.backend (where nodes run) or opts.makeLeafAgent',\n )\n }\n return validated\n}\n\nexport function superviseAgentGraph(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): Promise<GraphResult> {\n const registry = opts.registry ?? kernelPromptRegistry()\n const { root, workers, delegatesByWorker, analyzes, analystNodes } = assertRunGraphAuthoring(\n graph,\n opts,\n brain,\n )\n const journal = opts.journal ?? new InMemorySpawnJournal()\n const blobs = opts.blobs ?? new InMemoryResultBlobStore()\n const runId =\n opts.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 // ── Ledger state ──\n const ledger: EdgeTraversal[] = []\n const journaled = new Set<EdgeTraversal>()\n const traversalCounts = new Map<string, number>()\n const exhausted = new Set<string>()\n // The subset of `exhausted` that REFUSED work. Only a delegates cap closes the spawn cycle, so\n // only it can be the reason a run ended winnerless — an analyzes cap refuses nothing.\n const exhaustedDelegates = new Set<string>()\n const journalWrites: Promise<void>[] = []\n let ledgerSeq = 0\n const appendJournal = (entry: EdgeTraversal, nodeIdForEvent: string): Promise<void> => {\n if (journaled.has(entry)) return Promise.resolve()\n journaled.add(entry)\n const write = journal.appendEvent(runId, {\n kind: 'edge',\n id: nodeIdForEvent,\n edge: { kind: entry.kind, from: entry.from, to: entry.to, directive: entry.directive },\n traversal: entry.traversal,\n outcome: entry.outcome,\n continuity: entry.continuity,\n bytes: entry.bytes,\n ...(entry.reason !== undefined ? { reason: entry.reason } : {}),\n seq: ledgerSeq++,\n at: new Date(now()).toISOString(),\n })\n journalWrites.push(write)\n return write\n }\n const record = (entry: Omit<EdgeTraversal, 'traversal'>, journalNow: boolean): EdgeTraversal => {\n const count = (traversalCounts.get(entry.edge) ?? 0) + 1\n traversalCounts.set(entry.edge, count)\n const row: EdgeTraversal = { ...entry, traversal: count }\n ledger.push(row)\n if (journalNow) void appendJournal(row, row.workerId ?? `graph:${row.to}`)\n return row\n }\n\n // ── Node pinning + delegates spawn traversals (the authorizeSpawn wrapper) ──\n // Pinning lives in `authorizeSpawn`, which the kernel runs BEFORE it decides whether a child is\n // a leaf or a nested supervisor. That is what lets a node declared `role: 'driver'` become a real\n // supervisor carrying its canonical profile: the kernel's `isDriver` reads the PINNED profile,\n // not the driver-authored `{ name }` stub. (It used to live in `makeWorkerAgent`, a leaf-only\n // seam, which made every node a leaf no matter what its profile declared — #965.)\n const nodeByWorkerId = new Map<string, NodeId>()\n const pendingByAssignment = new Map<string, EdgeTraversal>()\n type SpawnAuthorizationInput = Parameters<NonNullable<SuperviseOptions['authorizeSpawn']>>[0]\n const pinNode = (input: SpawnAuthorizationInput): AgentProfile => {\n const requested =\n typeof (input.profile as { name?: unknown } | undefined)?.name === 'string'\n ? (input.profile as { name: string }).name\n : undefined\n // An analyst-AGENT run: the coordination settle hook — never the driver; the marker is\n // authored by the runtime, not accepted from model arguments — spawns the analyst NODE.\n // Pin the node's canonical profile; the analysis directive travels as the TASK (composed by\n // the coordination layer with the settled worker's trace evidence), so nothing is appended\n // to the profile's instructions here. Its traversal is ledgered on the finding/steer it\n // produces, exactly like a registry analyst's.\n if (input.analyst !== undefined) {\n const analystNode = analystNodes.get(input.analyst)\n if (!analystNode || requested !== analystNode.id) {\n throw new ValidationError(\n `runGraph: analyst run for ${JSON.stringify(input.analyst)} does not name an ` +\n `analyst node of this graph (analyst nodes: ${[...analystNodes.keys()].join(', ') || 'none'})`,\n )\n }\n return analystNode.profile\n }\n const node = requested !== undefined ? workers.get(requested) : undefined\n if (!node) {\n throw new ValidationError(\n `runGraph: spawn_agent named profile ${JSON.stringify(requested)} which is not a worker ` +\n `node of this graph (nodes: ${[...workers.keys()].join(', ')}). Spawn by node id: ` +\n 'profile.name selects the node; the node profile itself is pinned by the graph.',\n )\n }\n const edge = delegatesByWorker.get(node.id) as Extract<GraphEdge, { kind: 'delegates' }>\n const id = edgeId(edge)\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const used = traversalCounts.get(id) ?? 0\n // The EFFECTIVE spawn mode the coordination layer resolved (per-call override, else this\n // edge's declared default, else fresh) — stamped on the row so the ledger states how each\n // hop continued, never how it was merely configured to.\n const spawnContinuity = input.continuity ?? 'fresh'\n if (used >= cap) {\n exhausted.add(id)\n exhaustedDelegates.add(id)\n record(\n {\n edge: id,\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: 'unpropagated',\n continuity: spawnContinuity,\n bytes: 0,\n reason: `traversal-cap-exhausted (max ${cap})`,\n },\n true,\n )\n throw new ValidationError(\n `runGraph: delegates edge ${id} exhausted its traversal cap (${cap}) — the ` +\n 'cyclic-graph backstop refused this spawn',\n )\n }\n const directiveText = registry.resolve(edge.directive).text\n const taskText = stringifyPayload(input.task)\n const bytes = byteLength(directiveText) + byteLength(taskText)\n const row = record(\n {\n edge: id,\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: bytes === 0 ? 'empty' : 'delivered',\n continuity: spawnContinuity,\n bytes,\n ...(bytes === 0 ? { reason: 'no directive text and no task payload' } : {}),\n },\n false,\n )\n pendingByAssignment.set(input.assignmentId, row)\n // The delegation directive is a STANDING instruction of this traversal: appended to the\n // node's canonical prompt instructions, so the worker runs under node profile + edge\n // directive, and the driver-authored profile contributes ONLY the node selection.\n return directiveText.length === 0\n ? node.profile\n : {\n ...node.profile,\n prompt: {\n ...(node.profile.prompt ?? {}),\n instructions: [\n ...((node.profile.prompt?.instructions as readonly string[] | undefined) ?? []),\n directiveText,\n ],\n },\n }\n }\n // The pre-journal gate (a bridge backend's route/admission check) must judge the profile that\n // will run, not the `{ name }` stub — otherwise every graph spawn over a bridge is refused\n // `model-route` before the graph ever pins it. This resolver is PURE: it answers \"which node\"\n // without ledgering, because the gate may refuse and nothing may be journaled for a refusal.\n const resolveSpawnProfile = (authored: AgentProfile): AgentProfile => {\n const requested = typeof authored.name === 'string' ? authored.name : undefined\n const node =\n (requested !== undefined ? workers.get(requested) : undefined) ??\n (requested !== undefined ? analystNodes.get(requested) : undefined)\n // Unknown names fall through to authorizeSpawn, which refuses them with the full message and\n // a ledger row; the gate just sees the stub and lets that later refusal speak.\n return node?.profile ?? authored\n }\n // Graph authority first, then the caller's: a product authorizing spawns sees the CANONICAL\n // node profile (what will actually run), never the driver's `{ name }` stub.\n const graphAuthorizeSpawn: NonNullable<SuperviseOptions['authorizeSpawn']> = (input) => {\n const pinned = pinNode(input)\n if (!opts.authorizeSpawn) return { profile: pinned }\n return opts.authorizeSpawn({ ...input, profile: pinned })\n }\n\n // ── Analyzes edges → analyst-on-settle routes with destinations ──\n // A LENS edge's directive wraps the findings for the recipient (so a driver-destined lens\n // route carries no directive — it becomes the driver brief below). A NODE edge's directive is\n // the analyst AGENT's task, so it always rides the route, wherever the findings go.\n const routes: Array<string | AnalyzeOnSettleRoute> = analyzes.map((edge) => {\n const analystNode = analystNodes.get(edge.analyst)\n if (analystNode) {\n return {\n kind: edge.analyst,\n over: edge.over,\n agent: analystNode.profile,\n directive: registry.resolve(edge.directive).text,\n ...(edge.to === root.id ? {} : { to: edge.to }),\n }\n }\n return edge.to === root.id\n ? { kind: edge.analyst, over: edge.over }\n : {\n kind: edge.analyst,\n over: edge.over,\n to: edge.to,\n directive: registry.resolve(edge.directive).text,\n }\n })\n // Driver-destined analyzes findings are standing knowledge for the ROOT: the findings arrive\n // as bus events. For a lens edge the directive tells the driver what to do with them; for a\n // node edge the directive already went to the analyst agent as its task.\n const driverAnalyzesBriefs = analyzes\n .filter((edge) => edge.to === root.id)\n .map((edge) =>\n analystNodes.has(edge.analyst)\n ? `Findings from analyst '${edge.analyst}' (a tool-equipped analyst agent node, over: ` +\n `${edge.over.join(', ')}) will arrive as finding events.`\n : `Findings from analyst '${edge.analyst}' (over: ${edge.over.join(', ')}) will arrive as ` +\n `finding events.\\n${registry.resolve(edge.directive).text}`,\n )\n\n // ── Edge continuity defaults, threaded to the spawn tool by node id (= profile name) ──\n const continuityByProfile: Record<string, ContinuityMode> = {}\n for (const [nodeId, edge] of delegatesByWorker) {\n if (edge.continuity !== undefined) continuityByProfile[nodeId] = edge.continuity\n }\n\n // ── The driver graph brief: which nodes it may spawn, by exact name ──\n const workerLines = [...workers.values()].map((node) => {\n const edge = delegatesByWorker.get(node.id) as Extract<GraphEdge, { kind: 'delegates' }>\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const description =\n typeof node.profile.description === 'string' && node.profile.description.length > 0\n ? ` — ${node.profile.description}`\n : ''\n const continuityNote =\n edge.continuity === 'resume'\n ? \"; continuity: resume — each spawn after the first re-attaches to this node's latest \" +\n 'settled session (spawn again to continue it; steer while it is live)'\n : ''\n return `- '${node.id}'${description} (delegation cap: ${cap} traversals${continuityNote})`\n })\n const graphBrief = [\n 'AGENT GRAPH: you are the driver node of a fixed topology. You may spawn ONLY these worker',\n \"nodes, by EXACT name (spawn_agent with profile: { name: '<node id>' }; the node's full\",\n 'profile is pinned by the graph — any other profile fields you author are ignored):',\n ...workerLines,\n ...(driverAnalyzesBriefs.length > 0 ? ['', ...driverAnalyzesBriefs] : []),\n ].join('\\n')\n const rootProfile: AgentProfile = {\n ...root.profile,\n prompt: {\n ...(root.profile.prompt ?? {}),\n instructions: [\n ...((root.profile.prompt?.instructions as readonly string[] | undefined) ?? []),\n graphBrief,\n ],\n },\n }\n\n // ── Steer + finding observation (delegates steers, analyzes traversals) ──\n // The filter seam: when the caller's authorizeMessage NARROWS an instruction, the delivered\n // bytes differ from the composed bytes — that steer traversal is `stripped` (the VB incident:\n // authored steering silently replaced by boilerplate, byte-indistinguishable downstream).\n const strippedByDigest = new Map<string, { composedBytes: number }>()\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 authorizeMessage: NonNullable<SuperviseOptions['authorizeMessage']> = (input) => {\n if (!opts.authorizeMessage) return { instruction: input.instruction }\n const decision = opts.authorizeMessage(input)\n if (decision.instruction !== input.instruction) {\n strippedByDigest.set(canonicalCandidateDigest(decision.instruction), {\n composedBytes: byteLength(input.instruction),\n })\n }\n return decision\n }\n\n const routedAnalyzesByAnalyst = new Map<string, Extract<GraphEdge, { kind: 'analyzes' }>>()\n const driverAnalyzesByAnalyst = new Map<string, Extract<GraphEdge, { kind: 'analyzes' }>>()\n for (const edge of analyzes) {\n ;(edge.to === root.id ? driverAnalyzesByAnalyst : routedAnalyzesByAnalyst).set(\n edge.analyst,\n edge,\n )\n }\n const analyzesCapReached = (edge: Extract<GraphEdge, { kind: 'analyzes' }>): boolean => {\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const used = traversalCounts.get(edgeId(edge)) ?? 0\n if (used < cap) return false\n exhausted.add(edgeId(edge))\n return true\n }\n const ledgerAnalyzes = (\n edge: Extract<GraphEdge, { kind: 'analyzes' }>,\n outcome: EdgeDeliveryOutcome,\n bytes: number,\n reason: string | undefined,\n workerId: string | undefined,\n ): void => {\n const capped = analyzesCapReached(edge)\n record(\n {\n edge: edgeId(edge),\n kind: 'analyzes',\n from: edge.over.join('+'),\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: capped ? 'unpropagated' : outcome,\n // Every analyzes traversal is a mid-run delivery into an already-live recipient (a\n // routed steer leg, or the finding reaching the live driver) — never a spawn.\n continuity: 'steer',\n bytes,\n ...(capped\n ? {\n reason: `traversal-cap-exhausted (max ${edge.maxTraversals ?? defaultEdgeTraversalCap})`,\n }\n : reason !== undefined\n ? { reason }\n : {}),\n ...(workerId !== undefined ? { workerId } : {}),\n },\n true,\n )\n }\n\n const onCoordinationEvent = async (\n _context: unknown,\n _eventId: unknown,\n recordEnvelope: { readonly event: CoordinationEvent },\n ): Promise<void> => {\n const event = recordEnvelope.event\n if (event.type === 'finding') {\n // A routed edge's traversal is ledgered on its STEER (the delivery); the finding event is\n // its audit copy. A driver-destined edge's traversal IS the finding reaching the bus.\n const edge = driverAnalyzesByAnalyst.get(event.finding.analyst)\n if (!edge) return\n const sourceNode = nodeByWorkerId.get(event.finding.fromWorker)\n if (sourceNode === undefined || !edge.over.includes(sourceNode)) return\n // Absent findings (the analyst returned `undefined` — the producer omits the key so the\n // event stays digestable) contribute ZERO bytes, never the text \"undefined\".\n const findingsText =\n event.finding.findings === undefined ? '' : stringifyPayload(event.finding.findings)\n const directiveBytes = byteLength(registry.resolve(edge.directive).text)\n const empty = findingsText.length === 0\n ledgerAnalyzes(\n edge,\n empty ? 'empty' : 'delivered',\n directiveBytes + byteLength(findingsText),\n empty ? 'analyst returned no findings' : undefined,\n event.finding.fromWorker,\n )\n return\n }\n if (event.type === 'steer') {\n const down = event.down\n if (event.analyst !== undefined) {\n const edge = routedAnalyzesByAnalyst.get(event.analyst)\n if (!edge) return\n ledgerAnalyzes(\n edge,\n down.delivered ? 'delivered' : 'unpropagated',\n byteLength(down.instruction),\n down.delivered ? undefined : down.outcome,\n down.toWorker,\n )\n return\n }\n // A driver-authored steer to a live worker node is a delegates traversal too — the\n // mid-run leg of the same edge (the leg the motivating incident lost).\n const nodeId = nodeByWorkerId.get(down.toWorker)\n if (nodeId === undefined) return\n const edge = delegatesByWorker.get(nodeId)\n if (!edge) return\n const stripped = strippedByDigest.get(down.instructionDigest)\n record(\n {\n edge: edgeId(edge),\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: !down.delivered ? 'unpropagated' : stripped ? 'stripped' : 'delivered',\n // The mid-run leg of the edge: a delivery into the LIVE worker, never a spawn.\n continuity: 'steer',\n bytes: byteLength(down.instruction),\n ...(!down.delivered\n ? { reason: down.outcome }\n : stripped\n ? { reason: `authorization narrowed ${stripped.composedBytes} composed bytes` }\n : {}),\n workerId: down.toWorker,\n },\n true,\n )\n }\n }\n\n // ── Spawn-hook: bind ledger rows to concrete worker ids, then journal them ──\n const graphHooks = {\n onEvent: (event: {\n target?: string\n phase?: string\n payload?: unknown\n }): void | Promise<void> => {\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 const pending = pendingByAssignment.get(payload.assignmentId)\n if (!pending) return\n pendingByAssignment.delete(payload.assignmentId)\n const bound: EdgeTraversal = { ...pending, workerId: payload.childId }\n ledger[ledger.indexOf(pending)] = bound\n nodeByWorkerId.set(payload.childId, bound.to)\n return appendJournal(bound, payload.childId)\n },\n }\n const hooks = composeRuntimeHooks(graphHooks, opts.hooks)\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 // Every forwarded option the caller set, including the ones nobody thought to list here.\n // `backend` rides along: the kernel derives every authorized LEAF from it, under the graph's\n // pinning. The root driver stays an explicit `driverBackend` choice: `rootDriverFromBackend:\n // false` stops supervise() defaulting one from the other, so where workers run never selects\n // where the root runs (the axis split every graph caller relies on).\n ...forwardedSuperviseOptions(opts),\n rootDriverFromBackend: false,\n // Graph-owned values come after the spread: the graph, not the caller, decides these.\n budget: graph.budget,\n deliverable: graph.deliverable,\n authorizeSpawn: graphAuthorizeSpawn,\n resolveSpawnProfile,\n ...(opts.makeLeafAgent ? { makeLeafAgent: opts.makeLeafAgent } : {}),\n journal,\n blobs,\n runId,\n hooks,\n onCoordinationEvent,\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 ...(routes.length > 0\n ? { analyzeOnSettle: routes, ...(opts.analysts ? { analysts: opts.analysts } : {}) }\n : {}),\n ...(Object.keys(continuityByProfile).length > 0 ? { continuityByProfile } : {}),\n authorizeMessage,\n } satisfies SuperviseOptions\n const result =\n brain === undefined\n ? await supervise(rootProfile, graphTask(graph, root), superviseOptions)\n : await superviseWithTestBrain(rootProfile, graphTask(graph, root), {\n ...superviseOptions,\n brain,\n })\n\n // A spawn row is PROVISIONAL until the `agent.spawn` hook (fired synchronously once a worker\n // exists) binds it to a live worker id. A row still unbound here means the factory ran but no\n // NEW worker went live: the spawn was refused after the factory (identity conflict, runtime\n // floor) or a keyed re-spawn deduplicated to an already-completed result (prepare() runs the\n // factory, no hook fires). Both state the same truth every unpropagated row states — the\n // directive never reached a live worker — so rewrite rather than mint a new outcome. Then\n // settle every journal write, so the ledger's journal twin is complete when this returns.\n for (const pending of pendingByAssignment.values()) {\n const refused: EdgeTraversal = {\n ...pending,\n outcome: 'unpropagated',\n bytes: 0,\n reason: `no-live-worker-bound (spawn refused after the factory, or a keyed re-spawn deduplicated to a completed result; ${pending.bytes} composed bytes never crossed)`,\n }\n ledger[ledger.indexOf(pending)] = refused\n await appendJournal(refused, `graph:${refused.to}`)\n }\n pendingByAssignment.clear()\n await Promise.all(journalWrites)\n\n const exhaustedEdges = Object.freeze([...exhausted])\n const frozenLedger = Object.freeze(ledger.map((row) => Object.freeze({ ...row })))\n // A LIFECYCLE ending (caller abort, exhausted budget) 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' || result.reason === 'budget-exhausted')\n if (result.kind !== 'winner' && !lifecycleEnded && exhaustedDelegates.size > 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(Object.freeze([...exhaustedDelegates]), frozenLedger, result)\n }\n return { result, ledger: frozenLedger, exhaustedEdges, runId }\n }\n\n return start()\n}\n\n/** The root task: the graph's own framing. The deliverable (mandatory) is the termination; the\n * task names what the topology exists to produce. */\nfunction graphTask(graph: AgentGraph, root: GraphNode): string {\n const describe = graph.deliverable.describe\n return (\n describe ?? `Deliver the graph's deliverable by driving your worker nodes (root: '${root.id}').`\n )\n}\n"],"mappings":";;;;;;;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