@tangle-network/agent-runtime 0.342.1 → 0.343.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/{activation-DOH7Fnyp.js → activation-BMjalBNv.js} +4 -4
  2. package/dist/{activation-DOH7Fnyp.js.map → activation-BMjalBNv.js.map} +1 -1
  3. package/dist/{activation-CXqtijue.d.ts → activation-NJiV0MHb.d.ts} +2 -2
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +3 -3
  6. package/dist/{bundle-Cwpit6Tg.js → bundle-DKQtOO9d.js} +2 -2
  7. package/dist/{bundle-Cwpit6Tg.js.map → bundle-DKQtOO9d.js.map} +1 -1
  8. package/dist/candidate-execution/index.js +4 -4
  9. package/dist/{coordination-manager-HQE0bIav.js → coordination-manager-DIC19cgD.js} +22 -314
  10. package/dist/coordination-manager-DIC19cgD.js.map +1 -0
  11. package/dist/{delegate-DmShSdjy.js → delegate-BWXq1BeR.js} +2 -2
  12. package/dist/{delegate-DmShSdjy.js.map → delegate-BWXq1BeR.js.map} +1 -1
  13. package/dist/{durable-file-gNI9ILAn.js → durable-file-CA0kr1Pi.js} +8 -3
  14. package/dist/durable-file-CA0kr1Pi.js.map +1 -0
  15. package/dist/durable.d.ts +2 -2
  16. package/dist/durable.js +153 -16
  17. package/dist/durable.js.map +1 -1
  18. package/dist/{graph-BCghJFlS.js → graph-B89lApkU.js} +4 -4
  19. package/dist/{graph-BCghJFlS.js.map → graph-B89lApkU.js.map} +1 -1
  20. package/dist/{improve-Dga6OYt-.js → improve-CII-AhGN.js} +7 -8
  21. package/dist/{improve-Dga6OYt-.js.map → improve-CII-AhGN.js.map} +1 -1
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.js +9 -9
  24. package/dist/intelligence.d.ts +2 -2
  25. package/dist/intelligence.js +6 -6
  26. package/dist/kernel.d.ts +1 -1
  27. package/dist/kernel.js +10 -11
  28. package/dist/{loop-runner-CW87Vqoj.js → loop-runner-Bbk9It72.js} +2 -2
  29. package/dist/{loop-runner-CW87Vqoj.js.map → loop-runner-Bbk9It72.js.map} +1 -1
  30. package/dist/{loop-runner-CuhbgVGo.d.ts → loop-runner-D56Rpd2z.d.ts} +2 -2
  31. package/dist/loop-runner-bin.d.ts +1 -1
  32. package/dist/loop-runner-bin.js +1 -1
  33. package/dist/mcp/bin.js +3 -3
  34. package/dist/mcp/index.d.ts +1 -1
  35. package/dist/mcp/index.js +6 -6
  36. package/dist/mcp/index.js.map +1 -1
  37. package/dist/platform.js +1 -1
  38. package/dist/platform.js.map +1 -1
  39. package/dist/{prepare-C-cWCyt3.js → prepare-TEEHSJwq.js} +3 -3
  40. package/dist/{prepare-C-cWCyt3.js.map → prepare-TEEHSJwq.js.map} +1 -1
  41. package/dist/{profile-CbMw5hAn.js → profile-6OLpbjvV.js} +2 -2
  42. package/dist/{profile-CbMw5hAn.js.map → profile-6OLpbjvV.js.map} +1 -1
  43. package/dist/profiles.d.ts +1 -1
  44. package/dist/profiles.js +1 -1
  45. package/dist/profiles.js.map +1 -1
  46. package/dist/{provision-supervisor-BWR_TJFg.js → provision-supervisor-it-VCGyZ.js} +6 -6
  47. package/dist/{provision-supervisor-BWR_TJFg.js.map → provision-supervisor-it-VCGyZ.js.map} +1 -1
  48. package/dist/{run-cancellation-C9oL62sW.js → run-cancellation-DSpwvFmQ.js} +8 -4
  49. package/dist/{run-cancellation-C9oL62sW.js.map → run-cancellation-DSpwvFmQ.js.map} +1 -1
  50. package/dist/{runtime-CuRTZFe6.js → runtime-fKVK1rVb.js} +15 -17
  51. package/dist/{runtime-CuRTZFe6.js.map → runtime-fKVK1rVb.js.map} +1 -1
  52. package/dist/{sandbox-profile-compat-FN2kab2-.js → sandbox-profile-compat-_fEtHPCj.js} +2 -2
  53. package/dist/sandbox-profile-compat-_fEtHPCj.js.map +1 -0
  54. package/dist/{search-executor-0-SjHAao.js → search-executor-Ymr-tAKJ.js} +3 -3
  55. package/dist/{search-executor-0-SjHAao.js.map → search-executor-Ymr-tAKJ.js.map} +1 -1
  56. package/dist/{server-DTUK2wW1.js → server-BngfDubR.js} +4 -4
  57. package/dist/{server-DTUK2wW1.js.map → server-BngfDubR.js.map} +1 -1
  58. package/dist/{structural-rollout-kfaZgAkd.js → structural-rollout-BmKAIWWR.js} +3 -3
  59. package/dist/{structural-rollout-kfaZgAkd.js.map → structural-rollout-BmKAIWWR.js.map} +1 -1
  60. package/dist/{supervise-C_GAgiJU.js → supervise-DyCUu8Io.js} +415 -107
  61. package/dist/supervise-DyCUu8Io.js.map +1 -0
  62. package/dist/{supervisor-C_03z693.js → supervisor-gDn4C1o5.js} +627 -27
  63. package/dist/supervisor-gDn4C1o5.js.map +1 -0
  64. package/dist/testing.d.ts +1 -1
  65. package/dist/testing.js +13 -13
  66. package/dist/{top-snapshot-CbZE1JsU.js → top-snapshot-OjHdhai1.js} +2 -2
  67. package/dist/{top-snapshot-CbZE1JsU.js.map → top-snapshot-OjHdhai1.js.map} +1 -1
  68. package/dist/tui/bin.js +5 -3
  69. package/dist/tui/bin.js.map +1 -1
  70. package/dist/tui/index.d.ts +1 -1
  71. package/dist/tui/index.js +2 -2
  72. package/dist/{types-Cgs89PQd.d.ts → types-D0ZRqIJh.d.ts} +131 -17
  73. package/package.json +6 -6
  74. package/dist/content-digest-sBTLujlK.js +0 -9
  75. package/dist/content-digest-sBTLujlK.js.map +0 -1
  76. package/dist/coordination-manager-HQE0bIav.js.map +0 -1
  77. package/dist/durable-file-gNI9ILAn.js.map +0 -1
  78. package/dist/graph-registry-BnO64cn8.js +0 -197
  79. package/dist/graph-registry-BnO64cn8.js.map +0 -1
  80. package/dist/jsonl-file-C9Kde_0Z.js +0 -206
  81. package/dist/jsonl-file-C9Kde_0Z.js.map +0 -1
  82. package/dist/record-value-B6bwJxLa.js +0 -12
  83. package/dist/record-value-B6bwJxLa.js.map +0 -1
  84. package/dist/sandbox-profile-compat-FN2kab2-.js.map +0 -1
  85. package/dist/supervise-C_GAgiJU.js.map +0 -1
  86. package/dist/supervisor-C_03z693.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { i as ConfigError } from "./errors-DodWX-cb.js";
2
- import { t as supervise } from "./supervise-C_GAgiJU.js";
2
+ import { t as supervise } from "./supervise-DyCUu8Io.js";
3
3
  import { agentProfileSchema } from "@tangle-network/agent-interface";
4
4
  import { computeFindingId, makeFinding } from "@tangle-network/agent-eval";
5
5
  //#region src/runtime/supervise/authoring.ts
@@ -207,4 +207,4 @@ async function delegate(intent, opts) {
207
207
  //#endregion
208
208
  export { defaultProfileRichnessThresholds as a, assessAuthoredProfile as i, delegate as n, profileRichnessFinding as o, asAuthoredProfile as r, supervisorInstructions as s, defaultDelegateBudget as t };
209
209
 
210
- //# sourceMappingURL=delegate-DmShSdjy.js.map
210
+ //# sourceMappingURL=delegate-BWXq1BeR.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"delegate-DmShSdjy.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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EACA,UAP2C,SAAS,OAClD,SAAS,WAAW,MAClB,SACA,WACF;EAIF,MAAM;EACN;EACA;EACA,YAAY;EACZ,eAAe,CACb;GACE,MAAM;GACN,KAAK,WAAW;GAChB,SAAS,SAAS,SAAS,kBAAkB,SAAS,SAAS,kBAAkB,SAAS,SAAS,SAAS,UAAU,SAAS,UAAU,OAAO,SAAS,OAAO,YAAY,SAAS,SAAS,QAAQ,CAAC;EACzM,CACF;EACA,GAAI,SAAS,OACT,EAAE,oBAAoB,cAAc,SAAS,KAAK,UAAU,SAAS,QAAQ,KAAK,IAAI,EAAE,GAAG,IAC3F,CAAC;EACL,UAAU,iBAAiB;GACzB;GACA,MAAM;GACN;GACA,OAAO,YAAY,SAAS,OAAO,SAAS;EAC9C,CAAC;CACH,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;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
+ {"version":3,"file":"delegate-BWXq1BeR.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;EACA;EACA;EACA;EACA;EACA,GAAI,MAAM,OAAO,CAAC,IAAI,aAAa,KAAK,MAAM,IAAI,CAAC;CACrD,CAAC,CAAC,KAAK,IAAI;AACb;;AAqBA,MAAa,mCAA8D;CACzE,sBAAsB;CACtB,sBAAsB;AACxB;;;AA0BA,SAAS,oBAAoB,SAA+B;CAC1D,MAAM,KAAM,QAAiC;CAC7C,IAAI,OAAO,OAAO,UAAU,OAAO;CACnC,IAAI,MAAM,OAAO,OAAO,UAAU;EAChC,MAAM,IAAI;EACV,IAAI,OAAO,EAAE,iBAAiB,UAAU,OAAO,EAAE;EACjD,IAAI,OAAO,EAAE,WAAW,UAAU,OAAO,EAAE;CAC7C;CACA,OAAO;AACT;;;AAIA,SAAgB,sBACd,SACA,MACiB;CACjB,MAAM,KAAK;EAAE,GAAG;EAAkC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,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,4 +1,4 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import { closeSync, constants, existsSync, fchmodSync, fsyncSync, linkSync, lstatSync, openSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
3
3
  import { dirname, join, relative, resolve } from "node:path";
4
4
  //#region \0rolldown/runtime.js
@@ -13,6 +13,11 @@ var __exportAll = (all, no_symbols) => {
13
13
  return target;
14
14
  };
15
15
  //#endregion
16
+ //#region src/content-digest.ts
17
+ function sha256(value) {
18
+ return createHash("sha256").update(value).digest("hex");
19
+ }
20
+ //#endregion
16
21
  //#region src/runtime/supervise/durable-file.ts
17
22
  /**
18
23
  * Small filesystem durability primitives for Runtime-owned state.
@@ -156,6 +161,6 @@ function isNoEntryError(error) {
156
161
  return error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT";
157
162
  }
158
163
  //#endregion
159
- export { syncDurableDirectory as a, publishExclusiveDurableFile as i, assertNoSymlinkDescendant as n, writeAtomicDurableFile as o, durable_file_exports as r, __exportAll as s, appendDurableFile as t };
164
+ export { syncDurableDirectory as a, __exportAll as c, publishExclusiveDurableFile as i, assertNoSymlinkDescendant as n, writeAtomicDurableFile as o, durable_file_exports as r, sha256 as s, appendDurableFile as t };
160
165
 
161
- //# sourceMappingURL=durable-file-gNI9ILAn.js.map
166
+ //# sourceMappingURL=durable-file-CA0kr1Pi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"durable-file-CA0kr1Pi.js","names":["fsConstants"],"sources":["../src/content-digest.ts","../src/runtime/supervise/durable-file.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\n\nexport function sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n","/**\n * Small filesystem durability primitives for Runtime-owned state.\n *\n * Callers must validate their path and parent directory before invoking these functions.\n * The exclusive writer protects a no-clobber publication race; the atomic writer replaces one\n * state file after its temporary contents reach stable storage.\n *\n * @internal\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n existsSync,\n fchmodSync,\n constants as fsConstants,\n fsyncSync,\n linkSync,\n lstatSync,\n openSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n writeSync,\n} from 'node:fs'\nimport { dirname, join, relative, resolve } from 'node:path'\n\ninterface DurableFileOptions {\n readonly mode?: number\n}\n\n/** Publish a new file without replacing a concurrent winner. */\nexport function publishExclusiveDurableFile(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): boolean {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n let published = false\n try {\n writeExclusiveDurableFile(temporaryPath, content, options)\n try {\n linkSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n published = true\n } catch (error) {\n if (!isAlreadyExistsError(error)) throw error\n }\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n return published\n}\n\n/** Fsync a directory after publishing a durable file entry. */\nexport function syncDurableDirectory(directoryPath: string): void {\n const fd = openSync(directoryPath, 'r')\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/** Fsync one durable file after its contents reach stable storage. */\nfunction syncDurableFile(filePath: string, exactMode?: number): void {\n const fd = openSync(filePath, 'r')\n try {\n if (exactMode !== undefined && process.platform !== 'win32') fchmodSync(fd, exactMode)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/** Append one record with O_APPEND, then fsync the file and containing directory. */\nexport function appendDurableFile(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n const flags =\n fsConstants.O_APPEND |\n fsConstants.O_CREAT |\n fsConstants.O_WRONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0)\n const fd = openSync(filePath, flags, options.mode ?? 0o600)\n try {\n if (process.platform !== 'win32') fchmodSync(fd, options.mode ?? 0o600)\n const expectedBytes = Buffer.byteLength(content, 'utf8')\n const writtenBytes = writeSync(fd, content, undefined, 'utf8')\n if (writtenBytes !== expectedBytes) {\n throw new Error(\n `durable append wrote ${writtenBytes} of ${expectedBytes} bytes to '${filePath}'`,\n )\n }\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n syncDurableDirectory(dirname(filePath))\n}\n\n/** Reject a path that escapes its run directory or traverses a symbolic link. */\nexport function assertNoSymlinkDescendant(root: string, target: string, label = 'path'): void {\n const base = resolve(root)\n const exact = resolve(target)\n const rel = relative(base, exact)\n if (rel === '..' || rel.startsWith(`..${process.platform === 'win32' ? '\\\\' : '/'}`)) {\n throw new Error(`${label} path escapes its run directory`)\n }\n if (existsSync(base) && lstatSync(base).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${base}`)\n }\n let current = base\n for (const part of rel.split(/[\\\\/]/u).filter(Boolean)) {\n current = join(current, part)\n if (!existsSync(current)) continue\n if (lstatSync(current).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${current}`)\n }\n }\n}\n\n/** Write, fsync, atomically replace, and fsync one Runtime-owned state file.\n * preserveMode retains ordinary access permissions despite the current umask; a new\n * file keeps normal creation semantics. Callers still own path validation and write exclusion. */\nexport function writeAtomicDurableFile(\n filePath: string,\n content: string,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n try {\n let mode = options.mode\n let exactMode = false\n if (options.preserveMode) {\n try {\n mode = statSync(filePath).mode & 0o777\n exactMode = true\n } catch (error) {\n if (!isNoEntryError(error)) throw error\n }\n }\n writeExclusiveDurableFile(temporaryPath, content, { mode }, exactMode)\n renameSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n // A successful rename removes the temporary directory entry.\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n}\n\nfunction writeExclusiveDurableFile(\n filePath: string,\n content: string,\n options: DurableFileOptions,\n exactMode = false,\n): void {\n if (options.mode === undefined) {\n writeFileSync(filePath, content, { encoding: 'utf8', flag: 'wx' })\n } else {\n writeFileSync(filePath, content, { encoding: 'utf8', flag: 'wx', mode: options.mode })\n }\n syncDurableFile(filePath, exactMode ? options.mode : undefined)\n}\n\nfunction isAlreadyExistsError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'EEXIST'\n )\n}\n\nfunction isNoEntryError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAEA,SAAgB,OAAO,OAAuB;CAC5C,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;;;;;;;;;;;;;;;;;;;;AC6BA,SAAgB,4BACd,UACA,SACA,UAA8B,CAAC,GACtB;CACT,MAAM,gBAAgB,GAAG,SAAS,GAAG,WAAW,EAAE;CAClD,IAAI,kBAAkB;CACtB,IAAI;CACJ,IAAI,YAAY;C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,aAAa;CAC1B,SAAS,OAAO;EACd,IAAI,CAAC,eAAe,KAAK,GAAG,eAAe;CAE7C;CACA,IAAI,iBAAiB,MAAM;CAC3B,IAAI,iBAAiB,KAAA,GAAW,MAAM;AACxC;AAEA,SAAS,0BACP,UACA,SACA,SACA,YAAY,OACN;CACN,IAAI,QAAQ,SAAS,KAAA,GACnB,cAAc,UAAU,SAAS;EAAE,UAAU;EAAQ,MAAM;CAAK,CAAC;MAEjE,cAAc,UAAU,SAAS;EAAE,UAAU;EAAQ,MAAM;EAAM,MAAM,QAAQ;CAAK,CAAC;CAEvF,gBAAgB,UAAU,YAAY,QAAQ,OAAO,KAAA,CAAS;AAChE;AAEA,SAAS,qBAAqB,OAAyB;CACrD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,eAAe,OAAyB;CAC/C,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C"}
package/dist/durable.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $l as PursuitVersions, Av as ContinuityMode, Cd as SeatSelection, Cu as ObserverJournal, Cy as AnalyzeOnSettleRoute, D as RetainedPendingCause, Ed as SelectSeat, Eu as observerRecordDigest, Gm as ToolLoopCompactionOptions, Jf as CoordinationTransportOptions, Jl as JudgedPursuitVersion, Kf as CoordinationPublicAddress, Lv as MapOnSettleRoute, Ov as AuthorizedDownMessage, Ql as PursuitVersionStop, Su as FileObserverJournal, Tu as ObserverRecordKind, V as NodeId, Vd as DeadlineCheckIn, Wf as CoordinationAuthentication, Xf as CoordinationHttpAudit, Xl as NextPursuitVersionInput, Yl as NextPursuitVersion, Zf as CoordinationRejectReason, Zl as PursuitVersionChain, _u as PursuitProjection, au as SupervisePursuitError, av as WorkerWatchOptions, bu as PursuitStatus, cf as DriveHarnessOwnerContext, cu as superviseGraphPursuit, du as PursuitCostProvenance, ed as PursuitFork, ef as RootStreamRecord, eu as SettledPursuitVersion, fu as PursuitNodeCost, gu as PursuitNodeUsage, hu as PursuitNodeTiming, hv as EscalateQuestion, it as SupervisedResult, iu as SuperviseGraphPursuitOptions, jv as DownMessageAuthorizationInput, lu as supervisePursuit, mu as PursuitNodeProjection, nf as readRootStreamReceipt, nu as VersionVerdict, od as AuthorizedSpawn, ou as SupervisePursuitOptions, pu as PursuitNodePlatform, qf as CoordinationReadAccess, rt as RootStreamReceipt, ru as assertPursuitVersions, sd as AuthorizedSpawnContext, su as SupervisedPursuitResult, td as RUN_FORK_CORRELATION_KEYS, tf as readRootStream, tu as VersionJudge, ud as WorkerSlots, uf as ResolveDriveHarness, uu as PursuitObserverDelivery, vf as ManagerWakePolicy, vu as PursuitRunProjection, vv as QuestionEscalationOutcome, wd as SeatSelectionInput, wu as ObserverRecord, xu as projectPursuit, yu as PursuitRunTotals } from "./types-Cgs89PQd.js";
1
+ import { $l as PursuitVersions, Cu as FileObserverJournal, D as RetainedPendingCause, Dd as SelectSeat, Du as observerRecordDigest, Eu as ObserverRecordKind, Gf as CoordinationAuthentication, Hd as DeadlineCheckIn, Jf as CoordinationReadAccess, Jl as JudgedPursuitVersion, Km as ToolLoopCompactionOptions, Mv as DownMessageAuthorizationInput, Qf as CoordinationRejectReason, Ql as PursuitVersionStop, Rv as MapOnSettleRoute, Su as projectPursuit, Td as SeatSelectionInput, Tu as ObserverRecord, V as NodeId, Xl as NextPursuitVersionInput, Yf as CoordinationTransportOptions, Yl as NextPursuitVersion, Zf as CoordinationHttpAudit, Zl as PursuitVersionChain, _u as PursuitNodeUsage, au as SupervisePursuitError, bu as PursuitRunTotals, cd as AuthorizedSpawnContext, cu as superviseGraphPursuit, dd as WorkerSlots, df as ResolveDriveHarness, du as PursuitObserverDelivery, eu as SettledPursuitVersion, fu as PursuitCostProvenance, gu as PursuitNodeTiming, gv as EscalateQuestion, hu as PursuitNodeProjection, it as SupervisedResult, iu as SuperviseGraphPursuitOptions, jv as ContinuityMode, kv as AuthorizedDownMessage, lf as DriveHarnessOwnerContext, lu as supervisePursuit, mu as PursuitNodePlatform, nd as RUN_FORK_CORRELATION_KEYS, nf as readRootStream, nu as VersionVerdict, ou as SupervisePursuitOptions, ov as WorkerWatchOptions, pu as PursuitNodeCost, qf as CoordinationPublicAddress, rf as readRootStreamReceipt, rt as RootStreamReceipt, ru as assertPursuitVersions, sd as AuthorizedSpawn, su as SupervisedPursuitResult, td as PursuitFork, tf as RootStreamRecord, tu as VersionJudge, uu as RunReopen, vu as PursuitProjection, wd as SeatSelection, wu as ObserverJournal, wy as AnalyzeOnSettleRoute, xu as PursuitStatus, yf as ManagerWakePolicy, yu as PursuitRunProjection, yv as QuestionEscalationOutcome } from "./types-D0ZRqIJh.js";
2
2
  import { n as RuntimeDecisionKind, r as RuntimeDecisionPoint, t as RuntimeDecisionEvidenceRef } from "./runtime-hooks-nsqxSUFL.js";
3
3
  //#region src/durable/chat-engine.d.ts
4
4
  /**
@@ -257,5 +257,5 @@ interface DurableSupervisionDiscovery {
257
257
  */
258
258
  declare function discoverDurableSupervisionRun(runDir: string): Promise<DurableSupervisionDiscovery>;
259
259
  //#endregion
260
- export { type AnalyzeOnSettleRoute, type AuthorizedDownMessage, type AuthorizedSpawn, type AuthorizedSpawnContext, type ChatStreamEvent, type ChatTurnHooks, type ChatTurnIdentity, type ChatTurnProducer, type ChatTurnResult, type ContinuityMode, type CoordinationAuthentication, type CoordinationHttpAudit, type CoordinationPublicAddress, type CoordinationReadAccess, type CoordinationRejectReason, type CoordinationTransportOptions, type DeadlineCheckIn, type DownMessageAuthorizationInput, type DriveHarnessOwnerContext, type DurableCoordinationStreamIdentity, type DurableFailureRecord, type DurableSupervisionDiscovery, type EscalateQuestion, FileObserverJournal, type JudgedPursuitVersion, type ManagerWakePolicy, type MapOnSettleRoute, type NextPursuitVersion, type NextPursuitVersionInput, type ObserverJournal, type ObserverRecord, type ObserverRecordKind, type PursuitCostProvenance, type PursuitFork, type PursuitNodeCost, type PursuitNodePlatform, type PursuitNodeProjection, type PursuitNodeTiming, type PursuitNodeUsage, type PursuitObserverDelivery, type PursuitProjection, type PursuitRunProjection, type PursuitRunTotals, type PursuitStatus, type PursuitVersionChain, type PursuitVersionStop, type PursuitVersions, type QuestionEscalationOutcome, RUN_FORK_CORRELATION_KEYS, type ResolveDriveHarness, type RetainedPendingCause, type RootStreamRecord, type RunChatTurnInput, type RunDirectoryHolderLiveness, type RunDirectoryLock, type RunDirectoryLockHolder, RunDirectoryLockedError, type RuntimeDecisionEvidenceRef, type RuntimeDecisionKind, type RuntimeDecisionPoint, type SeatSelection, type SeatSelectionInput, type SelectSeat, type SettledPursuitVersion, SettledRunDirectoryError, type SuperviseGraphPursuitOptions, SupervisePursuitError, type SupervisePursuitOptions, type SupervisedPursuitResult, type ToolLoopCompactionOptions, type VersionJudge, type VersionVerdict, type WorkerSlots, type WorkerWatchOptions, acquireRunDirectoryLock, assertPursuitVersions, deriveExecutionId, discoverDurableSupervisionRun, handleChatTurn, observerRecordDigest, projectPursuit, readFailureRecord, readRootStream, readRootStreamReceipt, readRunDirectoryLock, readSettleRecord, runDirectoryHolderIsLive, superviseGraphPursuit, supervisePursuit };
260
+ export { type AnalyzeOnSettleRoute, type AuthorizedDownMessage, type AuthorizedSpawn, type AuthorizedSpawnContext, type ChatStreamEvent, type ChatTurnHooks, type ChatTurnIdentity, type ChatTurnProducer, type ChatTurnResult, type ContinuityMode, type CoordinationAuthentication, type CoordinationHttpAudit, type CoordinationPublicAddress, type CoordinationReadAccess, type CoordinationRejectReason, type CoordinationTransportOptions, type DeadlineCheckIn, type DownMessageAuthorizationInput, type DriveHarnessOwnerContext, type DurableCoordinationStreamIdentity, type DurableFailureRecord, type DurableSupervisionDiscovery, type EscalateQuestion, FileObserverJournal, type JudgedPursuitVersion, type ManagerWakePolicy, type MapOnSettleRoute, type NextPursuitVersion, type NextPursuitVersionInput, type ObserverJournal, type ObserverRecord, type ObserverRecordKind, type PursuitCostProvenance, type PursuitFork, type PursuitNodeCost, type PursuitNodePlatform, type PursuitNodeProjection, type PursuitNodeTiming, type PursuitNodeUsage, type PursuitObserverDelivery, type PursuitProjection, type PursuitRunProjection, type PursuitRunTotals, type PursuitStatus, type PursuitVersionChain, type PursuitVersionStop, type PursuitVersions, type QuestionEscalationOutcome, RUN_FORK_CORRELATION_KEYS, type ResolveDriveHarness, type RetainedPendingCause, type RootStreamRecord, type RunChatTurnInput, type RunDirectoryHolderLiveness, type RunDirectoryLock, type RunDirectoryLockHolder, RunDirectoryLockedError, type RunReopen, type RuntimeDecisionEvidenceRef, type RuntimeDecisionKind, type RuntimeDecisionPoint, type SeatSelection, type SeatSelectionInput, type SelectSeat, type SettledPursuitVersion, SettledRunDirectoryError, type SuperviseGraphPursuitOptions, SupervisePursuitError, type SupervisePursuitOptions, type SupervisedPursuitResult, type ToolLoopCompactionOptions, type VersionJudge, type VersionVerdict, type WorkerSlots, type WorkerWatchOptions, acquireRunDirectoryLock, assertPursuitVersions, deriveExecutionId, discoverDurableSupervisionRun, handleChatTurn, observerRecordDigest, projectPursuit, readFailureRecord, readRootStream, readRootStreamReceipt, readRunDirectoryLock, readSettleRecord, runDirectoryHolderIsLive, superviseGraphPursuit, supervisePursuit };
261
261
  //# sourceMappingURL=durable.d.ts.map
package/dist/durable.js CHANGED
@@ -1,19 +1,19 @@
1
- import { i as publishExclusiveDurableFile, o as writeAtomicDurableFile } from "./durable-file-gNI9ILAn.js";
2
- import { Hr as authoredProfileDigest, S as FileSpawnJournal, Si as contentAddress, ar as isFiniteNumber, at as loadSpawnForest, ir as failedItems, xi as detachedSnapshot } from "./supervisor-C_03z693.js";
1
+ import { a as syncDurableDirectory, i as publishExclusiveDurableFile, o as writeAtomicDurableFile } from "./durable-file-CA0kr1Pi.js";
2
+ import { Bi as assertValidBudget, C as FileSpawnJournal, Mi as contentAddress, Qr as authoredProfileDigest, _t as readCommittedJsonLines, ct as loadSpawnForest, hr as isFiniteNumber, ji as detachedSnapshot, mr as failedItems, mt as isNoEntError, pt as appendCommittedJsonLine, r as assertResumeLimits } from "./supervisor-gDn4C1o5.js";
3
3
  import { f as RuntimeRunStateError, m as ValidationError } from "./errors-DodWX-cb.js";
4
- import { t as isRecord } from "./record-value-B6bwJxLa.js";
5
- import { W as addSpend, X as errorMessage, ft as zeroSpend, q as cloneSpend } from "./sandbox-profile-compat-FN2kab2-.js";
4
+ import { W as addSpend, X as errorMessage, ft as zeroSpend, q as cloneSpend } from "./sandbox-profile-compat-_fEtHPCj.js";
6
5
  import { a as withPursuitContext, t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
7
- import { a as readCommittedJsonLines, n as isNoEntError, t as appendCommittedJsonLine } from "./jsonl-file-C9Kde_0Z.js";
8
- import { J as readRootStreamReceipt, a as superviseRootProfile, q as readRootStream, t as supervise } from "./supervise-C_GAgiJU.js";
9
- import { a as applyExactAgentProfileDiff } from "./profile-CbMw5hAn.js";
10
- import { g as supervisorRunDir } from "./run-cancellation-C9oL62sW.js";
11
- import { i as superviseAgentGraph } from "./graph-BCghJFlS.js";
6
+ import { a as applyExactAgentProfileDiff } from "./profile-6OLpbjvV.js";
7
+ import { a as superviseRootProfile, ot as readRootStream, st as readRootStreamReceipt, t as supervise } from "./supervise-DyCUu8Io.js";
8
+ import { a as runCancelRequestFile, o as runCancellationFile, v as supervisorRunDir, x as workerCancellationsDir } from "./run-cancellation-DSpwvFmQ.js";
9
+ import { i as superviseAgentGraph } from "./graph-B89lApkU.js";
12
10
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalCandidateJson, sha256Bytes } from "@tangle-network/agent-interface";
11
+ import { isRecord } from "@tangle-network/agent-core";
13
12
  import { createHash } from "node:crypto";
13
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from "node:fs";
14
14
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
15
15
  import { execFile } from "node:child_process";
16
- import { access, mkdir, readFile, realpath, rmdir, unlink } from "node:fs/promises";
16
+ import { access, mkdir, readFile, realpath, rm, rmdir, unlink } from "node:fs/promises";
17
17
  import { promisify } from "node:util";
18
18
  import { SearchRecorder, developmentClaim, incumbent, openSearchLedger, parseSearchLedgerLine, runSearch, uniform } from "@tangle-network/agent-eval/campaign";
19
19
  import { pathToFileURL } from "node:url";
@@ -897,7 +897,7 @@ var SettledRunDirectoryError = class extends Error {
897
897
  /** The root of the recorded run, which is its `runId`. */
898
898
  recordedRunId;
899
899
  constructor(path, recordedRunId, requestedRunId) {
900
- super(recordedRunId === requestedRunId ? `supervisePursuit: ${path} records that run '${recordedRunId}' already settled; a settled run is not re-entered` : `supervisePursuit: ${path} records that run '${recordedRunId}' already settled in this directory; a directory holds one settle record, so run '${requestedRunId}' needs its own runDir`);
900
+ super(recordedRunId === requestedRunId ? `supervisePursuit: ${path} records that run '${recordedRunId}' already settled; a settled run is not re-entered unless the call passes reopen: { operator, reason, operationId }` : `supervisePursuit: ${path} records that run '${recordedRunId}' already settled in this directory; a directory holds one settle record, so run '${requestedRunId}' needs its own runDir`);
901
901
  this.name = "SettledRunDirectoryError";
902
902
  this.path = path;
903
903
  this.recordedRunId = recordedRunId;
@@ -949,6 +949,10 @@ function jsonValue(result) {
949
949
  function settleRecordJson(result) {
950
950
  return canonicalCandidateJson(jsonValue(result));
951
951
  }
952
+ /** The digest the settle record's bytes hash to: the candidate digest of the result's JSON value. */
953
+ function settleRecordDigest(result) {
954
+ return canonicalCandidateDigest(jsonValue(result));
955
+ }
952
956
  /** Publish `result.json` in the run directory once. Throws when a record is already there. */
953
957
  async function writeSettleRecord(runDir, result) {
954
958
  const path = resolve(runDir, SETTLE_RECORD_FILE);
@@ -2322,6 +2326,119 @@ function startPursuitObserverDelivery(delivery, read, warn = (message) => consol
2322
2326
  };
2323
2327
  }
2324
2328
  //#endregion
2329
+ //#region src/durable/run-reopen.ts
2330
+ /** The directory that holds a run's archived settle records. */
2331
+ const SETTLE_ARCHIVE_DIR = "settles";
2332
+ /** Refuse a reopen that names no operator or reason, or that is combined with a fork or versions. */
2333
+ function assertRunReopen(reopen, opts) {
2334
+ if (reopen.operator.trim().length === 0) throw new TypeError("supervisePursuit: reopen.operator must be non-empty");
2335
+ if (reopen.reason.trim().length === 0) throw new TypeError("supervisePursuit: reopen.reason must be non-empty");
2336
+ if (reopen.operationId.trim().length === 0) throw new TypeError("supervisePursuit: reopen.operationId must be non-empty");
2337
+ if (reopen.budget !== void 0) assertValidBudget(reopen.budget, "reopen.budget");
2338
+ if (opts.fork !== void 0 || opts.versions !== void 0) throw new TypeError("supervisePursuit: reopen continues this run under its own id; fork and versions start new runs");
2339
+ }
2340
+ /**
2341
+ * Archive the settled segment of the run at `runDir` and clear it for a resume. Runs under the
2342
+ * directory lock. Throws when there is nothing to reopen, or when `operationId` already reopened a
2343
+ * segment that has since settled again.
2344
+ */
2345
+ async function reopenSettledRun(input) {
2346
+ const { runDir, runId, reopen, observer, pursuitId, now } = input;
2347
+ const operationId = reopen.operationId.trim();
2348
+ const settlePath = resolve(runDir, SETTLE_RECORD_FILE);
2349
+ const journal = input.journal ?? new FileSpawnJournal(resolve(runDir, "spawn-journal.jsonl"));
2350
+ const events = await journal.loadTree(runId) ?? [];
2351
+ const reopened = events.filter((event) => event.kind === "reopened" && event.id === runId);
2352
+ const mine = reopened.find((event) => event.operationId === operationId);
2353
+ const settled = await readBytes(settlePath);
2354
+ if (settled === void 0) {
2355
+ if (mine !== void 0) return;
2356
+ throw new Error(`supervisePursuit: ${runDir} holds no ${SETTLE_RECORD_FILE}; nothing to reopen; resume it`);
2357
+ }
2358
+ assertResumeLimits(events, {
2359
+ runId,
2360
+ budget: reopen.budget ?? input.limits.budget,
2361
+ ...input.limits.reservationPolicy === void 0 ? {} : { reservationPolicy: input.limits.reservationPolicy }
2362
+ }, mine === void 0 ? reopen.budget : void 0);
2363
+ const result = JSON.parse(settled);
2364
+ const digest = settleRecordDigest(result);
2365
+ if (mine !== void 0 && mine.prior.digest !== digest) throw new Error(`supervisePursuit: reopen '${operationId}' already reopened run '${runId}', which has settled again; reopen it under a new operationId`);
2366
+ const archivedAs = mine?.prior.archivedAs ?? await archiveName(runDir, settled);
2367
+ const archivePath = resolve(runDir, archivedAs);
2368
+ if (!publishExclusiveDurableFile(archivePath, settled) && await readBytes(archivePath) !== settled) throw new Error(`supervisePursuit: ${archivePath} already holds a different settle record; reopen refused`);
2369
+ const at = new Date(now()).toISOString();
2370
+ if (mine === void 0) await journal.appendEvent(runId, {
2371
+ kind: "reopened",
2372
+ id: runId,
2373
+ operator: reopen.operator,
2374
+ reason: reopen.reason,
2375
+ operationId,
2376
+ prior: {
2377
+ kind: String(result.kind),
2378
+ ...typeof result.reason === "string" ? { reason: result.reason } : {},
2379
+ digest,
2380
+ archivedAs
2381
+ },
2382
+ ...reopen.budget === void 0 ? {} : { budget: reopen.budget },
2383
+ seq: reopened.length,
2384
+ at
2385
+ });
2386
+ const eventId = `${runId}:pursuit:reopened:${operationId}`;
2387
+ if (!(await observer.read()).some((record) => record.event?.id === eventId)) await observer.appendEvent({
2388
+ id: eventId,
2389
+ pursuitId,
2390
+ runId,
2391
+ target: "agent.run",
2392
+ phase: "event",
2393
+ timestamp: now(),
2394
+ payload: { reopened: {
2395
+ operator: reopen.operator,
2396
+ reason: reopen.reason,
2397
+ archivedAs
2398
+ } }
2399
+ });
2400
+ setCancellationAside(runDir, operationId);
2401
+ await rm(settlePath);
2402
+ syncDurableDirectory(runDir);
2403
+ }
2404
+ /** The next free `settles/<n>.json`, or the archive that already holds these bytes (a reopen that
2405
+ * crashed after archiving and before its journal row). */
2406
+ async function archiveName(runDir, settled) {
2407
+ const dir = resolve(runDir, SETTLE_ARCHIVE_DIR);
2408
+ mkdirSync(dir, { recursive: true });
2409
+ const numbers = readdirSync(dir).map((name) => /^(\d+)\.json$/u.exec(name)?.[1]).filter((n) => n !== void 0).map(Number).sort((a, b) => a - b);
2410
+ for (const n of numbers) if (await readBytes(join(dir, `${n}.json`)) === settled) return `${SETTLE_ARCHIVE_DIR}/${n}.json`;
2411
+ return `${SETTLE_ARCHIVE_DIR}/${(numbers.at(-1) ?? 0) + 1}.json`;
2412
+ }
2413
+ /** Move the settled run's cancel request and acknowledgement aside under the reopen's and the
2414
+ * request's operation ids, so the reopened run accepts a new `cancelRun`. Idempotent: an absent
2415
+ * file is skipped. A reopen's operation id names one segment, so a later segment cancelled under
2416
+ * the same cancel operation id lands beside this one instead of over it. */
2417
+ function setCancellationAside(runDir, reopenOperationId) {
2418
+ const requestFile = runCancelRequestFile(runDir);
2419
+ const ackFile = runCancellationFile(runDir);
2420
+ if (!existsSync(requestFile) && !existsSync(ackFile)) return;
2421
+ const source = existsSync(requestFile) ? requestFile : ackFile;
2422
+ const { operationId } = JSON.parse(readFileSync(source, "utf8"));
2423
+ const reopenedDir = join(workerCancellationsDir(runDir), "reopened");
2424
+ const aside = join(reopenedDir, encodeURIComponent(reopenOperationId), encodeURIComponent(operationId));
2425
+ mkdirSync(aside, { recursive: true });
2426
+ if (existsSync(ackFile)) renameSync(ackFile, join(aside, "run.json"));
2427
+ if (existsSync(requestFile)) renameSync(requestFile, join(aside, "run.request.json"));
2428
+ syncDurableDirectory(aside);
2429
+ syncDurableDirectory(join(reopenedDir, encodeURIComponent(reopenOperationId)));
2430
+ syncDurableDirectory(reopenedDir);
2431
+ syncDurableDirectory(workerCancellationsDir(runDir));
2432
+ }
2433
+ async function readBytes(path) {
2434
+ try {
2435
+ return await readFile(path, "utf8");
2436
+ } catch (error) {
2437
+ if (error.code === "ENOENT") return void 0;
2438
+ throw error;
2439
+ }
2440
+ }
2441
+ //#endregion
2325
2442
  //#region src/durable/supervise-pursuit.ts
2326
2443
  /** A failed Runtime execution whose complete third-person projection was retained. */
2327
2444
  var SupervisePursuitError = class extends Error {
@@ -2359,16 +2476,33 @@ var SupervisePursuitError = class extends Error {
2359
2476
  */
2360
2477
  async function supervisePursuit(profile, task, opts) {
2361
2478
  assertPursuitDirectory(opts, "supervisePursuit");
2479
+ if (opts.reopen !== void 0) assertRunReopen(opts.reopen, opts);
2362
2480
  if (opts.versions !== void 0) return runPursuitVersions(profile, task, opts, supervisePursuit);
2363
- const { pursuitId: _pursuitId, hooks: _hooks, fork, versions: _versions, observerDelivery: _observerDelivery, ...superviseOptions } = opts;
2481
+ const { pursuitId: _pursuitId, hooks: _hooks, fork, versions: _versions, observerDelivery: _observerDelivery, reopen, ...superviseOptions } = opts;
2364
2482
  const forked = fork === void 0 ? void 0 : await prepareRunFork(profile, task, superviseOptions, fork);
2365
2483
  return runDurablePursuit(opts, ({ hooks, steerDir }) => supervise(forked?.profile ?? profile, task, {
2366
2484
  ...superviseOptions,
2367
2485
  ...forked === void 0 ? {} : { execution: forked.execution },
2486
+ ...reopen === void 0 ? {} : {
2487
+ resume: true,
2488
+ ...reopen.budget === void 0 ? {} : { budget: reopen.budget }
2489
+ },
2368
2490
  steerDir,
2369
2491
  retainedAtSettlement: "release",
2370
2492
  hooks
2371
- }), (result) => result);
2493
+ }), (result) => result, reopen === void 0 ? void 0 : (observer) => reopenSettledRun({
2494
+ runDir: opts.runDir.trim(),
2495
+ runId: opts.runId ?? "supervise",
2496
+ reopen,
2497
+ journal: opts.journal,
2498
+ limits: {
2499
+ budget: opts.budget,
2500
+ ...opts.reservationPolicy === void 0 ? {} : { reservationPolicy: opts.reservationPolicy }
2501
+ },
2502
+ observer,
2503
+ pursuitId: opts.pursuitId.trim(),
2504
+ now: opts.now ?? Date.now
2505
+ }));
2372
2506
  }
2373
2507
  /**
2374
2508
  * One-call durable execution of an `AgentGraph`: the graph twin of {@link supervisePursuit}.
@@ -2404,7 +2538,7 @@ function assertPursuitDirectory(opts, entry) {
2404
2538
  * journal, failure record and settle record. `execute` receives the observer-composed hooks and
2405
2539
  * the steer directory the run's control plane uses; `settled` names the value `result.json` holds.
2406
2540
  */
2407
- async function runDurablePursuit(opts, execute, settled) {
2541
+ async function runDurablePursuit(opts, execute, settled, reopen) {
2408
2542
  const pursuitId = opts.pursuitId.trim();
2409
2543
  const runDir = opts.runDir.trim();
2410
2544
  const observerPath = resolve(runDir, "observer.jsonl");
@@ -2416,9 +2550,12 @@ async function runDurablePursuit(opts, execute, settled) {
2416
2550
  let delivery;
2417
2551
  let terminalState = "failed";
2418
2552
  try {
2419
- const prior = await readSettleRecord(runDir);
2420
- if (prior !== void 0) throw new SettledRunDirectoryError(settlePath, prior.tree.root, runId);
2421
2553
  const observer = createFileObserverHooks(observerPath, pursuitId);
2554
+ if (reopen !== void 0) await reopen(observer.journal);
2555
+ else {
2556
+ const prior = await readSettleRecord(runDir);
2557
+ if (prior !== void 0) throw new SettledRunDirectoryError(settlePath, prior.tree.root, runId);
2558
+ }
2422
2559
  await observer.journal.appendEvent(rootEvent(pursuitId, runId, "before", now()));
2423
2560
  delivery = opts.observerDelivery === void 0 ? void 0 : startPursuitObserverDelivery(opts.observerDelivery, async () => projectPursuit(await observer.journal.read()));
2424
2561
  let result;