@tangle-network/agent-runtime 0.348.1 → 0.350.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-BEGalhOL.js → activation-CfJMyzEs.js} +12 -14
- package/dist/{activation-BEGalhOL.js.map → activation-CfJMyzEs.js.map} +1 -1
- package/dist/{activation-NQZP_mdI.d.ts → activation-DyiHrTlS.d.ts} +2 -24
- package/dist/agent.d.ts +8 -12
- package/dist/agent.js +9 -12
- package/dist/agent.js.map +1 -1
- package/dist/{analyst-loop-DZw5QWT9.js → analyst-loop-BZvXCDKy.js} +2 -3
- package/dist/{analyst-loop-DZw5QWT9.js.map → analyst-loop-BZvXCDKy.js.map} +1 -1
- package/dist/analyst-loop.d.ts +3 -5
- package/dist/analyst-loop.js +1 -2
- package/dist/{bundle-DKQtOO9d.js → bundle-Ze8pd07a.js} +3 -4
- package/dist/{bundle-DKQtOO9d.js.map → bundle-Ze8pd07a.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +13 -33
- package/dist/candidate-execution/index.js +16 -18
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/{coordination-manager-Bm6leXc6.js → coordination-manager-BkVfWlMz.js} +101 -132
- package/dist/coordination-manager-BkVfWlMz.js.map +1 -0
- package/dist/{delegate-Cp5-PsaX.js → delegate-DgEie4ad.js} +19 -21
- package/dist/delegate-DgEie4ad.js.map +1 -0
- package/dist/durable.d.ts +13 -23
- package/dist/durable.js +48 -43
- package/dist/durable.js.map +1 -1
- package/dist/{errors-DodWX-cb.js → errors-wuhGvpE3.js} +2 -3
- package/dist/{errors-DodWX-cb.js.map → errors-wuhGvpE3.js.map} +1 -1
- package/dist/{graph-CE_pzU31.js → graph-Cx0FhKSE.js} +192 -15
- package/dist/graph-Cx0FhKSE.js.map +1 -0
- package/dist/{improve-wT11zteg.js → improve-i0HU1-aa.js} +35 -53
- package/dist/{improve-wT11zteg.js.map → improve-i0HU1-aa.js.map} +1 -1
- package/dist/{improvement-adapter-sIthWkcN.d.ts → improvement-adapter-D5GRU1eY.d.ts} +2 -6
- package/dist/index.d.ts +41 -89
- package/dist/index.js +43 -61
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +39 -59
- package/dist/intelligence.js +23 -33
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +5 -5
- package/dist/kernel.js +11 -11
- package/dist/{loop-runner-CZzeeJTG.js → loop-runner-BwN9MhdP.js} +5 -6
- package/dist/{loop-runner-CZzeeJTG.js.map → loop-runner-BwN9MhdP.js.map} +1 -1
- package/dist/{loop-runner-CY5HHhtR.d.ts → loop-runner-DvfOXVx9.d.ts} +3 -5
- package/dist/loop-runner-bin.d.ts +5 -8
- package/dist/loop-runner-bin.js +2 -3
- package/dist/mcp/bin.js +6 -8
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +8 -18
- package/dist/mcp/index.js +17 -25
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/memory-bin.js +4 -6
- package/dist/mcp/memory-bin.js.map +1 -1
- package/dist/{model-policy-CyCUwHed.js → model-policy-GSxWwP-b.js} +11 -13
- package/dist/model-policy-GSxWwP-b.js.map +1 -0
- package/dist/placement.d.ts +12 -14
- package/dist/placement.js +1 -2
- package/dist/platform.d.ts +7 -13
- package/dist/platform.js +3 -6
- package/dist/platform.js.map +1 -1
- package/dist/{prepare-TEEHSJwq.js → prepare-DE8TQnLu.js} +49 -69
- package/dist/{prepare-TEEHSJwq.js.map → prepare-DE8TQnLu.js.map} +1 -1
- package/dist/{profile-6OLpbjvV.js → profile-CAhZDW2T.js} +58 -92
- package/dist/profile-CAhZDW2T.js.map +1 -0
- package/dist/{profile-materialization-bPm0gGLO.d.ts → profile-materialization-BRY22Oh8.d.ts} +1 -3
- package/dist/profiles.d.ts +25 -12
- package/dist/profiles.js +52 -11
- package/dist/profiles.js.map +1 -1
- package/dist/{protected-model-port-DVVh-hEk.d.ts → protected-model-port-IKqhTypD.d.ts} +2 -14
- package/dist/{protected-redaction-DFCeo4vg.js → protected-redaction-DilFZch5.js} +2 -3
- package/dist/{protected-redaction-DFCeo4vg.js.map → protected-redaction-DilFZch5.js.map} +1 -1
- package/dist/{provision-supervisor-CC0HdOHo.js → provision-supervisor-Bde_FF0R.js} +11 -15
- package/dist/{provision-supervisor-CC0HdOHo.js.map → provision-supervisor-Bde_FF0R.js.map} +1 -1
- package/dist/{record-events-D93DkpAx.js → record-events-B2GUgYdz.js} +12 -14
- package/dist/{record-events-D93DkpAx.js.map → record-events-B2GUgYdz.js.map} +1 -1
- package/dist/{run-cancellation-CzFhQGMa.js → run-cancellation-BLy_Zz-w.js} +6 -7
- package/dist/{run-cancellation-CzFhQGMa.js.map → run-cancellation-BLy_Zz-w.js.map} +1 -1
- package/dist/{runtime-B_40dXlF.js → runtime-6Ec9sHRe.js} +833 -215
- package/dist/runtime-6Ec9sHRe.js.map +1 -0
- package/dist/{runtime-hooks-tXpAarhW.js → runtime-hooks-CsW2pfFk.js} +2 -3
- package/dist/{runtime-hooks-tXpAarhW.js.map → runtime-hooks-CsW2pfFk.js.map} +1 -1
- package/dist/{runtime-hooks-nsqxSUFL.d.ts → runtime-hooks-ZQqPw-0g.d.ts} +1 -3
- package/dist/{sandbox-profile-compat-_fEtHPCj.js → sandbox-profile-compat-BxMQ1VXv.js} +62 -44
- package/dist/sandbox-profile-compat-BxMQ1VXv.js.map +1 -0
- package/dist/{search-executor-COd2F2wp.js → search-executor-B7g_5Wjl.js} +12 -17
- package/dist/search-executor-B7g_5Wjl.js.map +1 -0
- package/dist/{server-BGB4R4wQ.js → server-fvEMwGMQ.js} +19 -30
- package/dist/{server-BGB4R4wQ.js.map → server-fvEMwGMQ.js.map} +1 -1
- package/dist/{structural-rollout-Wl_rCuzM.js → structural-rollout-B86bSixU.js} +69 -70
- package/dist/structural-rollout-B86bSixU.js.map +1 -0
- package/dist/{substrate-CGDFTSRh.js → substrate-Db2pp6y3.js} +2 -3
- package/dist/{substrate-CGDFTSRh.js.map → substrate-Db2pp6y3.js.map} +1 -1
- package/dist/{supervise-BUOeThuB.js → supervise-CaeZcgAW.js} +615 -203
- package/dist/supervise-CaeZcgAW.js.map +1 -0
- package/dist/{supervisor-DDy0aEtR.js → supervisor-C1OePYE-.js} +526 -642
- package/dist/supervisor-C1OePYE-.js.map +1 -0
- package/dist/{task-queue-0fKkoweu.d.ts → task-queue-kefGy79U.d.ts} +1 -3
- package/dist/task-queue.d.ts +1 -1
- package/dist/task-queue.js +1 -2
- package/dist/testing.d.ts +8 -16
- package/dist/testing.js +241 -244
- package/dist/testing.js.map +1 -1
- package/dist/tool-loop.d.ts +16 -19
- package/dist/tool-loop.js +2 -3
- package/dist/{tool-server-XV4aJwoQ.js → tool-server-CwuYeW_Z.js} +3 -4
- package/dist/{tool-server-XV4aJwoQ.js.map → tool-server-CwuYeW_Z.js.map} +1 -1
- package/dist/{top-snapshot-CflmaDgk.js → top-snapshot-ChwpTr7A.js} +4 -5
- package/dist/{top-snapshot-CflmaDgk.js.map → top-snapshot-ChwpTr7A.js.map} +1 -1
- package/dist/tui/bin.js +7 -9
- package/dist/tui/bin.js.map +1 -1
- package/dist/tui/index.d.ts +3 -5
- package/dist/tui/index.js +2 -2
- package/dist/{types-hc4cmSc7.d.ts → types-Fowuwdz2.d.ts} +555 -503
- package/dist/{types-Cwrea-bU.d.ts → types-qsqfyQoY.d.ts} +1 -3
- package/dist/workspace-store/index.d.ts +12 -22
- package/dist/workspace-store/index.js +4 -7
- package/dist/workspace-store/index.js.map +1 -1
- package/dist/{workspace-streams-BiS4ABah.d.ts → workspace-streams-Dq2Fzk3c.d.ts} +1 -11
- package/package.json +25 -25
- package/skills/agent-graphs/SKILL.md +19 -4
- package/skills/be-ambitious/SKILL.md +46 -0
- package/skills/graph-designer/SKILL.md +15 -2
- package/skills/profile-authoring/SKILL.md +1 -1
- package/dist/coordination-manager-Bm6leXc6.js.map +0 -1
- package/dist/delegate-Cp5-PsaX.js.map +0 -1
- package/dist/graph-CE_pzU31.js.map +0 -1
- package/dist/model-policy-CyCUwHed.js.map +0 -1
- package/dist/profile-6OLpbjvV.js.map +0 -1
- package/dist/runtime-B_40dXlF.js.map +0 -1
- package/dist/sandbox-profile-compat-_fEtHPCj.js.map +0 -1
- package/dist/search-executor-COd2F2wp.js.map +0 -1
- package/dist/structural-rollout-Wl_rCuzM.js.map +0 -1
- package/dist/supervise-BUOeThuB.js.map +0 -1
- package/dist/supervisor-DDy0aEtR.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"delegate-Cp5-PsaX.js","names":[],"sources":["../src/runtime/supervise/authoring.ts","../src/runtime/supervise/delegate.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions (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'\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_worker` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n 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: an explicit profile-authoring instruction, never an implicit Runtime\n * policy. Editing this text changes how a profile designs the descendants it spawns. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_worker with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.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 ' • tools.agent_runtime_coordination_spawn_worker: true ONLY when this child should author and drive descendants. Add only the other agent_runtime_coordination_<verb> tools it will call, such as observe_agent or steer_agent.',\n ' • A child with spawn_worker MUST carry this complete profile-authoring instruction as an immutable resources.skills entry with resources.failOnError: true, so it can author its own descendants from the same contract.',\n ' • metadata may describe the work, but it never grants recursion or selects a Runtime execution path.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n '3. End your turn while your workers run: Runtime wakes you with each settled worker. A settlement says valid:true only if the deployable check passed.',\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n \"5. read_journal to re-read YOUR OWN record before you decide the next move: every spawn you made, every settle, every question and answer, every steer, every analyst finding — oldest first, this node only, including what you did before a restart. Use it to see what you already tried instead of trying it again. It is paged: pass the returned nextRow as the next call's sinceRow, narrow with kinds, and raise limit/maxBytes only as far as you will actually read. A truncated:true page means a bound cut it short — keep paging before you conclude you have read everything.\",\n '6. AUTHOR YOUR OWN LENS when the questions you can already ask of a settled trace do not cover the failure you are chasing: define_analyst takes an id, a description, an area, the question in your own words, the instructions for answering it with trace evidence, and the smallest toolGroup that can answer it (model is the seat it runs on; omit it for the run default). It is DATA, never code. Then run_analyst it on any settled worker like a lens the run shipped with, and read the finding. list_analysts shows what you have. Define a lens when you need a different question asked — not a second copy of a question already on the menu.',\n '7. EVERY refusal you get back carries a `reason` naming the exact unmet condition. Read it and change that condition — a spawn refused for budget-exhausted needs a smaller budget or the refund of a settled worker, an invalid-profile needs the named field fixed, a submit_result refused because the check THREW is a broken check to report, not a result to resubmit. Never repeat a call that was refused without changing what it was refused for.',\n '8. ask_parent ONLY when you genuinely cannot decide, and then READ ITS OUTCOME. \"queued-for-parent\" means an inbox above you now holds the question. \"no-parent\" means no inbox above you is configured to receive it: the question is still on the run record for anyone watching, but nothing will route an answer back to you, so do not block. Decide it with answer_question, or answer_question with deferReason to record that it stays open, and carry on — a blocking question left undecided also refuses your stop.',\n '9. Once the work is delivered, end your turn with nothing left running.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// receives in its next wake — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** 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","/**\n *\n * `delegate` — the one generic delegation verb. You hand it an INTENT (what you want done) and it\n * hands that intent to a default AUTHORING supervisor: a router-brained supervisor whose standing\n * instruction is `supervisorInstructions()` (the authoring-agent-profiles skill). The supervisor\n * DECOMPOSES the intent and AUTHORS the worker profile it needs per sub-task — there is NO hardcoded\n * coder/researcher profile here. That is the whole point: `delegate('fix the failing test', …)` and\n * `delegate('research X and cite sources', …)` route through the SAME front door; the supervisor\n * writes a code-shaped or research-shaped worker on its own.\n *\n * It is a thin wrapper over `supervise()` — the one front door — so the conserved-budget pool, the\n * completion oracle (`deliverable`), the coordination toolbox, and equal-compute accounting all come\n * for free; nothing is hand-rolled. The result is `supervise()`'s `SupervisedResult` returned\n * UNCHANGED, so its `spentTotal` (`{ iterations, tokens, usd, ms }`) rides straight back to the\n * caller on BOTH paths — a `winner` carries the delivered worker's spend, a `no-winner` carries the\n * spend incurred before it failed. That cost channel means a `delegate()` caller always learns what\n * the delegation actually spent.\n *\n * @experimental\n */\n\nimport { ConfigError } from '../../errors'\nimport type { RouterTransportConfig } from '../router-http-transport'\nimport type { DeliverableSpec } from './completion-gate'\nimport type { ExecutorConfig } from './runtime'\nimport { supervise } from './supervise'\nimport type { SupervisorProfile } from './supervisor-agent'\nimport type { Budget, SupervisedResult } from './types'\n\n/** The conserved pool a `delegate()` call applies when the caller does not pass its own `budget`.\n * A modest token ceiling + a small iteration ceiling — generous enough for a few-worker decompose,\n * bounded enough that an unsupervised intent cannot run away. Callers override via `opts.budget`. */\nexport const defaultDelegateBudget: Budget = { maxIterations: 50, maxTokens: 200_000 }\n\n/** Inputs to {@link delegate}. The intent is the first positional arg; everything here is optional\n * with explicit execution identity, so the common call names one exact supervisor profile. */\nexport interface DelegateOptions<Out = unknown> {\n /** The completion oracle (settled ⟺ delivered) the authored workers settle against. Strongly\n * recommended — without it the supervisor trusts a worker's self-report. For a code intent,\n * `patchDelivered()` is the canonical example; for a free-form answer, a content check. */\n readonly deliverable?: DeliverableSpec<Out>\n /** WHERE the authored workers run — the worker-execution backend (`router-tools` / `sandbox` /\n * `cli-worktree` / …). The supervisor authors the worker PROFILE; this is the substrate it runs\n * on. Provide this OR `makeWorkerAgent`-style wiring through `supervise()` is unavailable. */\n readonly backend?: ExecutorConfig\n /** The conserved compute pool for the whole delegation. Defaults to {@link defaultDelegateBudget}. */\n readonly budget?: Budget\n /** Exact executable authoring supervisor. Model, prompt, harness, and provider live here. */\n readonly supervisorProfile: SupervisorProfile\n /** Router endpoint/auth for a `cli-base` supervisor; contains no behavioral settings. */\n readonly router: RouterTransportConfig\n /** Restrict the run to this subset of models (forwarded to `supervise()`). */\n readonly allowedModels?: readonly string[]\n readonly runId?: string\n}\n\n/**\n * Delegate an INTENT to a default authoring supervisor and return its `SupervisedResult` unchanged.\n *\n * The supervisor authors + spawns whatever worker the intent needs over the conserved-budget pool;\n * `result.spentTotal` reports what the whole delegation actually cost. A `winner` result carries the\n * authored worker's delivered output; a `no-winner` result names why (never a fabricated success).\n */\nexport async function delegate<Out = unknown>(\n intent: string,\n opts: DelegateOptions<Out>,\n): Promise<SupervisedResult<Out>> {\n if (typeof intent !== 'string' || intent.trim().length === 0) {\n throw new ConfigError('delegate: `intent` must be a non-empty string')\n }\n return supervise(opts.supervisorProfile, intent, {\n budget: opts.budget ?? defaultDelegateBudget,\n ...(opts.backend ? { backend: opts.backend } : {}),\n ...(opts.deliverable ? { deliverable: opts.deliverable as DeliverableSpec<unknown> } : {}),\n router: opts.router,\n ...(opts.allowedModels ? { allowedModels: opts.allowedModels } : {}),\n ...(opts.runId ? { runId: opts.runId } : {}),\n }) as Promise<SupervisedResult<Out>>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,kBAAkB,KAAsC;CACtE,MAAM,SAAS,mBAAmB,UAAU,GAAG;CAC/C,IAAI,CAAC,OAAO,SAAS,OAAO;CAC5B,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;;;AAIA,SAAgB,uBAAuB,MAAkC;CACvE,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;E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AU,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;;;;;;;;;;;;;;;;;;;;;;;;;;AC5MA,MAAa,wBAAgC;CAAE,eAAe;CAAI,WAAW;AAAQ;;;;;;;;AA+BrF,eAAsB,SACpB,QACA,MACgC;CAChC,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,CAAC,CAAC,WAAW,GACzD,MAAM,IAAI,YAAY,+CAA+C;CAEvE,OAAO,UAAU,KAAK,mBAAmB,QAAQ;EAC/C,QAAQ,KAAK,UAAU;EACvB,GAAI,KAAK,UAAU,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;EAChD,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,YAAwC,IAAI,CAAC;EACxF,QAAQ,KAAK;EACb,GAAI,KAAK,gBAAgB,EAAE,eAAe,KAAK,cAAc,IAAI,CAAC;EAClE,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC5C,CAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"graph-CE_pzU31.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/maps/routes traversal lands in an EDGE LEDGER\n * (`delivered | stripped | empty | unpropagated | failed`, with byte counts), in memory on\n * the result AND as `edge` events in the run journal. The motivating incident: a filter\n * silently replaced 1,700-char steering with 241 chars of boilerplate for three rounds and\n * NO artifact said so — an unobservable edge cannot be trusted and its directive cannot be\n * optimized.\n * 3. **Directives as data** — edge text lives in the prompt registry (`<surface>/v<n>`), so every\n * edge is a versioned optimization target, never prose hardcoded in a builder function.\n * 4. **Per-edge traversal caps** — the cyclic-graph backstop. A delegates edge whose cap is\n * exhausted REFUSES further traversals (fail loud), so a cycle cannot spin the pool dry.\n * 5. **Continuity as data** — a delegates edge may declare `continuity: 'resume'`, so each spawn\n * after the node's first re-attaches to its latest SETTLED session (the spawn context hands\n * the executor seam `resume: { ofWorker, sequence }`; the kernel keeps identity, ordering,\n * ledger truth, and the one conserved pool). Every ledger row states how its hop continued:\n * `'fresh' | 'resume'` for spawns, `'steer'` for mid-run deliveries — fresh respawns, session\n * resumes, and live steers are all plain data, each a ledgered fact.\n * 6. **Fan-out over a run-time list** — a `maps` edge takes the array a JSON pointer selects in a\n * node's settled result and runs one item per element, then hands the ordered results to a\n * join node. The runtime spawns every item and the join when the source settles, so the\n * driver spends no model turn on them; each item is a spawn through the same authorized path,\n * reserving from the same conserved pool, and every expansion, item and join is a ledger row.\n * 7. **Flow graphs** — with `entry` set, no node is a root: Runtime spawns the entries and fires\n * `routes` edges on each settle (`graph-flow.ts`), so a fixed order, a branch, a bounded repair\n * loop and a stop rule are graph data. The root manager is Runtime's own and never calls a\n * model; every entry and route spawn takes the same authorized path a map item takes.\n *\n * ORACLES ARE ENVIRONMENT, NEVER WORKERS. Graders/verifiers must not be spawnable in the graph —\n * a delegates edge to them leaks the rubric. An `analyzes` edge names its analyst in one of two\n * forms: a LENS id from the environment's registry (a pure function over trace evidence), or the\n * id of a graph NODE — a tool-equipped analyst AGENT spawned on each matching settle with the\n * node's pinned profile, whose settle output IS the findings. Either way the oracle doctrine\n * holds: an analyst node can never be a delegates target (refused loudly), so no driver can hand\n * it work, and an id living in both the registry and the nodes is refused as ambiguous.\n *\n * @experimental\n */\n\nimport { resolve } from 'node:path'\nimport { type AgentProfile, canonicalCandidateDigest } from '@tangle-network/agent-interface'\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/in-memory-spawn-stores'\nimport { FileSpawnJournal } from '../../durable/spawn-journal/journal-store'\nimport { FileResultBlobStore } from '../../durable/spawn-journal/result-blob-store'\nimport { ConfigError, ValidationError } from '../../errors'\nimport type { AnalystRegistry } from '../../mcp/tools/coordination-analysts'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination-contracts'\nimport type { MapItemFailurePolicy } from '../../mcp/tools/coordination-map-contracts'\nimport type { ContinuityMode } from '../../mcp/tools/coordination-messages'\nimport type {\n GateDecision,\n GateDecisionRecord,\n GateRequest,\n RouteGate,\n RouteWhen,\n} from '../../mcp/tools/coordination-route-contracts'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport { harnessRunsAgent } from '../harness-role'\nimport type { ToolLoopChat } from '../tool-loop'\nimport type { DeliverableSpec } from './completion-gate'\nimport { runtimeFlowBrain } from './flow-brain'\nimport {\n createFlowRun,\n flowRootProfile,\n GraphRouteError,\n journaledGateDecider,\n routeFlowOf,\n validateFlowGraph,\n} from './graph-flow'\nimport { createGraphOverlay } from './graph-overlay'\nimport {\n graphRootProfile,\n type RootValidatedGraph,\n type ValidatedGraph,\n validateGraphTopology,\n} from './graph-topology'\nimport { kernelPromptRegistry, type PromptHandle, type PromptRegistry } from './prompt-registry'\nimport { withRunContext } from './run-context'\nimport {\n profileGuidanceComposer,\n type SuperviseOptions,\n supervise,\n superviseWithTestBrain,\n} from './supervise'\nimport type { Budget, NodeId, ResultBlobStore, SpawnJournal, SupervisedResult } from './types'\n\nexport type { MapItemFailurePolicy } from '../../mcp/tools/coordination-map-contracts'\nexport type {\n GateDecision,\n GateRequest,\n JsonScalar,\n RouteGate as GraphGate,\n RouteMatch,\n RouteWhen,\n} from '../../mcp/tools/coordination-route-contracts'\nexport { GraphRouteError } from './graph-flow'\nexport { defaultEdgeTraversalCap } from './graph-topology'\n\n// ── The algebra ────────────────────────────────────────────────────────────────\n\n/** A graph node: an id and a canonical `AgentProfile`. The profile is the ONLY way a node is\n * described — its `prompt.systemPrompt` is the standing role (the 0.117 canonical resolution;\n * never a legacy top-level-only reduction), its tools/mcp/resources are its capabilities. */\nexport interface GraphNode {\n readonly id: NodeId\n readonly profile: AgentProfile\n}\n\nexport type GraphEdge =\n /** Work flows down. The delegation directive is DATA → versionable, sweepable, optimizable.\n * Each spawn of `to` by `from` — and each mid-run steer from `from` to a live `to` worker —\n * is one traversal. */\n | {\n readonly kind: 'delegates'\n readonly from: NodeId\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Cyclic-graph backstop: traversals beyond this REFUSE (fail loud). Default\n * {@link defaultEdgeTraversalCap}. */\n readonly maxTraversals?: number\n /** Default continuity for this edge's SPAWN traversals. `'resume'` makes every spawn after\n * the node's first re-attach to its most recent SETTLED worker: a NEW live worker whose\n * spawn context carries `resume: { ofWorker, sequence }` for the executor seam, spending\n * from the same conserved pool — the node's first spawn is effectively `'fresh'`, and a\n * spawn while a prior worker is still live refuses loudly (steer is the live channel).\n * The driver's per-call `spawn_worker` `continuity` argument overrides either way. Omit =\n * `'fresh'` (today's behavior, byte-identical). Caps count resumes exactly like fresh\n * spawns. */\n readonly continuity?: ContinuityMode\n }\n /** Findings flow anywhere: an analyst over N nodes' settled traces, delivered to ONE node.\n * With a LENS analyst the directive wraps the findings for the recipient; with a NODE analyst\n * the directive is the analyst agent's task and the findings are its settle output. */\n | {\n readonly kind: 'analyzes'\n /** The analyst REFERENCE, in one of two forms: a lens id resolved against\n * `RunGraphOptions.analysts` (environment), or the id of a graph NODE with no delegates\n * edge pointing at it — then each matching settle spawns that node's pinned profile as a\n * tool-equipped analyst WORKER (same spawn machinery, conserved budget, trace join) whose\n * task is this edge's directive plus the settled worker's trace evidence and whose settle\n * output is the findings. An id that is both a node and a registry lens is refused. */\n readonly analyst: string\n readonly over: ReadonlyArray<NodeId>\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Observability cap: traversals beyond this are LEDGERED as exhausted (`unpropagated`).\n * Only delegates caps refuse traversal — they are what close the spawn cycle. */\n readonly maxTraversals?: number\n }\n /**\n * Fan-out over a list that exists only at run time, then one join. When `from` settles `done`,\n * the array at `pointer` in its result is expanded: each element becomes the TASK of one item\n * run, at most `concurrency` at a time, and once every item settled the `join` node runs with\n * `{ map, source, items, results: [{ index, item, result }], failures: [{ index, item, outcome,\n * reason }] }`, results in item order. The runtime spawns the items and the join (`from`'s\n * driver spends no turn on them) through the same authorized spawn path a delegates spawn\n * takes: each item reserves its budget from the one conserved pool and is pinned to the edge's\n * profile, so an item's content can never choose what runs.\n *\n * An item is either the node `to` (its pinned profile plus this edge's directive) or the nested\n * `graph`, started per item exactly as `run_graph` starts a graph. Refusals are loud and\n * ledgered, and the driver is woken with them: a pointer that does not resolve to an array, more\n * elements than `maxItems`, or a `concurrency` the run's worker-slot bound can never honor.\n * `concurrency` otherwise THROTTLES (items wait for a free place); it never refuses an item.\n *\n * An edge rather than a node-level spec, because every kernel invariant a map must keep already\n * attaches to edge traversal: pinning admits only the edge's item and join nodes (the spawn\n * context carries a runtime-authored `map` marker), each item is admitted like a spawn and\n * reserves from the conserved pool, each item settles under its own deliverable check, and each\n * expansion, item and join is a ledger row with its journal twin. Topology stays static; only the\n * traversal count is dynamic, so validation and the one-node-one-profile rule are unchanged.\n */\n | {\n readonly kind: 'maps'\n /** The source node: a delegates target, or the join of another maps edge. Each of its `done`\n * settles expands the map once. */\n readonly from: NodeId\n /** RFC 6901 JSON pointer into `from`'s settled result (`''` is the whole result). */\n readonly pointer: string\n /** The item node, run once per element with the element as its task. Exactly one of `to`\n * and `graph`. Reachable only through this edge: never a delegates target. */\n readonly to?: NodeId\n /** A graph run per element as one subtask, through the `run_graph` path. */\n readonly graph?: GraphTopology\n /** Receives the ordered results once every item settled. Reachable only through this edge. */\n readonly join: NodeId\n /** The item directive, appended to the item node's instructions per traversal. */\n readonly directive: PromptHandle\n /** Lists longer than this are refused before any item runs. */\n readonly maxItems: number\n /** How many items run at once. */\n readonly concurrency: number\n readonly onItemFailure: MapItemFailurePolicy\n /** Each item's budget, merged over the per-worker default as `spawn_worker`'s `budget` is. */\n readonly itemBudget?: Partial<Budget>\n }\n /**\n * A route in a flow graph (one with `entry`): Runtime traverses it when `from` settles, so no\n * root decides the order, the branch, the repair loop or the stop. On each usable settle of\n * `from` its outgoing routes edges are tried in declaration order and the first whose `when`\n * holds fires; an edge without `when` is the default branch and comes last. A node target is\n * spawned with `{ from: { node, result }, evidence: { [id]: latest usable result } }` (a join's\n * target with `{ from: { nodes }, evidence }`, see below) and the directive appended to its pinned instructions; `{ stop }` ends the run with no winner and\n * `GraphResult.stopped`; `{ finish }` makes this settle part of the run's output.\n *\n * A fork lists two or more nodes in `to`: one traversal spawns each of them at once, each under\n * its own key `route:<edge id>#<traversal>:<node>`. A join lists two or more nodes in `from`: it\n * fires once every member has settled usably since it last fired, and the target's task is\n * `{ from: { nodes: <members in declared order> }, evidence }` with each member's latest result\n * in `evidence`, so it does not depend on which member settled last and a resumed run derives the\n * same task. A routes edge that spawns a node with a settled worker in this flow (a back edge)\n * names that node's latest settled worker as the spawn's `successorOf`. A join carries no `when`, and it is the only routes edge\n * leaving each of its members. A route into a node that still has a running worker throws\n * {@link GraphRouteError} with reason `target-live`: converging branches use a join.\n */\n | {\n readonly kind: 'routes'\n readonly from: NodeId | ReadonlyArray<NodeId>\n readonly to:\n | NodeId\n | ReadonlyArray<NodeId>\n | { readonly stop: string }\n | { readonly finish: string }\n readonly directive: PromptHandle\n /** Absent on the default edge and on every join. A match reads `from` unless it names a node\n * in `evidence`. */\n readonly when?: RouteWhen\n /** Nodes whose latest usable result rides the target's task. */\n readonly evidence?: ReadonlyArray<NodeId>\n /** Traversals beyond this are skipped (ledgered `unpropagated`) and matching continues with\n * the next edge. Default {@link defaultEdgeTraversalCap}. Every routes cycle, each subcycle\n * included, must cross an edge that sets it. */\n readonly maxTraversals?: number\n /** `'resume'` re-attaches each spawn of the target to its latest settled session. Omit =\n * `'fresh'`. */\n readonly continuity?: ContinuityMode\n }\n\n/** A topology without the run's own budget and deliverable: the form a `maps` edge runs per item,\n * as `run_graph` runs it. With `entry` it is a flow graph. Inside a maps item, the item value is\n * the task of every entry whose task is the placeholder `{ item: true }`; a down settle inside the item ends\n * that item only, and the maps edge's `onItemFailure` decides the join. */\nexport interface GraphTopology {\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n readonly entry?: AgentGraph['entry']\n /** Refused here: a maps item's graph and a `run_graph` subtask have no `decideGate`. */\n readonly gates?: AgentGraph['gates']\n}\n\nexport interface AgentGraph {\n 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 /** Setting it makes this a FLOW graph: Runtime spawns every entry at once, each with its task,\n * and traverses `routes` edges itself. No node is a root and no caller brain runs; the run's\n * output is `{ [node]: latest usable result }` over its terminal nodes and `finish` sources,\n * judged by `deliverable`. */\n readonly entry?: ReadonlyArray<{ readonly node: NodeId; readonly task: unknown }>\n /** Flow-graph vertices that are not agents: a routes edge into one awaits\n * `RunGraphOptions.decideGate`, and one edge per choice leaves it, matching\n * `{ pointer: '/choice', equals: <choice> }`. A `finish` leaving a gate outputs\n * `{ [gate]: { choice, by } }`. */\n readonly gates?: ReadonlyArray<RouteGate>\n}\n\n// ── The edge ledger ────────────────────────────────────────────────────────────\n\n/** `failed` is a maps item or join that ran and settled without a usable result (down, or\n * rejected by its deliverable check); a traversal that never reached a worker is `unpropagated`. */\nexport type EdgeDeliveryOutcome = 'delivered' | 'stripped' | 'empty' | 'unpropagated' | 'failed'\n\n/** How one ledgered hop CONTINUED: a spawn traversal stamps its effective spawn mode\n * (`'fresh'` | `'resume'`), and every mid-run delivery into an already-live recipient — a\n * driver steer leg and every analyzes delivery (routed steer or driver-destined finding) —\n * stamps `'steer'`. Zero ambiguity: every row carries exactly one of the three. */\nexport type TraversalContinuity = ContinuityMode | 'steer'\n\n/** One recorded edge traversal — the in-memory row; the journal twin is the `edge` SpawnEvent. */\nexport interface EdgeTraversal {\n /** Stable edge id: `delegates:<from>-><to>`, `analyzes:<analyst>:<over…>-><to>`,\n * `maps:<from>-><to | graph>-><join>`, `routes:<from>#<ordinal>-><to | stop:<reason> |\n * finish:<reason>>`, or `routes:entry-><node>` for an entry. */\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes' | 'maps' | 'routes'\n readonly from: string\n readonly to: string\n /** The resolved directive reference (`<surface>/v<n>`). */\n readonly directive: string\n /** 1-based per-edge ordinal. */\n readonly traversal: number\n readonly outcome: EdgeDeliveryOutcome\n /** How this hop continued — see {@link TraversalContinuity}. */\n readonly continuity: TraversalContinuity\n /** Bytes of directive + payload that actually crossed the edge. */\n readonly bytes: number\n readonly reason?: string\n /** The concrete worker node id, once known. A maps expansion names the source worker. */\n readonly workerId?: string\n /** Present on maps rows: the expansion of the source's list, one item by its index, or the\n * join. */\n readonly map?: { readonly phase: 'expand' | 'item' | 'join'; readonly index?: number }\n /** Present on a gate's decision row (`gate:<id>`, `traversal` = visit): who decided, and what. */\n readonly gate?: GateDecisionRecord\n}\n\n/** A delegates edge exhausted its traversal cap and the run produced no winner: the cap, not the\n * task, ended it. Carries the full evidence so failing loud loses nothing. */\nexport class GraphEdgeCapError extends Error {\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly ledger: ReadonlyArray<EdgeTraversal>\n readonly result: SupervisedResult<unknown>\n constructor(\n exhaustedEdges: ReadonlyArray<string>,\n ledger: ReadonlyArray<EdgeTraversal>,\n result: SupervisedResult<unknown>,\n ) {\n super(\n `runGraph: edge traversal cap exhausted on ${exhaustedEdges.join(', ')} and the run ` +\n 'delivered no winner — the cap (the cyclic-graph backstop), not the task, ended this run. ' +\n 'Raise maxTraversals on the edge or fix the cycle; the full edge ledger and the ' +\n 'supervised result ride on this error.',\n )\n this.name = 'GraphEdgeCapError'\n this.exhaustedEdges = exhaustedEdges\n this.ledger = ledger\n this.result = result\n }\n}\n\n// ── Options / result ───────────────────────────────────────────────────────────\n\n/**\n * Every `SuperviseOptions` key, partitioned by what `runGraph` does with it.\n *\n * `runGraph` starts one `supervise()` run, so every option that run honors is a graph option too\n * unless the graph itself owns the value. This used to be an opt-in list written by hand, and the\n * hand lost: 25 of 49 keys never reached `supervise()` from a graph, including `childSettleGraceMs`\n * (a root-driver failure tore down children that had ALREADY computed the deliverable) and\n * `driverRetry` (agent-runtime#963). Each absence was discovered by losing a run.\n *\n * The four lists below must cover `keyof SuperviseOptions` exactly. `everySuperviseOptionIsClassified`\n * below fails to COMPILE, naming the offender, when a key belongs to none of them — so the next\n * option added to `supervise()` cannot go missing here silently. It has to be classified, and\n * classifying it as forwarded is one word.\n */\n\n/** The graph derives these from the `AgentGraph` itself; a caller value would be overwritten. */\nconst GRAPH_OWNED_SUPERVISE_OPTIONS = [\n 'rootDriverFromBackend',\n 'resolveSpawnProfile',\n 'budget',\n 'deliverable',\n 'makeWorkerAgent',\n 'onCoordinationEvent',\n 'analyzeOnSettle',\n 'mapOnSettle',\n // A flow graph's entries and routes edges; its runtime-owned root runs them.\n 'routeFlow',\n 'continuityByProfile',\n // A graph pins every node and its delegation edges; a node never gains spawn rights it lacks.\n 'inheritSpawnRights',\n] as const\n\n/** Caller-facing on `RunGraphOptions`, but the graph wraps or defaults the value before it goes in:\n * `hooks` composes with the graph's own spawn-binding hook, `authorizeMessage` is wrapped so a\n * narrowed instruction ledgers `stripped`, `authorizeSpawn` runs AFTER the graph has pinned the\n * node (so a product sees the canonical profile, never the driver's stub), `makeLeafAgent` is the\n * caller's leaf override slotted under the graph's pinning, `analysts` rides only with analyze\n * routes, and `journal`/`blobs`/`runId` get graph defaults. */\nconst GRAPH_TRANSFORMED_SUPERVISE_OPTIONS = [\n 'hooks',\n 'authorizeMessage',\n 'authorizeSpawn',\n 'makeLeafAgent',\n 'analysts',\n 'journal',\n 'blobs',\n 'runId',\n // Replays a journaled decision before asking the caller.\n 'decideGate',\n] as const\n\n/** Not reachable from a graph, with the reason. `registry` is a NAME COLLISION, not a policy:\n * `RunGraphOptions.registry` is the directive `PromptRegistry` and `SuperviseOptions.registry` is\n * the `SuperviseRegistry` name→value table. Two different types under one name; the graph's wins.\n * Giving the supervise one a graph channel means renaming a public option, so it is recorded here\n * rather than silently dropped. */\nconst GRAPH_REFUSED_SUPERVISE_OPTIONS = ['registry'] as const\n\n/**\n * Forwarded to the root `supervise()` VERBATIM. Everything not owned, transformed, or refused\n * above belongs here — the default is \"a graph honors it\", not \"someone remembered to add it\".\n */\nconst GRAPH_FORWARDED_SUPERVISE_OPTIONS = [\n 'parking',\n 'backend',\n // Forwarded: composes guidance into the root and into profiles a manager authors. The graph also\n // composes each PINNED node profile, because pinning replaces the composed `{ name }` stub.\n 'profileGuidance',\n // Forwarded, not graph-owned: a graph pins WHICH nodes run, never who answers a question one of\n // them raises. Without it a graph run's `ask_parent` would always report `no-parent` even when\n // the caller wired an inbox.\n 'escalateQuestion',\n 'rootHandle',\n 'signal',\n 'execution',\n 'resolveDeliverable',\n 'coordination',\n 'peerMail',\n 'peerAudit',\n 'traceTools',\n 'driverBackend',\n 'profileSecurity',\n 'authorizeSpawn',\n 'router',\n 'driveHarness',\n 'selectSeat',\n 'driverRetry',\n 'onDriverAttempt',\n 'workerRetry',\n 'onWorkerRetry',\n 'continuation',\n 'childSettleGraceMs',\n 'teardownConfirmMs',\n 'retainedAtSettlement',\n 'resolveDriveHarness',\n 'driveHarnessMaterialization',\n 'resolveSupervisorTools',\n 'extraTools',\n 'executeExtraTool',\n 'recoverExecutor',\n 'perWorker',\n 'reservationPolicy',\n 'deadlineCheckIn',\n 'budgetStopHoldMs',\n 'workerSlots',\n 'watchWorkers',\n 'stallAfterMs',\n 'wake',\n 'runDir',\n 'resume',\n 'segment',\n 'runContext',\n 'steerDir',\n 'stopRule',\n 'onProgressStop',\n 'maxDepth',\n 'maxTurns',\n 'compaction',\n 'now',\n 'allowedModels',\n 'finalizer',\n 'otel',\n // Forwarded: the registry a manager's `run_graph` resolves stored graphs against. A node of this\n // graph cannot start another graph (pinning refuses it), so it matters to no node here.\n 'graphRegistry',\n] as const\n\ntype ClassifiedSuperviseOption =\n | (typeof GRAPH_OWNED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_TRANSFORMED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_REFUSED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]\n\n/**\n * Every key `RunGraphOptions` accepts, as data: the forwarded and transformed `SuperviseOptions`\n * keys, the name-colliding `registry`, and the graph's own `brain`. `GRAPH_OWNED_SUPERVISE_OPTIONS`\n * is deliberately absent — a caller value for one of those is overwritten by the graph, so it is\n * refused by name rather than discarded.\n *\n * The assignment below fails to COMPILE, naming the key, when `RunGraphOptions` declares something\n * this list does not carry.\n */\nconst runGraphOptionKeys = [\n ...GRAPH_FORWARDED_SUPERVISE_OPTIONS,\n ...GRAPH_TRANSFORMED_SUPERVISE_OPTIONS,\n ...GRAPH_REFUSED_SUPERVISE_OPTIONS,\n 'brain',\n] as const\n\ntype UnlistedRunGraphOption = Exclude<keyof RunGraphOptions, (typeof runGraphOptionKeys)[number]>\nconst everyRunGraphOptionIsListed: UnlistedRunGraphOption extends never\n ? true\n : UnlistedRunGraphOption = true\nvoid everyRunGraphOptionIsListed\n\nconst runGraphOptionKeySet: ReadonlySet<string> = new Set<string>(runGraphOptionKeys)\nconst graphOwnedOptionKeySet: ReadonlySet<string> = new Set<string>(GRAPH_OWNED_SUPERVISE_OPTIONS)\n\n/**\n * Refuse an option key the graph would not read, naming it and saying which kind it is.\n *\n * A graph-owned key is the sharper case: it type-checks against a widened `SuperviseOptions`\n * value, the graph derives its own value and overwrites the caller's, the run succeeds, and the\n * capability the caller asked for is not there. The rename of the leaf seam from `makeWorkerAgent`\n * to `makeLeafAgent` is the shape of the failure — the old name stayed a valid `SuperviseOptions`\n * key AND a graph-owned one, so a caller that kept passing it got a run with no leaf override and\n * no complaint.\n */\nfunction assertRunGraphOptionKeys(opts: RunGraphOptions): void {\n const graphOwned: string[] = []\n const unknown: string[] = []\n for (const key of Object.keys(opts)) {\n if (runGraphOptionKeySet.has(key)) continue\n if (graphOwnedOptionKeySet.has(key)) graphOwned.push(key)\n else unknown.push(key)\n }\n if (graphOwned.length > 0) {\n throw new ConfigError(\n `runGraph: ${graphOwned.sort().join(', ')} — the graph derives this from the AgentGraph ` +\n 'itself, so a caller value is overwritten and the capability it asks for would silently ' +\n 'be absent',\n )\n }\n if (unknown.length > 0) {\n throw new ConfigError(\n `runGraph: unknown option ${unknown.sort().join(', ')} — no reader consults that name, so ` +\n 'the value would be discarded and the capability it asks for would silently be absent',\n )\n }\n}\n\n/** A `SuperviseOptions` key in none of the four lists makes this assignment fail, and the compiler\n * error names the key. Classify it — `GRAPH_FORWARDED_SUPERVISE_OPTIONS` is usually the answer. */\ntype UnclassifiedSuperviseOption = Exclude<keyof SuperviseOptions, ClassifiedSuperviseOption>\nconst everySuperviseOptionIsClassified: UnclassifiedSuperviseOption extends never\n ? true\n : UnclassifiedSuperviseOption = true\nvoid everySuperviseOptionIsClassified\n\n/** `backend` and `driverBackend` keep graph-specific documentation below.\n *\n * Do not inherit and redeclare them through an indexed access type.\n * TypeScript 7 correctly treats `SuperviseOptions['backend']` as including `undefined`, which makes\n * that redeclaration wider than the exact optional property inherited from `SuperviseOptions`.\n */\ntype GraphInheritedSuperviseOption = Exclude<\n (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number],\n 'backend' | 'driverBackend'\n>\n\n/** Copy every forwarded option the caller actually set. Absent stays absent: `supervise()` and the\n * graph must not disagree about what \"unset\" means. */\nfunction forwardedSuperviseOptions(\n opts: RunGraphOptions,\n): Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\n const forwarded: Record<string, unknown> = {}\n for (const key of GRAPH_FORWARDED_SUPERVISE_OPTIONS) {\n const value = (opts as Record<string, unknown>)[key]\n if (value !== undefined) forwarded[key] = value\n }\n return forwarded as Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]>\n}\n\n/**\n * Options for one `runGraph` run.\n *\n * Extends every forwarded `SuperviseOptions` key, so a graph honors what a `supervise()` run\n * honors WITHOUT anyone restating it here. Only the graph-specific members and the ones whose\n * graph semantics differ are declared below; everything else inherits its type AND its\n * documentation from `SuperviseOptions`, which is the one owner of both.\n */\nexport interface RunGraphOptions extends Pick<SuperviseOptions, GraphInheritedSuperviseOption> {\n /** WHERE worker nodes run — the executor backend. Provide this OR `makeLeafAgent`. Forwarded to\n * `supervise()`, which derives every authorized leaf from it. A node that declares\n * `agent_runtime_coordination_spawn_worker` becomes a nested supervisor instead, whose own\n * leaves are derived the same way. */\n readonly backend?: Exclude<SuperviseOptions['backend'], undefined>\n /** WHERE the ROOT node's harness brain runs — forwarded to `supervise()` verbatim (see\n * `SuperviseOptions.driverBackend`). Needed when the root node's profile declares an external\n * harness (`codex`, `claude-code`, `opencode`): that root is driven by the harness, not by the\n * router brain, and automatic execution supports a local `bridge`. Unlike `supervise()`, this\n * does NOT default to `backend`: a graph's `backend` places WORKER nodes, so the root driver\n * is selected only by this field. Omit = no harness driver, which is correct for a root whose\n * `profile.harness` is omitted or `cli-base` (that root runs on the router brain). */\n readonly driverBackend?: Exclude<SuperviseOptions['driverBackend'], undefined>\n /** Leaf-execution override (offline tests / advanced). `runGraph` still owns node pinning,\n * directive delivery, and the edge ledger AROUND this seam — only the leaf `act` is yours.\n * Slots INSIDE the kernel's authorized path (`SuperviseOptions.makeLeafAgent`), so a node that\n * declares the spawn tool still becomes a nested supervisor even under an offline leaf. */\n readonly makeLeafAgent?: MakeWorkerAgent\n /** The ROOT driver's inference seam — a caller-owned `ToolLoopChat` that makes every root\n * model call. Use it when the root's decisions must be caller-owned orchestration (a\n * deterministic conversation driver, a persona loop with its own LLM calls) rather than a\n * router-derived model call. The graph machinery around the seam is unchanged: node pinning,\n * directive delivery, the edge ledger, and the journal twin all run the same shipped path,\n * and the root profile keeps prompt control (`prompt-control-execution` materialization —\n * `systemPrompt`/`instructions` still apply). What moves to the caller with the brain:\n * model selection and provider-identity validation (`expectedModel` cannot be enforced on a\n * call the runtime did not place) and per-turn usage reporting (a brain that reports no\n * usage meters nothing into the pool). Omit = the router brain derived from the root\n * profile — the unchanged default. Mutually exclusive with `driverBackend`, and refused\n * when the root profile declares an external harness (that root is driven BY the harness). */\n readonly brain?: ToolLoopChat\n /** Caller-side runtime hooks (telemetry, policy, product extensions). Composed AFTER the\n * graph's own spawn-binding hook on the SAME event stream — the graph never swallows the\n * seam supervise() exposes. */\n readonly hooks?: RuntimeHooks\n /** The analyst lens registry `analyzes` edges resolve against. ENVIRONMENT — needed only for\n * lens analysts; an analyzes edge naming a graph NODE as its analyst needs no registry. */\n readonly analysts?: AnalystRegistry\n /** Answers a flow gate while the process holds the run; the wait counts against its deadline.\n * ENVIRONMENT, like `analysts`; required when the graph declares gates. */\n readonly decideGate?: (request: GateRequest) => Promise<GateDecision>\n /** Directive registry. Default: the seeded kernel registry (`kernelPromptRegistry()`).\n *\n * NOT `SuperviseOptions.registry`, which is the `SuperviseRegistry` name→value table for\n * code-valued options. The two share a name and nothing else, and this one wins here — see\n * `GRAPH_REFUSED_SUPERVISE_OPTIONS`. */\n readonly registry?: PromptRegistry\n /** The run journal the edge ledger and every spawn/settle ride. Default: in-memory. */\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly runId?: string\n /** Product authority over every steer/answer instruction (the filter seam). `runGraph` observes\n * what it CHANGES: a narrowed instruction ledgers its steer traversal as `stripped`. */\n readonly authorizeMessage?: SuperviseOptions['authorizeMessage']\n}\n\nexport interface GraphResult<Out = unknown> {\n readonly result: SupervisedResult<Out>\n /** Every edge traversal, in occurrence order — the observable-edge contract. */\n readonly ledger: ReadonlyArray<EdgeTraversal>\n /** Edge ids whose traversal cap was hit — analyzes exhaustion included (observable here, never\n * a refusal). A DELEGATES cap paired with a `no-winner` result THROWS\n * ({@link GraphEdgeCapError}) instead of returning: only delegates caps refuse spawns, so only\n * they can have ended the run. A LIFECYCLE no-winner (`aborted` / `budget-exhausted`) returns\n * normally even with an exhausted delegates cap — the abort or the pool, not the cap, ended\n * that run, and the exhaustion stays observable here. */\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly runId: string\n /** Why a flow graph ended early: a `stop` edge fired (`edge` names it), or a flow node settled\n * down (no `edge`; `reason` is `down: <worker reason>`) or, where a route was needed, without a\n * usable result (no `edge`; `reason` is `unusable: <why>`). Live flow workers are aborted. */\n readonly stopped?: {\n readonly edge?: string\n readonly at: NodeId\n readonly workerId: string\n readonly reason: string\n }\n}\n\n/** `RunGraphOptions` with the brain REQUIRED — the shape the `/testing` entry's\n * `runGraphWithTestBrain` keeps accepting now that `brain` is a production option. */\nexport interface RunGraphTestOptions extends RunGraphOptions {\n readonly brain: ToolLoopChat\n}\n\n// ── Validation ─────────────────────────────────────────────────────────────────\n\n/** Validate the graph and resolve every directive BEFORE any compute is spent — an invalid\n * topology or an unknown directive is a configuration fault, never a mid-run surprise. */\nfunction validateGraph(\n graph: AgentGraph,\n registry: PromptRegistry,\n analysts: AnalystRegistry | undefined,\n): ValidatedGraph {\n if (graph.entry === undefined) {\n if (!Array.isArray(graph.nodes) || graph.nodes.length === 0) {\n throw new ValidationError('runGraph: graph.nodes must be a non-empty array')\n }\n if (!Array.isArray(graph.edges) || graph.edges.length === 0) {\n throw new ValidationError('runGraph: graph.edges must be a non-empty array')\n }\n }\n if (typeof graph.deliverable?.check !== 'function') {\n throw new ValidationError('runGraph: graph.deliverable is mandatory (termination oracle)')\n }\n if (typeof graph.budget !== 'object' || graph.budget === null) {\n throw new ValidationError('runGraph: graph.budget is mandatory (the conserved pool)')\n }\n if (graph.entry !== undefined) return validateFlowGraph(graph, registry, analysts)\n if (graph.gates !== undefined)\n throw new ValidationError('runGraph: graph.gates needs graph.entry')\n return validateGraphTopology(graph.nodes, graph.edges, registry, analysts)\n}\n\n// ── The runner ─────────────────────────────────────────────────────────────────\n\n/**\n * Execute an {@link AgentGraph}. A flow graph (`entry` set) runs from its entries and routes edges\n * under a runtime-owned root that places no model call. Otherwise the root node becomes the\n * supervisor (`supervise()` — the execution core), each worker node is spawnable BY NODE ID\n * (`spawn_worker` with `profile: { name: '<node id>' }`; the node's canonical profile is pinned by\n * the graph), each\n * delegates directive is appended to the worker profile's `prompt.instructions` per traversal,\n * and each analyzes edge becomes an analyst-on-settle route with a real DESTINATION. Every\n * traversal is ledgered and journaled.\n */\nexport function runGraph(graph: AgentGraph, opts: RunGraphOptions): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/** Alias for graph tests written before `RunGraphOptions.brain` was production. The production\n * entry accepts the same shape; this wrapper only keeps the `/testing` import path working. */\nexport function runGraphWithTestBrain(\n graph: AgentGraph,\n opts: RunGraphTestOptions,\n): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/**\n * The graph supervise run, as its own entry: the engine's `run-graph` preset node executes exactly\n * this, so the preset and `runGraph` are the same code path by construction (agent-runtime#982).\n */\n/**\n * Every refusal a graph earns before any compute, in one place: the authoring contract. `runGraph`\n * calls it FIRST so a malformed graph throws synchronously, exactly as it did before the engine\n * preset (agent-runtime#982) moved execution behind a promise.\n */\nexport function assertRunGraphAuthoring(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): ReturnType<typeof validateGraph> {\n assertRunGraphOptionKeys(opts)\n const registry = opts.registry ?? kernelPromptRegistry()\n const validated = validateGraph(graph, registry, opts.analysts)\n const requireLeaves = (): void => {\n if (!opts.backend && !opts.makeLeafAgent) {\n throw new ValidationError(\n 'runGraph: provide opts.backend (where nodes run) or opts.makeLeafAgent',\n )\n }\n }\n if (validated.flow !== undefined) {\n // A flow's root is Runtime's own: nothing a caller sets for a root manager has a reader.\n const rootOptions = [\n ...(brain ? ['brain'] : []),\n ...(['driverBackend', 'finalizer', 'maxTurns', 'compaction'] as const).filter(\n (key) => opts[key] !== undefined,\n ),\n ]\n if (rootOptions.length > 0) {\n throw new ValidationError(\n `runGraph: ${rootOptions.join(', ')} with graph.entry — a flow graph has no root ` +\n 'manager: Runtime spawns its entries and traverses its routes edges, and the graph ' +\n \"owns the run's output\",\n )\n }\n if ((graph.gates?.length ?? 0) > 0 && opts.decideGate === undefined) {\n throw new ValidationError('runGraph: graph.gates needs opts.decideGate to answer them')\n }\n requireLeaves()\n return validated\n }\n const { root } = validated as RootValidatedGraph\n // A caller brain and a harness driver are two answers to WHO makes the root's calls: refuse the\n // contradiction before any compute, and refuse a harness-driven root outright — the harness IS\n // that root's brain, so a supplied one would be silently ignored downstream.\n if (brain && opts.driverBackend) {\n throw new ValidationError(\n 'runGraph: brain and driverBackend are mutually exclusive — a caller brain makes the root model calls, a driverBackend places a harness that makes its own',\n )\n }\n if (brain && harnessRunsAgent(root.profile.harness)) {\n throw new ValidationError(\n `runGraph: root node '${root.id}' declares harness '${root.profile.harness}', so the harness drives it — a caller brain applies only to a router-brained root (profile.harness omitted or 'cli-base')`,\n )\n }\n requireLeaves()\n return validated\n}\n\nexport function superviseAgentGraph(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): Promise<GraphResult> {\n const registry = opts.registry ?? kernelPromptRegistry()\n if (opts.runContext?.acquire !== undefined) {\n return withRunContext(opts.runContext, opts.signal, (runContext, signal) =>\n superviseAgentGraph(\n graph,\n {\n ...opts,\n runContext,\n ...(signal === undefined ? {} : { signal }),\n },\n brain,\n ),\n )\n }\n const validated = assertRunGraphAuthoring(graph, opts, brain)\n // A flow graph: Runtime schedules its nodes, and its root manager is Runtime's own.\n const flow = validated.flow === undefined ? undefined : createFlowRun()\n // A durable graph needs its journal AND blob store on disk. `supervise()` already resolves this\n // for its own context (`options.journal ?? createFileRunContext(runDir).journal`), but the graph\n // passes an explicit `journal`/`blobs` — the edge ledger's twin writes ride on it — so the graph\n // must do the same resolution itself or its in-memory default SHADOWS the file stores supervise\n // would have built: `runGraph({ runDir })` journaled only to the process, a second process\n // silently restarted the run from scratch, and `runDir/spawn-journal.jsonl` never existed.\n // Layout owner: `createFileRunContext` (run-context.ts); keep these paths byte-identical to it.\n const journal =\n opts.journal ??\n opts.runContext?.journal ??\n (opts.runDir !== undefined\n ? new FileSpawnJournal(`${resolve(opts.runDir)}/spawn-journal.jsonl`)\n : new InMemorySpawnJournal())\n const blobs =\n opts.blobs ??\n opts.runContext?.blobs ??\n (opts.runDir !== undefined\n ? new FileResultBlobStore(`${resolve(opts.runDir)}/blobs`)\n : new InMemoryResultBlobStore())\n const runId =\n opts.runId ??\n opts.runContext?.runId ??\n `graph-${canonicalCandidateDigest(graph.nodes.map((n) => n.id)).slice('sha256:'.length, 'sha256:'.length + 12)}`\n const now = opts.now ?? Date.now\n\n // The graph layer: node pinning, analyst routes, continuity defaults and the edge ledger. A\n // `run_graph` subtask builds the same overlay around its nested manager.\n // `profileGuidance` composes the profile a manager authors, but a graph then swaps that\n // `{ name }` stub for the pinned node profile. Compose the pinned profile too, so every node\n // that runs carries its harness and model guidance. Composition is idempotent.\n const guidance = profileGuidanceComposer(opts.profileGuidance)\n const overlay = createGraphOverlay(validated, {\n registry,\n journal,\n runId,\n now,\n ...(guidance ? { guidance } : {}),\n ...(opts.authorizeSpawn ? { authorizeSpawn: opts.authorizeSpawn } : {}),\n })\n // Always present: the kernel refuses steer/answer whenever spawn authorization is on (the\n // graph's pinning IS spawn authorization), so a graph with no caller filter passes instructions\n // through unchanged rather than losing its steer channel. Only a caller filter can strip.\n const callerAuthorizeMessage = opts.authorizeMessage\n const authorizeMessage = overlay.observeMessages<\n Parameters<NonNullable<SuperviseOptions['authorizeMessage']>>[0]\n >((input) =>\n callerAuthorizeMessage ? callerAuthorizeMessage(input) : { instruction: input.instruction },\n )\n\n // ── Spawn-hook: bind ledger rows to concrete worker ids, then journal them ──\n const graphHooks: RuntimeHooks = {\n onEvent: (event) => {\n if (event.target !== 'agent.spawn' || event.phase !== 'after') return\n const payload = event.payload as { childId?: unknown; assignmentId?: unknown } | undefined\n if (typeof payload?.childId !== 'string' || typeof payload.assignmentId !== 'string') return\n return overlay.bindSpawn(event.parentId, payload.assignmentId, payload.childId)\n },\n }\n const hooks = composeRuntimeHooks(graphHooks, opts.hooks)\n const rootProfile =\n flow === undefined\n ? graphRootProfile(validated as RootValidatedGraph, registry)\n : flowRootProfile\n const rootBrain = flow === undefined ? brain : runtimeFlowBrain()\n const task =\n flow === undefined\n ? graphTask(graph, (validated as RootValidatedGraph).root)\n : (graph.deliverable.describe ?? 'Runtime runs this flow graph from its entries.')\n\n // Every configuration fault above throws SYNCHRONOUSLY (matching `supervise()`'s own\n // contract); only the run itself is asynchronous.\n const start = async (): Promise<GraphResult> => {\n const superviseOptions = {\n // 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: overlay.authorizeSpawn,\n resolveSpawnProfile: overlay.resolveSpawnProfile,\n inheritSpawnRights: false,\n ...(opts.makeLeafAgent ? { makeLeafAgent: opts.makeLeafAgent } : {}),\n journal,\n blobs,\n runId,\n hooks,\n onCoordinationEvent: async (\n context: { readonly depth: number },\n _eventId: unknown,\n record: { readonly event: Parameters<typeof overlay.onCoordinationEvent>[0] },\n ) => {\n // A route event belongs to the flow of the manager that published it: a flow inside a\n // maps item or a run_graph subtask ledgers and concludes its own.\n if (record.event.type === 'route' && context.depth !== 0) return\n overlay.onCoordinationEvent(record.event)\n flow?.observe(record.event)\n },\n // Lens routes resolve against the registry; agent routes carry their own analyst profile,\n // so a graph whose only analysts are nodes needs no registry at all.\n ...(overlay.routes.length > 0\n ? {\n analyzeOnSettle: overlay.routes,\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n }\n : {}),\n ...(overlay.maps.length > 0 ? { mapOnSettle: overlay.maps } : {}),\n ...(Object.keys(overlay.continuityByProfile).length > 0\n ? { continuityByProfile: overlay.continuityByProfile }\n : {}),\n // A flow root's wake batches nothing for a decision, so it ends its turn on the first event.\n ...(flow === undefined\n ? {}\n : {\n routeFlow: routeFlowOf(validated),\n ...(opts.decideGate && {\n decideGate: journaledGateDecider(opts.decideGate, journal, runId),\n }),\n finalizer: flow.finalizer,\n wake: { debounceMs: 0, ...opts.wake },\n }),\n authorizeMessage,\n } satisfies SuperviseOptions\n // The flow root reaches supervise through the same brain seam a caller brain takes.\n const supervised =\n rootBrain === undefined\n ? await supervise(rootProfile, task, superviseOptions)\n : await superviseWithTestBrain(rootProfile, task, { ...superviseOptions, brain: rootBrain })\n\n const { ledger, exhaustedEdges, exhaustedDelegates } = await overlay.settle()\n const concluded = flow?.conclude(supervised)\n if (concluded?.kind === 'unrouted') {\n throw new GraphRouteError(concluded.unrouted, ledger, supervised)\n }\n const result = concluded?.result ?? supervised\n const stopped = concluded?.stopped\n // A LIFECYCLE ending (caller abort, exhausted budget, deadline) is its own complete explanation: the\n // cap did not end that run even when it was exhausted along the way, and blaming it would\n // misattribute the ending (and turn a caller-initiated abort into a throw). The exhaustion\n // stays observable in `exhaustedEdges` either way.\n const lifecycleEnded =\n result.kind === 'no-winner' &&\n (result.reason === 'aborted' ||\n result.reason === 'cancelled' ||\n result.reason === 'budget-exhausted' ||\n result.reason === 'deadline')\n if (result.kind !== 'winner' && !lifecycleEnded && exhaustedDelegates.length > 0) {\n // Fail LOUD: the backstop, not the task, ended this run. The evidence rides on the error.\n // Only DELEGATES caps refuse spawns, so only they can be the cause named here.\n throw new GraphEdgeCapError(exhaustedDelegates, ledger, result)\n }\n return { result, ledger, exhaustedEdges, runId, ...(stopped ? { stopped } : {}) }\n }\n\n return start()\n}\n\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyUA,IAAa,oBAAb,cAAuC,MAAM;CAC3C;CACA;CACA;CACA,YACE,gBACA,QACA,QACA;EACA,MACE,6CAA6C,eAAe,KAAK,IAAI,EAAE,2NAIzE;EACA,KAAK,OAAO;EACZ,KAAK,iBAAiB;EACtB,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;AACF;;;;;;;;;;;;;;;;AAoBA,MAAM,gCAAgC;CACpC;CACA;CACA;CACA;CACA;CACA;C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AY,CAAC,kBAAkB,mBAAmB,SAAS,GAG7E,MAAM,IAAI,kBAAkB,oBAAoB,QAAQ,MAAM;EAEhE,OAAO;GAAE;GAAQ;GAAQ;GAAgB;GAAO,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAAG;CAClF;CAEA,OAAO,MAAM;AACf;;;AAIA,SAAS,UAAU,OAAmB,MAAyB;CAE7D,OADiB,MAAM,YAAY,YAErB,wEAAwE,KAAK,GAAG;AAEhG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"model-policy-CyCUwHed.js","names":["positiveInteger"],"sources":["../src/runtime/harness-role.ts","../src/runtime/model-identity.ts","../src/runtime/router-auto-evidence.ts","../src/runtime/router-retry-policy.ts","../src/runtime/supervise/model-policy.ts"],"sourcesContent":["/**\n * Which `HarnessType` values name a real coding-agent runtime, and which name a MODE that has no\n * agent behind it.\n *\n * `cli-base` is the router-backed mode — a plain multi-turn router call with no coding-agent\n * harness (`@tangle-network/agent-interface`'s `HarnessType` doc, and the same table's\n * `harnessReasoningCeiling['cli-base'] = 'none'` commented \"cli-base has no agent\"). The\n * distinction is REAL; what was accidental is that three call sites each spelled the test\n * themselves, so a second no-agent mode would have to be remembered in three places.\n *\n * SHOULD UPSTREAM: this belongs next to `harnessHonorsEffort` in agent-interface's\n * `harness-capabilities.ts`, which already encodes the fact but exports no predicate for it.\n * Until it does, this is the one local copy — extend the set here, never re-test the name.\n */\n\nimport type { HarnessType } from '@tangle-network/agent-interface'\n\n/**\n * Harness ids that select a router/no-agent mode rather than a coding-agent runtime.\n *\n * `nanoclaw` is deliberately ABSENT: the shared capability table clamps its reasoning ceiling the\n * same way it clamps `cli-base`, but nanoclaw does run an agent (a socket-bridge runner to the\n * NanoClaw daemon) and every caller here treats it as a full harness. Add a row only with the\n * behavior change stated, never to make the two clamps look symmetric.\n */\nconst NO_AGENT_HARNESSES: ReadonlySet<string> = new Set<string>(['cli-base' satisfies HarnessType])\n\n/** Whether this profile harness selects a real coding-agent runtime (vs. the router/no-agent mode\n * or no preference at all). Accepts the looser `string` some local profile shapes declare, and\n * preserves the caller's own harness type when it is narrower. */\nexport function harnessRunsAgent<T extends string>(harness: T | null | undefined): harness is T {\n return harness != null && !NO_AGENT_HARNESSES.has(harness)\n}\n\n/** The coding-agent harness this profile selects, or `undefined` when it selects none — the shape\n * callers want when a no-agent mode must fall through to the router arm. */\nexport function agentHarness<T extends string>(harness: T | null | undefined): T | undefined {\n return harnessRunsAgent(harness) ? harness : undefined\n}\n","import { harnessTypeSchema } from '@tangle-network/agent-interface'\n\nconst SNAPSHOT_TOKEN = /^[A-Za-z0-9._-]+$/u\nconst datedIsoSuffix = /^(.*)-(\\d{4})-(\\d{2})-(\\d{2})$/u\nconst datedCompactSuffix = /^(.*)-(\\d{4})(\\d{2})(\\d{2})$/u\nconst datedMonthSuffix = /^(.*)-(\\d{4})-(\\d{2})$/u\n\ntype SnapshotKind = 'date' | 'opaque'\n\ninterface ModelIdentityParts {\n readonly base: string\n readonly snapshot?: string\n readonly snapshotKind?: SnapshotKind\n}\n\ninterface CanonicalObservedModelParts {\n readonly base: string\n readonly snapshot?: string\n readonly snapshotKind?: SnapshotKind\n readonly canonical: string\n}\n\n/** Match equivalent bare and provider-qualified spellings without discarding observed identity. */\nexport function observedModelMatchesDeclared(observed: string, declared: string): boolean {\n const observedIdentity = modelIdentityParts(observed)\n const declaredIdentity = modelIdentityParts(declared)\n if (!observedIdentity || !declaredIdentity) return false\n if (\n declaredIdentity.snapshot !== undefined &&\n (observedIdentity.snapshot !== declaredIdentity.snapshot ||\n observedIdentity.snapshotKind !== declaredIdentity.snapshotKind)\n ) {\n return false\n }\n return equivalentModelBase(observedIdentity.base, declaredIdentity.base)\n}\n\n/** Merge two observations of one served model while retaining a snapshot-bearing raw identity. */\nexport function mergeObservedModelIdentity(current: string, next: string): string | undefined {\n const currentIdentity = modelIdentityParts(current)\n const nextIdentity = modelIdentityParts(next)\n if (!currentIdentity || !nextIdentity) return undefined\n if (!equivalentModelBase(currentIdentity.base, nextIdentity.base)) return undefined\n if (\n currentIdentity.snapshot !== undefined &&\n nextIdentity.snapshot !== undefined &&\n (currentIdentity.snapshot !== nextIdentity.snapshot ||\n currentIdentity.snapshotKind !== nextIdentity.snapshotKind)\n ) {\n return undefined\n }\n return currentIdentity.snapshot === undefined && nextIdentity.snapshot !== undefined\n ? next\n : current\n}\n\n/** Canonicalize a served model for cross-route identity comparisons. */\nexport function canonicalObservedModel(model: string): string | undefined {\n return canonicalObservedModelParts(model)?.canonical\n}\n\n/** Return the canonical model and its validated snapshot kind for runtime evidence reduction. */\nexport function canonicalObservedModelParts(\n model: string,\n): CanonicalObservedModelParts | undefined {\n const identity = modelIdentityParts(model)\n if (!identity) return undefined\n const base = identity.base.slice(identity.base.lastIndexOf('/') + 1)\n const canonical =\n identity.snapshot === undefined\n ? base\n : identity.snapshotKind === 'date'\n ? `${base}-${identity.snapshot}`\n : `${base}@${identity.snapshot}`\n return {\n base,\n ...(identity.snapshot !== undefined ? { snapshot: identity.snapshot } : {}),\n ...(identity.snapshotKind !== undefined ? { snapshotKind: identity.snapshotKind } : {}),\n canonical,\n }\n}\n\n/** Return whether an observed identity includes a provider snapshot. */\nexport function observedModelHasSnapshot(model: string): boolean {\n return modelIdentityParts(model)?.snapshot !== undefined\n}\n\nfunction modelIdentityParts(model: string): ModelIdentityParts | null {\n if (model.length === 0) return null\n const at = model.lastIndexOf('@')\n if (at < 0) {\n const dated = datedModelIdentity(model)\n if (dated !== undefined) return dated\n return modelLeaf(model).length === 0 ? null : { base: model }\n }\n const base = model.slice(0, at)\n const snapshot = model.slice(at + 1)\n if (base.length === 0 || modelLeaf(base).length === 0 || !SNAPSHOT_TOKEN.test(snapshot)) {\n return null\n }\n return { base, snapshot, snapshotKind: 'opaque' }\n}\n\nfunction equivalentModelBase(observed: string, declared: string): boolean {\n const observedPath = modelBaseParts(observed)\n const declaredPath = modelBaseParts(declared)\n if (!samePath(observedPath.path, declaredPath.path)) return false\n\n // A bare id omits provider routing. It can match an explicitly qualified spelling\n // only when the model path is otherwise identical.\n if (\n observedPath.provider === undefined ||\n declaredPath.provider === undefined ||\n sameProvider(observedPath.provider, declaredPath.provider)\n ) {\n return true\n }\n\n // Tangle Router may report the upstream provider's qualified spelling. Preserve this\n // one documented alias without allowing arbitrary provider-to-provider substitutions.\n if (observedPath.provider === 'tangle-router' || declaredPath.provider === 'tangle-router') {\n const router = observedPath.provider === 'tangle-router' ? observedPath : declaredPath\n const upstream = observedPath.provider === 'tangle-router' ? declaredPath : observedPath\n if (upstream.provider === undefined) return false\n return (\n samePath(router.path, upstream.path) ||\n (router.path[0] === upstream.provider && samePath(router.path.slice(1), upstream.path))\n )\n }\n\n return false\n}\n\n/**\n * Compare provider slugs across catalogs that spell one vendor with or without hyphens,\n * such as `zai` and OpenRouter's `z-ai`. Any other provider difference is a substitution.\n */\nfunction sameProvider(left: string, right: string): boolean {\n return left.replaceAll('-', '') === right.replaceAll('-', '')\n}\n\ninterface ModelBaseParts {\n readonly provider: string | undefined\n readonly path: ReadonlyArray<string>\n}\n\nfunction modelBaseParts(model: string): ModelBaseParts {\n const segments = model.split('/')\n const normalized =\n segments.length > 1 && isHarnessPrefix(segments[0]) ? segments.slice(1) : segments\n if (normalized.length === 1) return { provider: undefined, path: normalized }\n return { provider: normalized[0], path: normalized.slice(1) }\n}\n\nfunction isHarnessPrefix(segment: string | undefined): boolean {\n return segment !== undefined && harnessTypeSchema.safeParse(segment).success\n}\n\nfunction samePath(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {\n return left.length === right.length && left.every((segment, index) => segment === right[index])\n}\n\nfunction modelLeaf(model: string): string {\n return model.slice(model.lastIndexOf('/') + 1)\n}\n\n/**\n * Parse the provider's documented dated snapshot forms.\n *\n * `undefined` means that the model has no dated shape and must be treated as a normal base.\n * `null` means that it has a dated shape but the date is invalid, so identity matching fails.\n */\nfunction datedModelIdentity(model: string): ModelIdentityParts | null | undefined {\n const iso = datedIsoSuffix.exec(model)\n if (iso) {\n const [, base, yearText, monthText, dayText] = iso\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}-${dayText}`,\n isValidCalendarDate(yearText, monthText, dayText),\n )\n }\n\n const compact = datedCompactSuffix.exec(model)\n if (compact) {\n const [, base, yearText, monthText, dayText] = compact\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}-${dayText}`,\n isValidCalendarDate(yearText, monthText, dayText),\n )\n }\n\n const month = datedMonthSuffix.exec(model)\n if (month) {\n const [, base, yearText, monthText] = month\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}`,\n isValidCalendarMonth(yearText, monthText),\n )\n }\n\n return undefined\n}\n\nfunction buildDatedIdentity(\n base: string | undefined,\n snapshot: string,\n valid: boolean,\n): ModelIdentityParts | null | undefined {\n // A date that is the entire model segment is not a snapshot suffix.\n if (base === undefined || base.length === 0 || base.endsWith('/')) return undefined\n return valid ? { base, snapshot, snapshotKind: 'date' } : null\n}\n\nfunction isValidCalendarDate(\n yearText: string | undefined,\n monthText: string | undefined,\n dayText: string | undefined,\n): boolean {\n if (yearText === undefined || monthText === undefined || dayText === undefined) return false\n const year = Number(yearText)\n const month = Number(monthText)\n const day = Number(dayText)\n if (year < 2000 || year > 2099 || month < 1 || month > 12 || day < 1 || day > 31) {\n return false\n }\n const date = new Date(Date.UTC(year, month - 1, day))\n return (\n date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n )\n}\n\nfunction isValidCalendarMonth(\n yearText: string | undefined,\n monthText: string | undefined,\n): boolean {\n if (yearText === undefined || monthText === undefined) return false\n const year = Number(yearText)\n const month = Number(monthText)\n return year >= 2000 && year <= 2099 && month >= 1 && month <= 12\n}\n","import { ValidationError } from '../errors'\nimport { observedModelMatchesDeclared } from './model-identity'\n\nfunction object(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new ValidationError('Router Auto requires an inline policy and routing receipt')\n }\n return value as Record<string, unknown>\n}\n\n/** Router owns policy parsing. Runtime requires visible model authority before dispatch. */\nexport function assertRouterAutoDeclaration(value: unknown, stream: boolean | undefined): void {\n const policy = object(value)\n if (stream === true) throw new ValidationError('Router Auto requires buffered transport')\n if (\n policy.version !== 1 ||\n typeof policy.id !== 'string' ||\n typeof policy.revision !== 'string' ||\n !Array.isArray(policy.strategies) ||\n policy.strategies.length === 0\n ) {\n throw new ValidationError(\n 'Router Auto requires a versioned inline policy with concrete strategies',\n )\n }\n for (const raw of policy.strategies) {\n const strategy = object(raw)\n if (\n typeof strategy.id !== 'string' ||\n typeof strategy.model !== 'string' ||\n strategy.model === 'tangle/auto' ||\n strategy.model.length === 0\n ) {\n throw new ValidationError('Router Auto strategy model authority is missing')\n }\n }\n for (const phase of ['selector', 'review']) {\n if (policy[phase] !== undefined && typeof object(policy[phase]).model !== 'string') {\n throw new ValidationError('Router Auto assessment model authority is missing')\n }\n }\n}\n\n/** An alias does not waive identity checks. Every reported child must match its declared phase. */\nexport function assertRouterAutoResponse(\n policyValue: unknown,\n response: unknown,\n served: string | undefined,\n): void {\n const policy = object(policyValue)\n const receipt = object(object(response).tangle_auto)\n const decision = object(receipt.decision)\n const strategies = policy.strategies as unknown[]\n const selected = strategies.map(object).find((strategy) => strategy.id === decision.strategyId)\n if (\n decision.requestedModel !== 'tangle/auto' ||\n decision.policyId !== policy.id ||\n decision.policyRevision !== policy.revision ||\n typeof decision.policyDigest !== 'string' ||\n !selected ||\n decision.selectedModel !== selected.model ||\n served === undefined ||\n !observedModelMatchesDeclared(served, String(selected.model))\n ) {\n throw new ValidationError(\n 'Router Auto response does not match AgentProfile policy/model authority',\n )\n }\n if (!Array.isArray(receipt.calls) || receipt.calls.length === 0) {\n throw new ValidationError('Router Auto response is missing physical call receipts')\n }\n for (const raw of receipt.calls) {\n const call = object(raw)\n const declared =\n call.phase === 'selector'\n ? object(policy.selector).model\n : call.phase === 'review'\n ? object(policy.review).model\n : call.phase === 'initial' || call.phase === 'escalation'\n ? strategies.map(object).map((strategy) => strategy.model)\n : []\n const allowed = Array.isArray(declared) ? declared : [declared]\n if (\n typeof call.model !== 'string' ||\n !allowed.some(\n (model) =>\n typeof model === 'string' && observedModelMatchesDeclared(call.model as string, model),\n )\n )\n throw new ValidationError('Router Auto physical call exceeds AgentProfile model authority')\n }\n}\n\n/** The concrete authority declared by an inline Auto policy, including paid assessments. */\nexport function routerAutoDeclaredModels(value: unknown): readonly string[] {\n assertRouterAutoDeclaration(value, undefined)\n const policy = object(value)\n const models = (policy.strategies as unknown[]).map((raw) => String(object(raw).model))\n for (const phase of ['selector', 'review']) {\n if (policy[phase] !== undefined) models.push(String(object(policy[phase]).model))\n }\n return [...new Set(models)]\n}\n","import { ValidationError } from '../errors'\n\n/** Exact retry controls accepted at `AgentProfile.model.metadata.retry`. */\nexport interface RouterRetryPolicy {\n /** Total attempts, including the first request. */\n readonly maxAttempts?: number\n /** Delay before the second attempt. Later delays grow exponentially. */\n readonly initialBackoffMs?: number\n /** Maximum delay between attempts. */\n readonly maxBackoffMs?: number\n /** Symmetric random variation around each delay, from 0 through 1. */\n readonly jitter?: number\n /** HTTP statuses that may be retried. */\n readonly retryStatuses?: ReadonlyArray<number>\n /** Deadline for receiving one attempt's response headers. Zero disables it. */\n readonly requestTimeoutMs?: number\n}\n\nexport interface ResolvedRouterRetryPolicy {\n readonly maxAttempts: number\n readonly initialBackoffMs: number\n readonly maxBackoffMs: number\n readonly jitter: number\n readonly retryStatuses: ReadonlyArray<number>\n readonly requestTimeoutMs: number\n}\n\nconst maximumTimerMs = 2_147_483_647\nconst defaultRetryStatuses = Object.freeze([408, 425, 429, 500, 502, 503, 504, 520, 522, 524])\nconst retryPolicyKeys = new Set([\n 'initialBackoffMs',\n 'jitter',\n 'maxAttempts',\n 'maxBackoffMs',\n 'requestTimeoutMs',\n 'retryStatuses',\n])\n\n/** Parse untrusted profile/config data once and return an immutable complete policy. */\nexport function resolveRouterRetryPolicy(\n input: unknown,\n context: string,\n): ResolvedRouterRetryPolicy {\n if (\n input !== undefined &&\n (typeof input !== 'object' || input === null || Array.isArray(input))\n ) {\n throw new ValidationError(`${context} must be an object`)\n }\n const policy = input === undefined ? {} : Object.fromEntries(Object.entries(input))\n const unknown = Object.keys(policy).filter((key) => !retryPolicyKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(`${context} has unsupported fields: ${unknown.join(', ')}`)\n }\n const maxAttempts = positiveInteger(policy.maxAttempts, 5, `${context}.maxAttempts`)\n const initialBackoffMs = timerInteger(\n policy.initialBackoffMs,\n 1_000,\n `${context}.initialBackoffMs`,\n )\n const maxBackoffMs = timerInteger(policy.maxBackoffMs, 30_000, `${context}.maxBackoffMs`)\n const requestTimeoutMs = timerInteger(\n policy.requestTimeoutMs,\n 0,\n `${context}.requestTimeoutMs`,\n Number.MAX_SAFE_INTEGER - Date.now(),\n )\n const jitter = policy.jitter ?? 0.25\n if (typeof jitter !== 'number' || !Number.isFinite(jitter) || jitter < 0 || jitter > 1) {\n throw new ValidationError(`${context}.jitter must be a finite number from 0 through 1`)\n }\n const retryStatuses = parseRetryStatuses(policy.retryStatuses, context)\n return Object.freeze({\n maxAttempts,\n initialBackoffMs,\n maxBackoffMs,\n jitter,\n retryStatuses,\n requestTimeoutMs,\n })\n}\n\nfunction parseRetryStatuses(value: unknown, context: string): ReadonlyArray<number> {\n if (value === undefined) return defaultRetryStatuses\n if (!Array.isArray(value)) {\n throw new ValidationError(`${context}.retryStatuses must be an array of HTTP statuses`)\n }\n const statuses: number[] = []\n const seen = new Set<number>()\n for (const status of value) {\n if (!Number.isSafeInteger(status) || status < 100 || status > 599) {\n throw new ValidationError(\n `${context}.retryStatuses must contain integer HTTP statuses from 100 through 599`,\n )\n }\n if (seen.has(status)) {\n throw new ValidationError(`${context}.retryStatuses must not contain duplicates`)\n }\n seen.add(status)\n statuses.push(status)\n }\n return Object.freeze(statuses)\n}\n\nfunction positiveInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed < 1) {\n throw new ValidationError(`${context} must be a positive safe integer`)\n }\n return parsed\n}\n\nfunction timerInteger(\n value: unknown,\n fallback: number,\n context: string,\n maximum = maximumTimerMs,\n): number {\n const parsed = value ?? fallback\n if (\n typeof parsed !== 'number' ||\n !Number.isSafeInteger(parsed) ||\n parsed < 0 ||\n parsed > maximum\n ) {\n throw new ValidationError(\n `${context} must be a nonnegative safe integer no greater than ${maximum}`,\n )\n }\n return parsed\n}\n","/**\n * `assertModelAllowed` — a fail-loud guard that restricts a run to a chosen subset of\n * models. The two front doors (`supervise()` / `improve()`) call it once per configured\n * model at resolve time, so a run that names a model outside the allowed set throws before\n * any compute is spent — never silently swapped or silently allowed.\n */\nimport { HARNESS_NATIVE_MODEL } from '@tangle-network/agent-eval'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../../errors'\nimport { agentHarness } from '../harness-role'\nimport { routerAutoDeclaredModels } from '../router-auto-evidence'\nimport { type ResolvedRouterRetryPolicy, resolveRouterRetryPolicy } from '../router-retry-policy'\n\n/**\n * Return the model id an executor may send to a provider.\n *\n * Eval stamps {@link HARNESS_NATIVE_MODEL} into a profile when model selection is deliberately\n * delegated to the configured runtime. That marker belongs in experiment identity and cost\n * admission; it is not a provider model id.\n */\nexport function concreteModelId(model: string | undefined): string | undefined {\n if (model === undefined) return undefined\n const id = model.trim()\n return id.length > 0 && !isHarnessNativeModel(id) ? id : undefined\n}\n\n/** Whether a model value delegates selection to the chosen execution system. */\nfunction isHarnessNativeModel(model: string | undefined): boolean {\n return model?.trim() === HARNESS_NATIVE_MODEL\n}\n\n/** Return a profile's explicitly selected provider model, if it has one. */\nexport function concreteProfileModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n return concreteModelId(profile.model?.default)\n}\n\n/**\n * Return the model id for a direct provider request.\n *\n * A portable profile can qualify its model with the selected provider. The direct endpoint already\n * selects that provider, so remove only the exact matching prefix. Preserve every other prefix\n * because it can identify a provider-owned nested route, such as `anthropic/claude-sonnet`.\n */\nexport function profileProviderModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider?.trim()\n if (!model || !provider || !model.startsWith(`${provider}/`)) return model\n return concreteModelId(model.slice(provider.length + 1))\n}\n\n/** The full cli-bridge wire id declared by a profile: harness/provider/model. */\nexport function profileBridgeWireModel(\n profile: Pick<AgentProfile, 'harness' | 'model'>,\n): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider\n const harness = agentHarness(profile.harness)\n const modelWithoutHarness =\n model && harness && model.startsWith(`${harness}/`) ? model.slice(harness.length + 1) : model\n const providerModel = modelWithoutHarness\n ? provider && !modelWithoutHarness.startsWith(`${provider}/`)\n ? `${provider}/${modelWithoutHarness}`\n : modelWithoutHarness\n : undefined\n if (!harness) return providerModel\n if (!providerModel) return harness\n // Always add the harness segment: a provider may share the harness's name. opencode's own keyless\n // provider is `opencode`, so `opencode/glm-5.3-flash-free` is a provider/model pair; reading it as\n // already harness-prefixed sent `opencode/glm-5.3-flash-free`, cli-bridge removed the harness, and\n // opencode received the bare model and could not resolve it (\"Model not found\").\n return `${harness}/${providerModel}`\n}\n\n/**\n * Refuse an incomplete execution identity before any backend may fill it from ambient config.\n * `AgentProfile` is the sole behavioral authority: harness, provider, and concrete model all\n * participate in its digest. Eval's runtime-selected marker is a matrix-planning value, never an\n * executable model.\n */\nexport function assertExecutableAgentProfile(profile: AgentProfile, context: string): void {\n if (profile.harness === undefined) {\n throw new ConfigError(`${context}: AgentProfile.harness must be explicit before execution`)\n }\n const declared = profile.model?.default\n const model = concreteModelId(declared)\n if (!model) {\n const reason = isHarnessNativeModel(declared) ? 'runtime-selected' : 'missing'\n throw new ConfigError(\n `${context}: AgentProfile.model.default is ${reason}; execution requires a concrete model`,\n )\n }\n if (!profile.model?.provider?.trim()) {\n throw new ConfigError(\n `${context}: AgentProfile.model.provider must be explicit before execution`,\n )\n }\n}\n\n/**\n * Separate completion ceilings an exact profile may request.\n *\n * They are distinct because providers do not share one meaning for a single number: measured\n * through the Tangle Router on 2026-08-10, `glm-5.2` accepted `max_tokens: 8` and still billed 135\n * completion tokens — 132 reasoning, 3 visible — while `max_completion_tokens: 256` bounded the\n * total. A path that cannot enforce a requested ceiling refuses the run instead of sending a\n * number that means something else there.\n */\nexport interface ProfileTokenLimits {\n /** Visible answer tokens, from `AgentProfile.model.maxVisibleOutputTokens`. */\n readonly visible?: number\n /** Hidden reasoning tokens, from `AgentProfile.model.maxReasoningTokens`. */\n readonly reasoning?: number\n /** Visible and reasoning tokens together, from `AgentProfile.model.maxTotalOutputTokens`. */\n readonly total?: number\n}\n\n/** The ceilings one execution path actually sends, in the request fields it sends them as. */\nexport interface AppliedTokenLimits {\n /** Sent as `max_tokens`. */\n readonly maxTokens?: number\n /** Sent as `max_completion_tokens`. */\n readonly maxCompletionTokens?: number\n}\n\n/** What a path was asked to enforce and what it sent, for the execution receipt. */\nexport interface TokenLimitDecision {\n readonly requested: ProfileTokenLimits\n readonly applied: AppliedTokenLimits\n}\n\n/** The execution paths that lower a profile into a provider request. */\ntype ModelExecutionPath = 'router' | 'bridge' | 'sandbox' | 'provider'\n\n/** Generation and loop controls that may affect one model execution. */\nexport interface ProfileModelExecutionSettings {\n readonly temperature?: number\n /** Completion ceilings the profile requested. Empty when it requested none. */\n readonly tokenLimits: ProfileTokenLimits\n readonly retry?: ResolvedRouterRetryPolicy\n readonly seed?: number\n readonly toolChoice?: 'auto' | 'required' | 'none'\n readonly extraBody?: Readonly<Record<string, unknown>>\n /** Zero means no turn-count cap; conserved budgets and deadlines still apply. */\n readonly maxTurns?: number\n /**\n * Take each Router completion over SSE, with or without tools. The Router's request deadline ends\n * when response headers are committed, so a long thinking-model answer needs a stream to finish.\n * Requires the HTTP transport; an injected buffered `complete` transport is refused.\n */\n readonly stream?: boolean\n /**\n * This node's action space is CODE, not JSON tool calls (router-tools backend\n * only): the model is shown `tool_search` + `codemode` instead of the raw tool\n * set, and composes the granted handlers as one QuickJS program. `true` takes\n * host settings or engine defaults; an object can tighten host ceilings and\n * add direct-only tools. `false` selects ordinary tools for this node. Host\n * state and direct-only restrictions survive every enabled profile declaration.\n */\n readonly codeMode?: boolean | ProfileCodeModeSettings\n}\n\n/** The per-node code-mode controls a profile may pin — the seam's subset, minus\n * host-only (wasm/workerUrl) and executor-owned (store) options. */\nexport interface ProfileCodeModeSettings {\n /** Includes time in tools; at most 2,147,483,647 ms. */\n readonly timeoutMs?: number\n readonly memoryLimitBytes?: number\n /** Excess calls queue; Promise.all does not fail simply because the queue is full. */\n readonly concurrency?: number\n /** Bounds total admitted calls, including queued calls. */\n readonly maxCalls?: number\n /** These capabilities keep their direct model tools and are not callable from code. */\n readonly directTools?: ReadonlyArray<string>\n}\n\nconst PROFILE_MODEL_METADATA_KEYS = new Set([\n 'codeMode',\n 'extraBody',\n 'maxTurns',\n 'retry',\n 'seed',\n 'stream',\n 'temperature',\n 'toolChoice',\n])\n\n/**\n * Read execution controls from the exact profile and reject unknown controls.\n * Credential intent reaches environment providers unchanged; other paths cannot enforce it.\n * Backends receive endpoint/auth and executable ports only; they cannot silently alter behavior.\n */\nexport function profileModelExecutionSettings(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n path: ModelExecutionPath = 'router',\n): ProfileModelExecutionSettings {\n const metadata = profile.model?.metadata ?? {}\n if (metadata.maxTokens !== undefined) {\n throw new ConfigError(\n `${context}: AgentProfile.model.metadata.maxTokens is ambiguous across providers; declare AgentProfile.model.maxVisibleOutputTokens, maxReasoningTokens, or maxTotalOutputTokens instead`,\n )\n }\n const unknown = Object.keys(metadata).filter(\n (key) =>\n !PROFILE_MODEL_METADATA_KEYS.has(key) && !(path === 'provider' && key === 'credentialSource'),\n )\n if (unknown.length > 0) {\n throw new ConfigError(\n `${context}: unsupported AgentProfile.model.metadata fields: ${unknown.join(', ')}`,\n )\n }\n if (\n metadata.credentialSource !== undefined &&\n metadata.credentialSource !== 'managed' &&\n metadata.credentialSource !== 'subscription'\n ) {\n throw new ConfigError(\n `${context}: AgentProfile.model.metadata.credentialSource must be managed or subscription`,\n )\n }\n const temperature = finiteNumber(metadata.temperature, `${context}: temperature`)\n const tokenLimits = profileTokenLimits(profile, context)\n const retryInput = metadata.retry\n const retry =\n retryInput === undefined\n ? undefined\n : resolveRouterRetryPolicy(retryInput, `${context}: AgentProfile.model.metadata.retry`)\n const seed = safeInteger(metadata.seed, `${context}: seed`)\n const maxTurns = nonnegativeInteger(metadata.maxTurns, `${context}: maxTurns`)\n const stream = optionalBoolean(metadata.stream, `${context}: stream`)\n const toolChoice = metadata.toolChoice\n if (\n toolChoice !== undefined &&\n toolChoice !== 'auto' &&\n toolChoice !== 'required' &&\n toolChoice !== 'none'\n ) {\n throw new ConfigError(`${context}: toolChoice must be auto, required, or none`)\n }\n const extraBody = metadata.extraBody\n if (\n extraBody !== undefined &&\n (typeof extraBody !== 'object' || extraBody === null || Array.isArray(extraBody))\n ) {\n throw new ConfigError(`${context}: extraBody must be an object`)\n }\n const codeMode = profileCodeModeSettings(metadata.codeMode, context)\n return {\n ...(temperature !== undefined ? { temperature } : {}),\n tokenLimits,\n ...(retry !== undefined ? { retry } : {}),\n ...(seed !== undefined ? { seed } : {}),\n ...(toolChoice !== undefined ? { toolChoice } : {}),\n ...(extraBody !== undefined\n ? { extraBody: Object.freeze({ ...(extraBody as Record<string, unknown>) }) }\n : {}),\n ...(maxTurns !== undefined ? { maxTurns } : {}),\n ...(stream !== undefined ? { stream } : {}),\n ...(codeMode !== undefined ? { codeMode } : {}),\n }\n}\n\nconst PROFILE_CODE_MODE_KEYS = new Set([\n 'concurrency',\n 'directTools',\n 'maxCalls',\n 'memoryLimitBytes',\n 'timeoutMs',\n])\n\n/** Validate `AgentProfile.model.metadata.codeMode`: a boolean, or an object pinning\n * exactly the subset a node may choose (host-only wasm/workerUrl and the\n * executor-owned store are refused — those belong to the seam). */\nfunction profileCodeModeSettings(\n value: unknown,\n context: string,\n): boolean | ProfileCodeModeSettings | undefined {\n if (value === undefined) return undefined\n if (typeof value === 'boolean') return value\n const label = `${context}: codeMode`\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ConfigError(`${label} must be a boolean or an object of engine settings`)\n }\n const input = value as Record<string, unknown>\n const unknown = Object.keys(input).filter((key) => !PROFILE_CODE_MODE_KEYS.has(key))\n if (unknown.length > 0) {\n throw new ConfigError(\n `${label} refuses unsupported fields: ${unknown.join(', ')} (allowed: ${[...PROFILE_CODE_MODE_KEYS].join(', ')}; wasm/workerUrl/store belong to the executor seam)`,\n )\n }\n const timeoutMs = positiveInteger(input.timeoutMs, `${label}.timeoutMs`)\n const memoryLimitBytes = positiveInteger(input.memoryLimitBytes, `${label}.memoryLimitBytes`)\n const concurrency = positiveInteger(input.concurrency, `${label}.concurrency`)\n const maxCalls = positiveInteger(input.maxCalls, `${label}.maxCalls`)\n const directTools = input.directTools\n if (\n directTools !== undefined &&\n (!Array.isArray(directTools) || directTools.some((name) => typeof name !== 'string' || !name))\n ) {\n throw new ConfigError(`${label}.directTools must be an array of tool names`)\n }\n return Object.freeze({\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n ...(memoryLimitBytes !== undefined ? { memoryLimitBytes } : {}),\n ...(concurrency !== undefined ? { concurrency } : {}),\n ...(maxCalls !== undefined ? { maxCalls } : {}),\n ...(Array.isArray(directTools) ? { directTools: Object.freeze([...directTools]) } : {}),\n })\n}\n\n/**\n * Read the completion ceilings an exact profile declares. The Interface schema already refines\n * these fields, but a profile can reach an executor without a parse, so the same rules are\n * enforced here: positive integers, and no single ceiling above the total.\n */\nfunction profileTokenLimits(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n): ProfileTokenLimits {\n const model = profile.model\n const visible = positiveInteger(\n model?.maxVisibleOutputTokens,\n `${context}: maxVisibleOutputTokens`,\n )\n const reasoning = positiveInteger(model?.maxReasoningTokens, `${context}: maxReasoningTokens`)\n const total = positiveInteger(model?.maxTotalOutputTokens, `${context}: maxTotalOutputTokens`)\n if (total !== undefined) {\n for (const [name, value] of [\n ['maxVisibleOutputTokens', visible],\n ['maxReasoningTokens', reasoning],\n ] as const) {\n if (value !== undefined && value > total) {\n throw new ConfigError(\n `${context}: AgentProfile.model.${name} (${value}) exceeds maxTotalOutputTokens (${total})`,\n )\n }\n }\n }\n return {\n ...(visible !== undefined ? { visible } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n ...(total !== undefined ? { total } : {}),\n }\n}\n\n/**\n * Lower the requested ceilings onto one execution path, or refuse the run before any paid\n * transport.\n *\n * - Router and OpenAI-compatible routes send the visible ceiling as `max_tokens` and the total as\n * `max_completion_tokens`.\n * - The CLI Bridge lowers ONE completion cap into the run's model catalog, so it carries the total\n * as `max_tokens` and cannot bound the visible half on its own.\n * - The Sandbox and environment-provider paths expose no completion cap at all.\n * - No route publishes a reasoning-token budget, so a reasoning ceiling is refused everywhere.\n * `AgentProfile.model.reasoningEffort` is an intensity dial, not a token bound.\n */\nexport function enforceTokenLimits(\n limits: ProfileTokenLimits,\n path: ModelExecutionPath,\n context: string,\n): TokenLimitDecision {\n const refuse = (field: string, reason: string): never => {\n throw new ConfigError(\n `${context}: AgentProfile.model.${field} cannot be enforced on the ${path} path (${reason}); remove the ceiling or select a path that enforces it`,\n )\n }\n if (limits.reasoning !== undefined) {\n refuse('maxReasoningTokens', 'no route exposes a reasoning-token budget')\n }\n if (path === 'router') {\n return {\n requested: limits,\n applied: {\n ...(limits.visible !== undefined ? { maxTokens: limits.visible } : {}),\n ...(limits.total !== undefined ? { maxCompletionTokens: limits.total } : {}),\n },\n }\n }\n if (path === 'bridge') {\n if (limits.visible !== undefined) {\n refuse('maxVisibleOutputTokens', 'the bridge lowers one completion cap covering both halves')\n }\n return {\n requested: limits,\n applied: {\n ...(limits.total !== undefined ? { maxTokens: limits.total } : {}),\n },\n }\n }\n if (limits.visible !== undefined) refuse('maxVisibleOutputTokens', 'the backend accepts no cap')\n if (limits.total !== undefined) refuse('maxTotalOutputTokens', 'the backend accepts no cap')\n return { requested: limits, applied: {} }\n}\n\nfunction finiteNumber(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new ConfigError(`${context} must be a finite number`)\n }\n return value\n}\n\nfunction safeInteger(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value)) throw new ConfigError(`${context} must be a safe integer`)\n return value as number\n}\n\nfunction positiveInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 1) {\n throw new ConfigError(`${context} must be positive`)\n }\n return parsed\n}\n\nfunction nonnegativeInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 0) {\n throw new ConfigError(`${context} must be nonnegative`)\n }\n return parsed\n}\n\nfunction optionalBoolean(value: unknown, context: string): boolean | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'boolean') throw new ConfigError(`${context} must be boolean`)\n return value\n}\n\n/**\n * Throw a `ConfigError` when `allowed` is set, `model` is defined, and `model` is not a\n * member of `allowed`. No-op when `allowed` is unset (the unrestricted default) or when\n * `model` is undefined (nothing was configured to check).\n */\nexport function assertModelAllowed(\n model: string | undefined,\n allowed: readonly string[] | undefined,\n): void {\n if (!allowed || model === undefined) return\n if (!allowed.includes(model)) {\n throw new ConfigError(\n `model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`,\n )\n }\n}\n\n/** Check every canonical model-bearing field in a complete profile, including the models a\n * backend may select for cheap work, named subagents, or modes.\n *\n * Every compared value is a bare model id. The composed `harness/provider/model` wire id\n * (`profileBridgeWireModel`) is neither built nor compared here, so this admits any route that\n * declares an allowed id, and a qualified entry in `allowed` matches nothing. Route pinning\n * belongs to `SuperviseOptions.authorizeSpawn`. */\nexport function assertProfileModelsAllowed(\n profile: AgentProfile,\n allowed: readonly string[] | undefined,\n): void {\n assertModelAllowed(profile.model?.default, allowed)\n assertModelAllowed(profile.model?.small, allowed)\n if (profile.model?.default === 'tangle/auto') {\n const extra = profile.model.metadata?.extraBody\n const policy =\n extra !== null && typeof extra === 'object'\n ? (extra as Record<string, unknown>).auto\n : undefined\n for (const model of routerAutoDeclaredModels(policy)) assertModelAllowed(model, allowed)\n }\n for (const subagent of Object.values(profile.subagents ?? {})) {\n assertModelAllowed(subagent.model, allowed)\n }\n for (const mode of Object.values(profile.modes ?? {})) {\n assertModelAllowed(mode.model, allowed)\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,MAAM,qCAA0C,IAAI,IAAY,CAAC,UAAgC,CAAC;;;;AAKlG,SAAgB,iBAAmC,SAA6C;CAC9F,OAAO,WAAW,QAAQ,CAAC,mBAAmB,IAAI,OAAO;AAC3D;;;AAIA,SAAgB,aAA+B,SAA8C;CAC3F,OAAO,iBAAiB,OAAO,IAAI,UAAU,KAAA;AAC/C;;;ACpCA,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;;AAkBzB,SAAgB,6BAA6B,UAAkB,UAA2B;CACxF,MAAM,mBAAmB,mBAAmB,QAAQ;CACpD,MAAM,mBAAmB,mBAAmB,QAAQ;CACpD,IAAI,CAAC,oBAAoB,CAAC,kBAAkB,OAAO;CACnD,IACE,iBAAiB,aAAa,KAAA,MAC7B,iBAAiB,aAAa,iBAAiB,YAC9C,iBAAiB,iBAAiB,iBAAiB,eAErD,OAAO;CAET,OAAO,oBAAoB,iBAAiB,MAAM,iBAAiB,IAAI;AACzE;;AAGA,SAAgB,2BAA2B,SAAiB,MAAkC;CAC5F,MAAM,kBAAkB,mBAAmB,OAAO;CAClD,MAAM,eAAe,mBAAmB,IAAI;CAC5C,IAAI,CAAC,mBAAmB,CAAC,cAAc,OAAO,KAAA;CAC9C,IAAI,CAAC,oBAAoB,gBAAgB,MAAM,aAAa,IAAI,GAAG,OAAO,KAA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M,YAAY,OAAO,OAAO,QAAQ,aAAa,CAAC,CAAC,GAC1D,mBAAmB,SAAS,OAAO,OAAO;CAE5C,KAAK,MAAM,QAAQ,OAAO,OAAO,QAAQ,SAAS,CAAC,CAAC,GAClD,mBAAmB,KAAK,OAAO,OAAO;AAE1C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"profile-6OLpbjvV.js","names":["canonicalCandidateBytes","sha256Bytes","canonicalCandidateDigest"],"sources":["../src/candidate-execution/public-config.ts","../src/candidate-execution/system-prompt.ts","../src/candidate-execution/profile.ts"],"sourcesContent":["import type { AgentCandidateConfigValue } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\n\n/** Candidate execution has no private secret resolver; never lower a reference to argv or env. */\nexport function requirePublicCandidateConfigValue(\n value: AgentCandidateConfigValue,\n path: string,\n): string {\n if (value.kind !== 'public') {\n throw new ValidationError(\n `candidate ${path} requires a public value; secret references are unsupported`,\n )\n }\n return value.value\n}\n","import { posix } from 'node:path'\n\nimport type {\n AgentCandidateConfigValue,\n AgentCandidateLaunch,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentCandidateWorkspacePlan,\n HarnessId,\n} from '@tangle-network/agent-profile-materialize'\nimport { requirePublicCandidateConfigValue } from './public-config'\n\nconst SYSTEM_PROMPT_FILE = '.tangle/system-prompt.md'\nconst APPEND_SYSTEM_PROMPT_FILE = '.tangle/append-system-prompt.md'\n\n/**\n * One row describes the native process control for each prompt intent this adapter owns.\n * A row with no executor projection means the shared materializer already lowered the intent into\n * the signed workspace plan; this adapter still proves that the launch reaches the native binary.\n */\ninterface HarnessSystemPrompt {\n /** The native binary the launch must run for this projection to be provable. */\n readonly executable: string\n /** Apply a replacement prompt to the harness's own control. */\n readonly project: (\n plan: AgentCandidateWorkspacePlan,\n systemPrompt: string,\n systemPromptFilePath: string,\n ) => AgentCandidateWorkspacePlan\n /** Apply an addition without replacing the harness's own prompt. */\n readonly projectAppend?: (\n plan: AgentCandidateWorkspacePlan,\n appendSystemPrompt: string,\n appendSystemPromptFilePath: string,\n ) => AgentCandidateWorkspacePlan\n /** The materializer already projected replacement text into native plan files and flags. */\n readonly retainsProjectedSystemPrompt?: boolean\n /** Does caller argv already set a replacement control this projection would shadow? */\n readonly conflictsWithArgs: (values: readonly string[]) => boolean\n /** Does caller argv already set an additive control this projection would shadow? */\n readonly conflictsWithAppendArgs: (values: readonly string[]) => boolean\n}\n\nconst SYSTEM_PROMPT_FLAGS = ['--system-prompt', '--system-prompt-file'] as const\nconst APPEND_SYSTEM_PROMPT_FLAGS = [\n '--append-system-prompt',\n '--append-system-prompt-file',\n] as const\n\nfunction argsSetSystemPromptFlag(values: readonly string[]): boolean {\n return values.some((value) =>\n SYSTEM_PROMPT_FLAGS.some((flag) => value === flag || value.startsWith(`${flag}=`)),\n )\n}\n\nfunction argsSetAppendSystemPromptFlag(values: readonly string[]): boolean {\n return values.some((value) =>\n APPEND_SYSTEM_PROMPT_FLAGS.some((flag) => value === flag || value.startsWith(`${flag}=`)),\n )\n}\n\n/** Codex keys that can replace or contaminate the materializer's sealed instructions file. */\nconst CODEX_INSTRUCTION_KEYS = ['model_instructions_file', 'developer_instructions'] as const\n\nfunction argsSetCodexInstructionOverride(values: readonly string[]): boolean {\n for (let index = 0; index < values.length; index++) {\n const value = values[index]!\n const config =\n value === '-c' || value === '--config'\n ? values[index + 1]\n : value.startsWith('--config=')\n ? value.slice('--config='.length)\n : undefined\n if (\n config !== undefined &&\n CODEX_INSTRUCTION_KEYS.some((key) => config.trimStart().startsWith(`${key}=`))\n ) {\n return true\n }\n }\n return false\n}\n\nconst HARNESS_SYSTEM_PROMPTS = {\n 'claude-code': {\n executable: 'claude',\n project: (plan, systemPrompt, path) =>\n appendFlags(\n addPromptFile(plan, SYSTEM_PROMPT_FILE, systemPrompt),\n '--system-prompt-file',\n path,\n ),\n projectAppend: (plan, appendSystemPrompt, path) =>\n appendFlags(\n addPromptFile(plan, APPEND_SYSTEM_PROMPT_FILE, appendSystemPrompt),\n '--append-system-prompt-file',\n path,\n ),\n conflictsWithArgs: argsSetSystemPromptFlag,\n conflictsWithAppendArgs: argsSetAppendSystemPromptFlag,\n },\n /** OpenCode's bound primary agent is already selected by the materializer's --agent flag. */\n opencode: {\n executable: 'opencode',\n project: (plan) => plan,\n retainsProjectedSystemPrompt: true,\n conflictsWithArgs: (values) =>\n values.some((value) => value === '--agent' || value.startsWith('--agent=')),\n conflictsWithAppendArgs: argsSetAppendSystemPromptFlag,\n },\n pi: {\n executable: 'pi',\n project: (plan, systemPrompt, path) =>\n appendFlags(addPromptFile(plan, SYSTEM_PROMPT_FILE, systemPrompt), '--system-prompt', path),\n projectAppend: (plan, appendSystemPrompt, path) =>\n appendFlags(\n addPromptFile(plan, APPEND_SYSTEM_PROMPT_FILE, appendSystemPrompt),\n '--append-system-prompt',\n path,\n ),\n conflictsWithArgs: argsSetSystemPromptFlag,\n conflictsWithAppendArgs: argsSetAppendSystemPromptFlag,\n },\n prime: {\n executable: 'prime-agent',\n project: (plan, systemPrompt, path) =>\n appendFlags(addPromptFile(plan, SYSTEM_PROMPT_FILE, systemPrompt), '--system-prompt', path),\n projectAppend: (plan, appendSystemPrompt, path) =>\n appendFlags(\n addPromptFile(plan, APPEND_SYSTEM_PROMPT_FILE, appendSystemPrompt),\n '--append-system-prompt',\n path,\n ),\n conflictsWithArgs: argsSetSystemPromptFlag,\n conflictsWithAppendArgs: argsSetAppendSystemPromptFlag,\n },\n /** Gemini's file and env lowering is materializer-owned; this row supplies the launch proof. */\n gemini: {\n executable: 'gemini',\n project: (plan) => plan,\n conflictsWithArgs: argsSetSystemPromptFlag,\n conflictsWithAppendArgs: argsSetAppendSystemPromptFlag,\n },\n} as const satisfies Partial<Record<HarnessId, HarnessSystemPrompt>>\n\ninterface MaterializedPromptDelivery {\n readonly executable: string\n readonly delivered: (plan: AgentCandidateWorkspacePlan) => boolean\n readonly conflictsWithArgs: (values: readonly string[]) => boolean\n}\n\n/**\n * These controls are lowered by agent-profile-materialize into files plus launch inputs. The\n * candidate adapter does not own the spawn, so it must reject an arbitrary entrypoint even when\n * the plan has the right bytes: only the native binary can make those inputs effective.\n */\nconst MATERIALIZED_PROMPT_DELIVERIES = {\n codex: {\n executable: 'codex',\n delivered: (plan) =>\n plan.files.some((file) => file.relPath === '.codex/system-prompt.md') &&\n plan.flags.some(\n (flag) =>\n requirePublicCandidateConfigValue(flag, 'profile.flags') ===\n 'model_instructions_file=.codex/system-prompt.md',\n ),\n conflictsWithArgs: argsSetCodexInstructionOverride,\n },\n gemini: {\n executable: 'gemini',\n delivered: (plan) => {\n const env = plan.env.GEMINI_SYSTEM_MD\n return (\n plan.files.some((file) => file.relPath === '.gemini/system.md') &&\n env !== undefined &&\n requirePublicCandidateConfigValue(env, 'profile.env.GEMINI_SYSTEM_MD') === '1'\n )\n },\n conflictsWithArgs: argsSetSystemPromptFlag,\n },\n} as const satisfies Partial<Record<HarnessId, MaterializedPromptDelivery>>\n\n/** Project both prompt intents onto their distinct native process controls. */\nexport function projectCandidatePromptIntents(\n plan: AgentCandidateWorkspacePlan,\n launch: AgentCandidateLaunch,\n systemPromptFilePath: string,\n requestedSystemPrompt: string | undefined = plan.systemPrompt === undefined\n ? undefined\n : requirePublicCandidateConfigValue(plan.systemPrompt, 'profile.systemPrompt'),\n requestedAppendSystemPrompt: string | undefined = plan.appendSystemPrompt === undefined\n ? undefined\n : requirePublicCandidateConfigValue(plan.appendSystemPrompt, 'profile.appendSystemPrompt'),\n): AgentCandidateWorkspacePlan {\n const systemPrompt = plan.systemPrompt\n const appendSystemPrompt = plan.appendSystemPrompt\n const delivery = MATERIALIZED_PROMPT_DELIVERIES[\n plan.harness as keyof typeof MATERIALIZED_PROMPT_DELIVERIES\n ] as MaterializedPromptDelivery | undefined\n\n if (systemPrompt === undefined && delivery?.delivered(plan)) {\n assertProvableNativeLaunch(plan.harness, delivery.executable, launch, 'replacement')\n assertNoShadowingArgs(plan.harness, delivery.conflictsWithArgs, launch, 'replacement')\n if (requestedSystemPrompt === undefined) return plan\n return plan\n }\n\n if (requestedSystemPrompt === undefined && requestedAppendSystemPrompt === undefined) {\n return plan\n }\n\n const projection = HARNESS_SYSTEM_PROMPTS[plan.harness as keyof typeof HARNESS_SYSTEM_PROMPTS] as\n | HarnessSystemPrompt\n | undefined\n if (!projection) {\n throw new Error(`candidate system prompt has no native launch projection for ${plan.harness}`)\n }\n\n const requestedReplacement = requestedSystemPrompt !== undefined\n if (requestedReplacement && systemPrompt === undefined) {\n throw new Error(\n `profile materializer did not deliver the candidate system prompt for ${plan.harness}`,\n )\n }\n if (systemPrompt !== undefined && requestedSystemPrompt === undefined) {\n throw new Error(\n `profile materializer added an unexpected candidate system prompt for ${plan.harness}`,\n )\n }\n if (\n systemPrompt !== undefined &&\n requirePublicCandidateConfigValue(systemPrompt, 'profile.systemPrompt') !==\n requestedSystemPrompt\n ) {\n throw new Error('profile materializer changed the candidate system prompt')\n }\n if (\n appendSystemPrompt !== undefined &&\n requirePublicCandidateConfigValue(appendSystemPrompt, 'profile.appendSystemPrompt') !==\n requestedAppendSystemPrompt\n ) {\n throw new Error('profile materializer changed the candidate append system prompt')\n }\n\n const intent = requestedReplacement ? 'replacement' : 'addition'\n assertProvableNativeLaunch(plan.harness, projection.executable, launch, intent)\n const launchArgs = (launch.args ?? []).map((value, index) =>\n requirePublicCandidateConfigValue(value, `launch.args[${index}]`),\n )\n if (requestedReplacement && projection.conflictsWithArgs(launchArgs)) {\n throw new Error(\n `${plan.harness} launch arguments conflict with the candidate profile system prompt`,\n )\n }\n if (requestedAppendSystemPrompt !== undefined && projection.conflictsWithAppendArgs(launchArgs)) {\n throw new Error(\n `${plan.harness} launch arguments conflict with the candidate profile append system prompt`,\n )\n }\n\n let projected = plan\n if (systemPrompt !== undefined) {\n projected = projection.project(\n projection.retainsProjectedSystemPrompt\n ? projected\n : omitPromptIntent(projected, 'systemPrompt'),\n requirePublicCandidateConfigValue(systemPrompt, 'profile.systemPrompt'),\n systemPromptFilePath,\n )\n }\n if (appendSystemPrompt !== undefined) {\n if (!projection.projectAppend) {\n throw new Error(\n `candidate append system prompt has no native launch projection for ${plan.harness}`,\n )\n }\n projected = projection.projectAppend(\n omitPromptIntent(projected, 'appendSystemPrompt'),\n requirePublicCandidateConfigValue(appendSystemPrompt, 'profile.appendSystemPrompt'),\n posix.join(posix.dirname(systemPromptFilePath), 'append-system-prompt.md'),\n )\n }\n // The source-profile digest binds authored values. Remove executor handoff fields only after\n // converting them into native controls; materializer-owned controls remain visible in the plan.\n return projected\n}\n\nfunction assertProvableNativeLaunch(\n harness: string,\n expectedExecutable: string,\n launch: AgentCandidateLaunch,\n intent: 'replacement' | 'addition',\n): asserts launch is AgentCandidateLaunch & { kind: 'container-command' } {\n if (launch.kind !== 'container-command') {\n throw new Error(`candidate-entrypoint launch cannot prove ${harness} system-prompt ${intent}`)\n }\n if (\n launch.executable !== expectedExecutable &&\n !(\n posix.isAbsolute(launch.executable) &&\n posix.basename(launch.executable) === expectedExecutable\n )\n ) {\n throw new Error(\n `${harness} system-prompt ${intent} requires the native ${expectedExecutable} executable`,\n )\n }\n}\n\nfunction assertNoShadowingArgs(\n harness: string,\n conflictsWithArgs: (values: readonly string[]) => boolean,\n launch: Extract<AgentCandidateLaunch, { kind: 'container-command' }>,\n intent: 'replacement' | 'addition',\n): void {\n if (\n conflictsWithArgs(\n (launch.args ?? []).map((value, index) =>\n requirePublicCandidateConfigValue(value, `launch.args[${index}]`),\n ),\n )\n ) {\n throw new Error(\n `${harness} launch arguments conflict with the candidate profile ${intent === 'replacement' ? 'system' : 'append system'} prompt`,\n )\n }\n}\n\nfunction omitPromptIntent(\n plan: AgentCandidateWorkspacePlan,\n intent: 'systemPrompt' | 'appendSystemPrompt',\n): AgentCandidateWorkspacePlan {\n const projected = { ...plan }\n delete projected[intent]\n return projected\n}\n\nfunction appendFlags(\n plan: AgentCandidateWorkspacePlan,\n ...values: string[]\n): AgentCandidateWorkspacePlan {\n return {\n ...plan,\n flags: [...plan.flags, ...values.map(publicValue)],\n }\n}\n\nfunction publicValue(value: string): AgentCandidateConfigValue {\n return { kind: 'public', value }\n}\n\nfunction addPromptFile(\n plan: AgentCandidateWorkspacePlan,\n relPath: string,\n prompt: string,\n): AgentCandidateWorkspacePlan {\n // Candidate argv rejects control characters. Native prompt-file loading preserves multiline\n // bytes without weakening the shared process schema.\n if (plan.files.some((file) => file.relPath === relPath)) {\n throw new Error(`candidate profile conflicts with reserved ${relPath}`)\n }\n return {\n ...plan,\n files: [\n ...plan.files,\n {\n relPath,\n content: prompt,\n source: 'generated',\n },\n ],\n }\n}\n","import { posix } from 'node:path'\nimport type {\n AgentCandidateConfigValue,\n AgentCandidateExecutionPlanMaterial,\n AgentCandidateLaunch,\n AgentCandidateProfile,\n AgentCandidateProfileActivation,\n AgentCandidateProfilePlanEvidence,\n AgentCandidateResourceRef,\n AgentProfile,\n AgentProfileConfigValue,\n AgentProfileDiff,\n AgentProfileMcpServer,\n AgentProfileResourceRef,\n HarnessType,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateProfileActivationSchema,\n agentCandidateProfileSchema,\n agentProfileDiffSchema,\n agentProfileSchema,\n applyAgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentCandidateWorkspacePlan,\n HarnessId,\n} from '@tangle-network/agent-profile-materialize'\nimport {\n isMaterializerHarness,\n materializeCandidateProfile,\n resolvePiRuntimePaths,\n} from '@tangle-network/agent-profile-materialize'\nimport {\n assertSandboxProfileCompatibility,\n refuseSandboxProfileField,\n} from '../runtime/sandbox-profile-compat'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n embeddedCandidateArtifact,\n immutableCandidateValue,\n omitTopLevelDigest,\n sha256Bytes,\n} from './digest'\nimport { requirePublicCandidateConfigValue } from './public-config'\nimport { projectCandidatePromptIntents } from './system-prompt'\nimport type { AgentCandidateTaskExecution, VerifiedAgentCandidate } from './types'\n\nexport function candidateMaterializerHarness(harness: HarnessType): HarnessId {\n if (!isMaterializerHarness(harness)) {\n throw new Error(\n `sealed candidate profile materialization is unsupported for harness ${harness}`,\n )\n }\n return harness\n}\n\n/** Runtime applies the materializer's launch flags to the candidate process. */\nconst CANDIDATE_PROFILE_MATERIALIZER_BINDS = ['systemPrompt'] as const\nexport const PI_CANDIDATE_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR'\nexport const PI_CANDIDATE_SESSION_DIR_ENV = 'PI_CODING_AGENT_SESSION_DIR'\n\ninterface MaterializeAgentCandidateProfilePlanOptions {\n profile: AgentCandidateProfile\n harness: HarnessType\n launch: AgentCandidateLaunch\n workspace: 'task' | 'candidate'\n workspaces: {\n taskRoot: string\n candidateRoot?: string\n }\n resolvedResources?: ReadonlyMap<Sha256Digest, string>\n}\n\n/** Derive the exact native profile plan used by preparation and later evidence checks. */\nexport function materializeAgentCandidateProfilePlan(\n options: MaterializeAgentCandidateProfilePlanOptions,\n): AgentCandidateWorkspacePlan {\n const root =\n options.workspace === 'task' ? options.workspaces.taskRoot : options.workspaces.candidateRoot\n if (!root) throw new Error('candidate profile target is missing its execution workspace root')\n const plan = materializeCandidateProfile(\n options.profile,\n candidateMaterializerHarness(options.harness),\n {\n binds: CANDIDATE_PROFILE_MATERIALIZER_BINDS,\n resolvedResources: options.resolvedResources,\n },\n )\n return projectCandidatePromptIntents(\n plan,\n options.launch,\n posix.join(root, '.tangle/system-prompt.md'),\n options.profile.prompt?.systemPrompt,\n options.profile.prompt?.appendSystemPrompt,\n )\n}\n\n/** Resolve the private Pi roots needed by an agent-root profile plan. */\nexport function candidateProfileAgentPaths(\n plan: {\n harness: HarnessType\n files: ReadonlyArray<{ root?: 'agent' | 'workspace' }>\n },\n runtimeHome: string | undefined,\n): { agentDir: string; sessionDir: string } | undefined {\n if (!plan.files.some((file) => file.root === 'agent')) return undefined\n if (plan.harness !== 'pi') {\n throw new Error(`candidate profile agent-root files are unsupported for ${plan.harness}`)\n }\n if (runtimeHome === undefined) {\n throw new Error('candidate profile agent-root files require executionRoots.profileRoot')\n }\n return resolvePiRuntimePaths(runtimeHome)\n}\n\n/** Bind exact native profile text to the canonical plan captured during preparation. */\nexport function createAgentCandidateProfileActivation(\n plan: AgentCandidateWorkspacePlan,\n profilePlan: AgentCandidateProfilePlanEvidence,\n): AgentCandidateProfileActivation {\n const sourceByIdentity = new Map(\n plan.files.map((file) => [profileFileIdentity(file.root, file.relPath), file]),\n )\n if (sourceByIdentity.size !== plan.files.length) {\n throw new Error('candidate profile activation contains duplicate rooted native file paths')\n }\n const files = profilePlan.material.files.map((expected) => {\n const source = sourceByIdentity.get(profileFileIdentity(expected.root, expected.relPath))\n if (!source) {\n throw new Error(\n `candidate profile activation is missing ${profileFileLabel(expected.root, expected.relPath)}`,\n )\n }\n const mode = source.mode ?? 0o644\n if (!Number.isSafeInteger(mode) || mode < 0 || mode > 0o777) {\n throw new Error(\n `candidate profile activation has invalid mode for ${profileFileLabel(expected.root, expected.relPath)}`,\n )\n }\n return { path: expected.relPath, mode, content: source.content }\n })\n if (files.length !== plan.files.length) {\n throw new Error('candidate profile activation contains unplanned native files')\n }\n return parseAgentCandidateProfileActivation(\n canonicalCandidateDocument<AgentCandidateProfileActivation>({\n kind: 'agent-candidate-profile-activation',\n profilePlan,\n files,\n }).value,\n profilePlan.digest,\n )\n}\n\nfunction profileFileIdentity(root: 'agent' | 'workspace' | undefined, relPath: string): string {\n return `${root ?? 'workspace'}\\0${relPath}`\n}\n\nfunction profileFileLabel(root: 'agent' | 'workspace' | undefined, relPath: string): string {\n return root === 'agent' ? `agent:${relPath}` : relPath\n}\n\n/** Parse and check every native file hash plus both canonical document digests. */\nexport function parseAgentCandidateProfileActivation(\n input: unknown,\n expectedProfilePlanDigest?: AgentCandidateProfilePlanEvidence['digest'],\n): AgentCandidateProfileActivation {\n const activation = agentCandidateProfileActivationSchema.parse(input)\n const planBytes = canonicalCandidateBytes(activation.profilePlan.material)\n const profilePlanArtifact = activation.profilePlan.artifact\n if (\n sha256Bytes(planBytes) !== activation.profilePlan.digest ||\n profilePlanArtifact.sha256 !== activation.profilePlan.digest ||\n profilePlanArtifact.byteLength !== planBytes.byteLength ||\n ('content' in profilePlanArtifact &&\n !Buffer.from(profilePlanArtifact.content, 'base64').equals(Buffer.from(planBytes))) ||\n (expectedProfilePlanDigest !== undefined &&\n activation.profilePlan.digest !== expectedProfilePlanDigest)\n ) {\n throw new Error('candidate profile activation has an invalid canonical profile plan')\n }\n if (canonicalCandidateDigest(omitTopLevelDigest(activation)) !== activation.digest) {\n throw new Error('candidate profile activation digest does not match')\n }\n return immutableCandidateValue(activation)\n}\n\nconst CANDIDATE_PROFILE_DIRECT_FIELDS = [\n 'name',\n 'description',\n 'version',\n 'tags',\n 'prompt',\n 'harness',\n 'permissions',\n 'tools',\n 'confidential',\n] as const\n\n/** Convert only behavior-preserving generic profile fields into the closed candidate contract. */\nexport function freezeGenericAgentCandidateProfile(input: AgentProfile): AgentCandidateProfile {\n assertSandboxProfileCompatibility(input)\n const profile = parseExactAgentProfile(input, 'profile')\n return candidateProfileFromGenericProfile(profile)\n}\n\n/**\n * Keep every generic-profile-to-candidate conversion in one place.\n * Callers use this both when sealing a new bundle and when proving a measured\n * profile is exactly the profile in an existing candidate.\n */\nfunction candidateProfileFromGenericProfile(profile: AgentProfile): AgentCandidateProfile {\n assertResolvedKnowledgeResources(profile.resources)\n if (profile.connections !== undefined) unsupportedProfileField('connections')\n if (profile.metadata !== undefined) unsupportedProfileField('metadata')\n if (profile.extensions !== undefined) unsupportedProfileField('extensions')\n if (profile.model?.metadata !== undefined) unsupportedProfileField('model.metadata')\n\n const candidate: Record<string, unknown> = {}\n copyDirectProfileFields(candidate, profile as Record<string, unknown>)\n if (profile.model) {\n const { metadata: _metadata, ...model } = profile.model\n candidate.model = model\n }\n if (profile.mcp) candidate.mcp = freezeMcpServers(profile.mcp)\n if (profile.subagents) {\n candidate.subagents = Object.fromEntries(\n Object.entries(profile.subagents).map(([name, subagent]) => {\n if (subagent.metadata !== undefined) unsupportedProfileField(`subagents.${name}.metadata`)\n const { metadata: _metadata, ...value } = subagent\n return [name, value]\n }),\n )\n }\n if (profile.resources) candidate.resources = freezeResources(profile.resources)\n if (profile.hooks && Object.values(profile.hooks).some((commands) => commands.length > 0)) {\n throw new Error(\n 'generic AgentProfile hooks cannot be safely tokenized; use a candidate-profile source with executable/args',\n )\n }\n if (profile.hooks) candidate.hooks = profile.hooks\n if (profile.modes) {\n candidate.modes = Object.fromEntries(\n Object.entries(profile.modes).map(([name, mode]) => {\n if (mode.metadata !== undefined) unsupportedProfileField(`modes.${name}.metadata`)\n const { metadata: _metadata, ...value } = mode\n return [name, value]\n }),\n )\n }\n const parsed = parseExactCandidateProfile(candidate)\n return parsed\n}\n\n/** Prove the measured generic profile and sealed candidate profile describe the same behavior. */\nexport function assertCandidateProfileBinding(\n measuredInput: unknown,\n bundled: AgentCandidateProfile,\n): void {\n assertSandboxProfileCompatibility(measuredInput)\n const measured = parseExactAgentProfile(measuredInput, 'measured agent profile')\n const expected = candidateProfileFromGenericProfile(measured)\n if (canonicalCandidateDigest(expected) !== canonicalCandidateDigest(bundled)) {\n throw new Error('measured agent profile does not match sealed candidate profile')\n }\n}\n\n/** Parse a complete profile without silently discarding unsupported fields. */\nexport function parseExactAgentProfile(input: unknown, label: string): AgentProfile {\n let parsed: AgentProfile\n try {\n parsed = agentProfileSchema.parse(input) as AgentProfile\n } catch (cause) {\n throw new Error(`${label} contains unsupported or non-canonical fields`, { cause })\n }\n assertCanonicalParse(input, parsed, label)\n return parsed\n}\n\n/** Parse a profile diff without silently discarding unsupported fields. */\nexport function parseExactAgentProfileDiff(input: unknown, label: string): AgentProfileDiff {\n let parsed: AgentProfileDiff\n try {\n parsed = agentProfileDiffSchema.parse(input) as AgentProfileDiff\n } catch (cause) {\n throw new Error(`${label} contains unsupported or non-canonical fields`, { cause })\n }\n assertCanonicalParse(input, parsed, label)\n return parsed\n}\n\n/** Apply one exact diff and reject any value that cannot be preserved canonically. */\nexport function applyExactAgentProfileDiff(\n baseInput: unknown,\n diffInput: unknown,\n label: string,\n): AgentProfile {\n const base = parseExactAgentProfile(baseInput, `${label} base profile`)\n const diff = parseExactAgentProfileDiff(diffInput, `${label} diff`)\n const applied = omitUndefinedObjectFields(applyAgentProfileDiff(base, diff), label)\n return parseExactAgentProfile(applied, `${label} result`)\n}\n\n/** Parse a candidate profile without silently discarding unsupported or non-canonical fields. */\nexport function parseExactCandidateProfile(input: unknown): AgentCandidateProfile {\n const parsed = agentCandidateProfileSchema.parse(input)\n assertCanonicalParse(input, parsed, 'candidate profile')\n return parsed\n}\n\n/** Reject profile fields whose behavioral effect is not yet proven by candidate executors. */\nexport function assertCandidateProfileExecutionSupport(profile: AgentCandidateProfile): void {\n assertResolvedKnowledgeResources(profile.resources)\n assertSandboxProfileCompatibility(profile)\n const fields = ['tools', 'permissions', 'modes', 'confidential'] as const\n const unsupported = fields.filter((field) => hasEntries(profile[field]))\n if (unsupported.length > 0) {\n throw new Error(\n `candidate execution cannot prove in-session effects for non-empty AgentProfile fields: ${unsupported.join(', ')}`,\n )\n }\n}\n\n/** Convert the candidate profile contract into the portable interface profile it represents. */\nexport function agentCandidateProfileAsAgentProfile(\n candidate: AgentCandidateProfile,\n): AgentProfile {\n assertResolvedKnowledgeResources(candidate.resources)\n assertSandboxProfileCompatibility(candidate)\n const output: Record<string, unknown> = {}\n copyDirectProfileFields(output, candidate as unknown as Record<string, unknown>)\n if (candidate.model) output.model = { ...candidate.model }\n if (candidate.mcp) {\n output.mcp = Object.fromEntries(\n Object.entries(candidate.mcp).map(([name, server]) => [\n name,\n {\n ...server,\n // Candidate config values ({kind:'public', value}) are already valid\n // AgentProfileConfigValue entries under interface >=0.40 — clone them\n // rather than unwrapping to plain strings, which the 0.40 profile\n // schema rejects.\n ...(server.args ? { args: server.args.map((value) => ({ ...value })) } : {}),\n ...(server.env ? { env: cloneRecord(server.env) } : {}),\n },\n ]),\n )\n }\n if (candidate.subagents) output.subagents = cloneRecord(candidate.subagents)\n if (candidate.modes) output.modes = cloneRecord(candidate.modes)\n if (candidate.hooks) {\n output.hooks = Object.fromEntries(\n Object.entries(candidate.hooks).map(([event, hooks]) => [\n event,\n hooks.map(({ executable, args, env, ...hook }) => ({\n ...hook,\n command: [\n executable,\n ...(args ?? []).map((value, index) =>\n requirePublicCandidateConfigValue(value, `hooks.${event}.args[${index}]`),\n ),\n ]\n .map(shellQuote)\n .join(' '),\n // Hook env stays in config-value form: the 0.40 profile hook contract\n // types env as Record<string, AgentProfileConfigValue>.\n ...(env ? { env: cloneRecord(env) } : {}),\n })),\n ]),\n )\n }\n if (candidate.resources) {\n if (candidate.resources.failOnError !== true) {\n throw new Error('sealed candidate profile contains fields unsupported by generic profiles')\n }\n output.resources = {\n failOnError: true,\n ...(candidate.resources.files\n ? {\n files: candidate.resources.files.map((file) => ({\n ...file,\n resource: publicResource(file.resource),\n })),\n }\n : {}),\n ...(candidate.resources.tools\n ? { tools: candidate.resources.tools.map(publicResource) }\n : {}),\n ...(candidate.resources.skills\n ? { skills: candidate.resources.skills.map(publicResource) }\n : {}),\n ...(candidate.resources.agents\n ? { agents: candidate.resources.agents.map(publicResource) }\n : {}),\n ...(candidate.resources.commands\n ? { commands: candidate.resources.commands.map(publicResource) }\n : {}),\n ...(candidate.resources.instructions !== undefined\n ? {\n instructions:\n typeof candidate.resources.instructions === 'string'\n ? candidate.resources.instructions\n : publicResource(candidate.resources.instructions),\n }\n : {}),\n }\n }\n return output as AgentProfile\n}\n\n/** Recursively remove undefined object fields while refusing undefined array entries. */\nexport function omitUndefinedObjectFields(value: unknown, path: string): unknown {\n if (Array.isArray(value)) {\n return value.map((entry, index) => {\n if (entry === undefined) {\n throw new Error(`${path} produced an undefined array entry at ${index}`)\n }\n return omitUndefinedObjectFields(entry, `${path}[${index}]`)\n })\n }\n if (value === null || typeof value !== 'object') return value\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .map(([key, entry]) => [key, omitUndefinedObjectFields(entry, `${path}.${key}`)]),\n )\n}\n\nfunction freezeMcpServers(servers: Record<string, AgentProfileMcpServer>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(servers).map(([name, server]) => {\n if (server.transport !== undefined && server.transport !== 'stdio') {\n unsupportedProfileField(`mcp.${name}.transport=${server.transport}`)\n }\n if (server.url !== undefined) unsupportedProfileField(`mcp.${name}.url`)\n if (server.headers !== undefined) unsupportedProfileField(`mcp.${name}.headers`)\n if (server.metadata !== undefined) unsupportedProfileField(`mcp.${name}.metadata`)\n return [\n name,\n {\n ...(server.transport ? { transport: server.transport } : {}),\n ...(server.command ? { command: server.command } : {}),\n ...(server.args\n ? {\n args: server.args.map((value, index) =>\n candidatePublicValue(value, `mcp.${name}.args[${index}]`),\n ),\n }\n : {}),\n ...(server.env ? { env: mapCandidatePublicValues(server.env, `mcp.${name}.env`) } : {}),\n ...(server.cwd ? { cwd: server.cwd } : {}),\n ...(server.enabled === undefined ? {} : { enabled: server.enabled }),\n },\n ]\n }),\n )\n}\n\n/** A newer peer may admit knowledge pins that these candidate conversions cannot preserve. */\nfunction assertResolvedKnowledgeResources(resources: unknown): void {\n if (\n resources !== null &&\n typeof resources === 'object' &&\n 'knowledge' in resources &&\n resources.knowledge !== undefined\n ) {\n throw new Error(\n 'candidate profile resources.knowledge must be owner-authorized and resolved before candidate conversion or execution',\n )\n }\n}\n\nfunction freezeResources(resources: NonNullable<AgentProfile['resources']>): unknown {\n if (resources.failOnError !== true) {\n throw new Error('candidate profile resources require failOnError: true')\n }\n return {\n failOnError: true,\n ...(resources.files\n ? {\n files: resources.files.map((file) => ({\n ...file,\n resource: freezeResource(file.resource),\n })),\n }\n : {}),\n ...(resources.tools ? { tools: resources.tools.map(freezeResource) } : {}),\n ...(resources.skills ? { skills: resources.skills.map(freezeResource) } : {}),\n ...(resources.agents ? { agents: resources.agents.map(freezeResource) } : {}),\n ...(resources.commands ? { commands: resources.commands.map(freezeResource) } : {}),\n ...(resources.instructions === undefined\n ? {}\n : {\n instructions:\n typeof resources.instructions === 'string'\n ? resources.instructions\n : freezeResource(resources.instructions),\n }),\n }\n}\n\nfunction freezeResource(resource: AgentProfileResourceRef): AgentCandidateResourceRef {\n if (resource.kind === 'github') {\n throw new Error(\n 'generic GitHub profile resources do not carry byte identity; use a candidate-profile source with a pinned commit, digest, and byte length',\n )\n }\n const bytes = Buffer.from(resource.content, 'utf8')\n return {\n ...resource,\n sha256: embeddedCandidateArtifact(bytes).sha256,\n byteLength: bytes.byteLength,\n }\n}\n\nfunction copyDirectProfileFields(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): void {\n for (const key of CANDIDATE_PROFILE_DIRECT_FIELDS) {\n if (source[key] !== undefined) target[key] = source[key]\n }\n}\n\nfunction assertCanonicalParse(input: unknown, parsed: unknown, label: string): void {\n if (!Buffer.from(canonicalCandidateBytes(input)).equals(canonicalCandidateBytes(parsed))) {\n throw new Error(`${label} contains unsupported or non-canonical fields`)\n }\n}\n\nfunction publicResource(resource: AgentCandidateResourceRef): unknown {\n if (resource.kind === 'inline') {\n return { kind: 'inline', name: resource.name, content: resource.content }\n }\n return {\n kind: 'github',\n repository: `${resource.repository.owner}/${resource.repository.repo}`,\n path: resource.path,\n ref: resource.commit,\n ...(resource.name ? { name: resource.name } : {}),\n }\n}\n\n/** Freeze one profile config value into the candidate's PUBLIC-only config\n * shape. A secret-ref is refused, never silently dropped or unwrapped. */\nfunction candidatePublicValue(\n value: AgentProfileConfigValue,\n path: string,\n): { kind: 'public'; value: string } {\n if (value.kind !== 'public') refuseSandboxProfileField(`${path} (${value.kind})`)\n return { kind: 'public', value: value.value }\n}\n\nfunction mapCandidatePublicValues(\n values: Record<string, AgentProfileConfigValue>,\n pathPrefix: string,\n): Record<string, { kind: 'public'; value: string }> {\n return Object.fromEntries(\n Object.entries(values).map(([name, value]) => [\n name,\n candidatePublicValue(value, `${pathPrefix}.${name}`),\n ]),\n )\n}\n\nfunction cloneRecord<T>(values: Record<string, T>): Record<string, T> {\n return Object.fromEntries(\n Object.entries(values).map(([key, value]) => [key, { ...value }]),\n ) as Record<string, T>\n}\n\nfunction hasEntries(value: unknown): boolean {\n return value !== undefined && value !== null && typeof value === 'object'\n ? Object.keys(value).length > 0\n : false\n}\n\nfunction shellQuote(value: string): string {\n return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replaceAll(\"'\", `'\"'\"'`)}'`\n}\n\nfunction unsupportedProfileField(path: string): never {\n throw new Error(\n `generic AgentProfile field ${path} is not representable in a sealed candidate profile`,\n )\n}\n\nexport function buildLaunch(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n profileFlags: AgentCandidateConfigValue[],\n): { executable: string; args: AgentCandidateConfigValue[] } {\n const launch = candidate.bundle.execution.launch\n if (launch.kind === 'container-command') {\n return { executable: launch.executable, args: [...(launch.args ?? []), ...profileFlags] }\n }\n const candidateRoot = task.executionRoots.candidateRoot\n if (!candidateRoot) throw new Error('candidate entrypoint requires a container candidate root')\n const entrypoint = posix.join(candidateRoot, launch.entrypoint)\n const candidateArgs = launch.args ?? []\n if (launch.interpreter) {\n return {\n executable: launch.interpreter,\n args: [{ kind: 'public', value: entrypoint }, ...candidateArgs, ...profileFlags],\n }\n }\n return { executable: entrypoint, args: [...candidateArgs, ...profileFlags] }\n}\n\nexport function modelRoutes(\n profile: VerifiedAgentCandidate['bundle']['profile'],\n requested: string,\n): AgentCandidateExecutionPlanMaterial['model']['routes'] {\n const routes: AgentCandidateExecutionPlanMaterial['model']['routes'] = [\n { kind: 'primary', requested },\n ]\n if (profile.model?.small) routes.push({ kind: 'small', requested })\n for (const name of Object.keys(profile.modes ?? {}).sort()) {\n if (profile.modes?.[name]?.model) routes.push({ kind: 'mode', name, requested })\n }\n for (const name of Object.keys(profile.subagents ?? {}).sort()) {\n if (profile.subagents?.[name]?.model) routes.push({ kind: 'subagent', name, requested })\n }\n return routes\n}\n\nexport function candidateEntrypointReceipt(\n candidate: VerifiedAgentCandidate,\n): { path: string; sha256: `sha256:${string}`; byteLength: number } | undefined {\n const launch = candidate.bundle.execution.launch\n const workspace = candidate.bundle.execution.workspace\n if (launch.kind !== 'candidate-entrypoint' || !workspace) return undefined\n const file = workspace.material.files.find((entry) => entry.path === launch.entrypoint)\n if (!file) throw new Error('candidate entrypoint is absent from the verified workspace')\n return { path: file.path, sha256: file.sha256, byteLength: file.byteLength }\n}\n\nexport function absoluteExecutionCwd(\n cwd: VerifiedAgentCandidate['bundle']['execution']['cwd'],\n roots: AgentCandidateTaskExecution['executionRoots'],\n): string {\n const root = workspaceExecutionRoot(cwd.workspace, roots)\n const absolute = cwd.path === '.' ? root : posix.join(root, cwd.path)\n if (absolute !== root && !absolute.startsWith(`${root}/`)) {\n throw new Error('candidate cwd escapes its execution workspace')\n }\n return absolute\n}\n\nfunction workspaceExecutionRoot(\n workspace: 'task' | 'candidate',\n roots: AgentCandidateTaskExecution['executionRoots'],\n): string {\n const root = workspace === 'task' ? roots.taskRoot : roots.candidateRoot\n if (!root) throw new Error(`candidate ${workspace} workspace root is missing`)\n return root\n}\n\nexport function exactProfileExecutorFiles(\n sourceFiles: ReadonlyArray<{\n relPath: string\n content: string\n mode?: number\n root?: 'agent' | 'workspace'\n }>,\n expectedFiles: ReadonlyArray<{\n relPath: string\n mode: number\n contentSha256: string\n root?: 'agent'\n }>,\n): Array<{ path: string; mode: number; root?: 'agent'; bytes: Uint8Array }> {\n const byIdentity = new Map(\n sourceFiles.map((file) => [profileFileIdentity(file.root, file.relPath), file]),\n )\n if (byIdentity.size !== sourceFiles.length || sourceFiles.length !== expectedFiles.length) {\n throw new Error('profile source files do not match the signed profile plan')\n }\n return expectedFiles.map((expected) => {\n const source = byIdentity.get(profileFileIdentity(expected.root, expected.relPath))\n const mode = source?.mode ?? 0o644\n const bytes = Buffer.from(source?.content ?? '', 'utf8')\n if (\n !source ||\n !Number.isInteger(mode) ||\n mode < 0 ||\n mode > 0o777 ||\n mode !== expected.mode ||\n sha256Bytes(bytes) !== expected.contentSha256\n ) {\n throw new Error('profile source files do not match the signed profile plan')\n }\n return {\n path: expected.relPath,\n mode,\n ...(expected.root === 'agent' ? { root: 'agent' as const } : {}),\n bytes: Uint8Array.from(bytes),\n }\n })\n}\n"],"mappings":";;;;;;;AAIA,SAAgB,kCACd,OACA,MACQ;CACR,IAAI,MAAM,SAAS,UACjB,MAAM,IAAI,gBACR,aAAa,KAAK,4DACpB;CAEF,OAAO,MAAM;AACf;;;ACFA,MAAM,qBAAqB;AAC3B,MAAM,4BAA4B;AA8BlC,MAAM,sBAAsB,CAAC,mBAAmB,sBAAsB;AACtE,MAAM,6BAA6B,CACjC,0BACA,6BACF;AAEA,SAAS,wBAAwB,QAAoC;CACnE,OAAO,OAAO,MAAM,UAClB,oBAAoB,MAAM,SAAS,UAAU,QAAQ,MAAM,WAAW,GAAG,KAAK,EAAE,CAAC,CACnF;AACF;AAEA,SAAS,8BAA8B,QAAoC;CACzE,OAAO,OAAO,MAAM,UAClB,2BAA2B,MAAM,SAAS,UAAU,QAAQ,MAAM,WAAW,GAAG,KAAK,EAAE,CAAC,CAC1F;AACF;;AAGA,MAAM,yBAAyB,CAAC,2BAA2B,wBAAwB;AAEnF,SAAS,gCAAgC,QAAoC;CAC3E,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS;EAClD,MAAM,QAAQ,OAAO;EACrB,MAAM,SACJ,UAAU,QAAQ,UAAU,aACxB,OAAO,QAAQ,KACf,MAAM,WAAW,WAAW,IAC1B,MAAM,MAAM,CAAkB,IAC9B,KAAA;EACR,IACE,WAAW,KAAA,KACX,uBAAuB,MAAM,QAAQ,OAAO,UAAU,CAAC,CAAC,WAAW,GAAG,IAAI,EAAE,CAAC,GAE7E,OAAO;CAEX;CACA,OAAO;AACT;AAEA,MAAM,yBAAyB;CAC7B,eAAe;EACb,YAAY;EACZ,UAAU,MAAM,cAAc,SAC5B,YACE,cAAc,MAAM,oBA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