@tangle-network/agent-runtime 6.0.8 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +23 -9
- package/dist/{activation-Cwy3_Qn_.js → activation-Ba9IAgQ3.js} +2 -2
- package/dist/{activation-Cwy3_Qn_.js.map → activation-Ba9IAgQ3.js.map} +1 -1
- package/dist/{activation-CWx7I1PU.d.ts → activation-DIkTEBWF.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{coordination-manager-D9z7To7p.js → coordination-manager-DQZ2u6L-.js} +58 -6
- package/dist/coordination-manager-DQZ2u6L-.js.map +1 -0
- package/dist/{delegate-ws-KBA2H.js → delegate-DFLSVjFG.js} +2 -2
- package/dist/{delegate-ws-KBA2H.js.map → delegate-DFLSVjFG.js.map} +1 -1
- package/dist/durable.d.ts +71 -4
- package/dist/durable.js +158 -10
- package/dist/durable.js.map +1 -1
- package/dist/{failure-cause-BzjUUsRz.js → failure-cause-rJTm_Tx8.js} +6 -9
- package/dist/failure-cause-rJTm_Tx8.js.map +1 -0
- package/dist/{graph-2_nX4ib4.js → graph-BjQF2syl.js} +6 -6
- package/dist/{graph-2_nX4ib4.js.map → graph-BjQF2syl.js.map} +1 -1
- package/dist/{improve-BxfqTsZy.js → improve-BolbYegO.js} +6 -6
- package/dist/{improve-BxfqTsZy.js.map → improve-BolbYegO.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +10 -10
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +4 -4
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +13 -13
- package/dist/{loop-runner-BmGZ4y1W.js → loop-runner-C9W3T_3T.js} +2 -2
- package/dist/{loop-runner-BmGZ4y1W.js.map → loop-runner-C9W3T_3T.js.map} +1 -1
- package/dist/{loop-runner-CUMypgRw.d.ts → loop-runner-Cs9IJ6Nk.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +6 -6
- package/dist/mcp/memory-bin.js +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-CeQTPHRr.js → provision-supervisor-BQFHjCtN.js} +5 -5
- package/dist/{provision-supervisor-CeQTPHRr.js.map → provision-supervisor-BQFHjCtN.js.map} +1 -1
- package/dist/{run-cancellation-D_4vJ522.js → run-cancellation-B84X8ZAP.js} +2 -2
- package/dist/{run-cancellation-D_4vJ522.js.map → run-cancellation-B84X8ZAP.js.map} +1 -1
- package/dist/{run-state-CTZVngI_.js → run-state-Dh1bGERI.js} +6 -6
- package/dist/{run-state-CTZVngI_.js.map → run-state-Dh1bGERI.js.map} +1 -1
- package/dist/{runtime-COm9uBBx.js → runtime-C9F1PG2A.js} +13 -13
- package/dist/{runtime-COm9uBBx.js.map → runtime-C9F1PG2A.js.map} +1 -1
- package/dist/{search-executor-DTEIl58w.js → search-executor-CKR9_6NR.js} +4 -4
- package/dist/{search-executor-DTEIl58w.js.map → search-executor-CKR9_6NR.js.map} +1 -1
- package/dist/{server-zO9Nz9Nk.js → server-Dh3SQGQT.js} +4 -4
- package/dist/{server-zO9Nz9Nk.js.map → server-Dh3SQGQT.js.map} +1 -1
- package/dist/{settle-record-U7fkQEZa.js → settle-record-C6LdVvok.js} +12 -4
- package/dist/settle-record-C6LdVvok.js.map +1 -0
- package/dist/{structural-rollout-BwTwTUXF.js → structural-rollout-Dapf2aZY.js} +25 -7
- package/dist/structural-rollout-Dapf2aZY.js.map +1 -0
- package/dist/{supervise-tmqDU6YT.js → supervise-xwl2D6q3.js} +9 -7
- package/dist/{supervise-tmqDU6YT.js.map → supervise-xwl2D6q3.js.map} +1 -1
- package/dist/{supervision-discovery-CGbXayGv.js → supervision-discovery-B47U8TH5.js} +3 -3
- package/dist/{supervision-discovery-CGbXayGv.js.map → supervision-discovery-B47U8TH5.js.map} +1 -1
- package/dist/{scope-gIYQ5ZiL.js → supervisor-accounting-DxLQ_TQe.js} +330 -44
- package/dist/supervisor-accounting-DxLQ_TQe.js.map +1 -0
- package/dist/{supervisor-1A27fE6k.js → supervisor-gC-u_PRk.js} +11 -314
- package/dist/supervisor-gC-u_PRk.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +11 -11
- package/dist/{tool-server-B9q2dtnW.js → tool-server-Dg350Bgz.js} +2 -2
- package/dist/{tool-server-B9q2dtnW.js.map → tool-server-Dg350Bgz.js.map} +1 -1
- package/dist/{top-web-CS4PD4ck.js → top-web-BJLnFQdr.js} +6 -6
- package/dist/{top-web-CS4PD4ck.js.map → top-web-BJLnFQdr.js.map} +1 -1
- package/dist/tui/bin.js +6 -6
- package/dist/tui/bin.js.map +1 -1
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +2 -2
- package/dist/{types-w3Oo1uRJ.d.ts → types-Jg274chm.d.ts} +153 -309
- package/package.json +1 -1
- package/dist/coordination-manager-D9z7To7p.js.map +0 -1
- package/dist/failure-cause-BzjUUsRz.js.map +0 -1
- package/dist/scope-gIYQ5ZiL.js.map +0 -1
- package/dist/settle-record-U7fkQEZa.js.map +0 -1
- package/dist/structural-rollout-BwTwTUXF.js.map +0 -1
- package/dist/supervisor-1A27fE6k.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as ConfigError } from "./errors-AzSuGI23.js";
|
|
2
|
-
import { t as supervise } from "./supervise-
|
|
2
|
+
import { t as supervise } from "./supervise-xwl2D6q3.js";
|
|
3
3
|
import { agentProfileSchema } from "@tangle-network/agent-interface";
|
|
4
4
|
import { computeFindingId, makeFinding } from "@tangle-network/agent-eval";
|
|
5
5
|
// src/runtime/supervise/authoring.ts
|
|
@@ -205,4 +205,4 @@ async function delegate(intent, opts) {
|
|
|
205
205
|
}
|
|
206
206
|
export { defaultProfileRichnessThresholds as a, assessAuthoredProfile as i, delegate as n, profileRichnessFinding as o, asAuthoredProfile as r, supervisorInstructions as s, defaultDelegateBudget as t };
|
|
207
207
|
|
|
208
|
-
//# sourceMappingURL=delegate-
|
|
208
|
+
//# sourceMappingURL=delegate-DFLSVjFG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"delegate-ws-KBA2H.js","names":[],"sources":["../src/runtime/supervise/authoring.ts","../src/runtime/supervise/delegate.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions, tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific guidance are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt\n}\n\n/** Narrow an untyped `spawn_worker` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n if (!resolveSystemPrompt(parsed.data).trim()) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt },\n }\n}\n\n/** The supervisor skill: an explicit profile-authoring instruction, never an implicit Runtime\n * policy. Editing this text changes how a profile designs the descendants it spawns. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_worker with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.appendSystemPrompt: rich additive instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • tools.agent_runtime_coordination_spawn_worker: true ONLY when this child should author and drive descendants. Add only the other agent_runtime_coordination_<verb> tools it will call, such as observe_agent or steer_agent.',\n ' • A child with spawn_worker MUST carry this complete profile-authoring instruction as an immutable resources.skills entry with resources.failOnError: true, so it can author its own descendants from the same contract.',\n ' • metadata may describe the work, but it never grants recursion or selects a Runtime execution path.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n '3. End your turn while your workers run: Runtime wakes you with each settled worker. A settlement says valid:true only if the deployable check passed.',\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.appendSystemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n \"5. read_journal to re-read YOUR OWN record before you decide the next move: every spawn you made, every settle, every question and answer, every steer, every analyst finding — oldest first, this node only, including what you did before a restart. Use it to see what you already tried instead of trying it again. It is paged: pass the returned nextRow as the next call's sinceRow, narrow with kinds, and raise limit/maxBytes only as far as you will actually read. A truncated:true page means a bound cut it short — keep paging before you conclude you have read everything.\",\n '6. AUTHOR YOUR OWN LENS when the questions you can already ask of a settled trace do not cover the failure you are chasing: define_analyst takes an id, a description, an area, the question in your own words, the instructions for answering it with trace evidence, and the smallest toolGroup that can answer it (model is the seat it runs on; omit it for the run default). It is DATA, never code. Then run_analyst it on any settled worker like a lens the run shipped with, and read the finding. list_analysts shows what you have. Define a lens when you need a different question asked — not a second copy of a question already on the menu.',\n '7. EVERY refusal you get back carries a `reason` naming the exact unmet condition. Read it and change that condition — a spawn refused for budget-exhausted needs a smaller budget or the refund of a settled worker, an invalid-profile needs the named field fixed, a submit_result refused because the check THREW is a broken check to report, not a result to resubmit. Never repeat a call that was refused without changing what it was refused for.',\n '8. ask_parent ONLY when you genuinely cannot decide, and then READ ITS OUTCOME. \"queued-for-parent\" means an inbox above you now holds the question. \"no-parent\" means no inbox above you is configured to receive it: the question is still on the run record for anyone watching, but nothing will route an answer back to you, so do not block. Decide it with answer_question, or answer_question with deferReason to record that it stays open, and carry on — a blocking question left undecided also refuses your stop.',\n '9. Once the work is delivered, end your turn with nothing left running.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// receives in its next wake — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** Resolved authored guidance from replacement, addition and instruction sections. */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read authored guidance without requiring replacement of native coding instructions. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n return [\n Reflect.get(o, 'systemPrompt'),\n Reflect.get(o, 'appendSystemPrompt'),\n ...(Array.isArray(Reflect.get(o, 'instructions')) ? Reflect.get(o, 'instructions') : []),\n Reflect.get(o, 'system'),\n ]\n .filter((value) => typeof value === 'string')\n .join('\\n\\n')\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n","/**\n *\n * `delegate` — the one generic delegation verb. You hand it an INTENT (what you want done) and it\n * hands that intent to a default AUTHORING supervisor: a router-brained supervisor whose standing\n * instruction is `supervisorInstructions()` (the authoring-agent-profiles skill). The supervisor\n * DECOMPOSES the intent and AUTHORS the worker profile it needs per sub-task — there is NO hardcoded\n * coder/researcher profile here. That is the whole point: `delegate('fix the failing test', …)` and\n * `delegate('research X and cite sources', …)` route through the SAME front door; the supervisor\n * writes a code-shaped or research-shaped worker on its own.\n *\n * It is a thin wrapper over `supervise()` — the one front door — so the conserved-budget pool, the\n * completion oracle (`deliverable`), the coordination toolbox, and equal-compute accounting all come\n * for free; nothing is hand-rolled. The result is `supervise()`'s `SupervisedResult` returned\n * UNCHANGED, so its `spentTotal` (`{ iterations, tokens, usd, ms }`) rides straight back to the\n * caller on BOTH paths — a `winner` carries the delivered worker's spend, a `no-winner` carries the\n * spend incurred before it failed. That cost channel means a `delegate()` caller always learns what\n * the delegation actually spent.\n *\n * @experimental\n */\n\nimport { ConfigError } from '../../errors'\nimport type { RouterTransportConfig } from '../router-http-transport'\nimport type { DeliverableSpec } from './completion-gate'\nimport type { ExecutorConfig } from './runtime'\nimport { supervise } from './supervise'\nimport type { SupervisorProfile } from './supervisor-agent'\nimport type { Budget, SupervisedResult } from './types'\n\n/** The conserved pool a `delegate()` call applies when the caller does not pass its own `budget`.\n * A modest token ceiling + a small iteration ceiling — generous enough for a few-worker decompose,\n * bounded enough that an unsupervised intent cannot run away. Callers override via `opts.budget`. */\nexport const defaultDelegateBudget: Budget = { maxIterations: 50, maxTokens: 200_000 }\n\n/** Inputs to {@link delegate}. The intent is the first positional arg; everything here is optional\n * with explicit execution identity, so the common call names one exact supervisor profile. */\nexport interface DelegateOptions<Out = unknown> {\n /** The completion oracle (settled ⟺ delivered) the authored workers settle against. Strongly\n * recommended — without it the supervisor trusts a worker's self-report. For a code intent,\n * `patchDelivered()` is the canonical example; for a free-form answer, a content check. */\n readonly deliverable?: DeliverableSpec<Out>\n /** WHERE the authored workers run — the worker-execution backend (`router-tools` / `sandbox` /\n * `cli-worktree` / …). The supervisor authors the worker PROFILE; this is the substrate it runs\n * on. Provide this OR `makeWorkerAgent`-style wiring through `supervise()` is unavailable. */\n readonly backend?: ExecutorConfig\n /** The conserved compute pool for the whole delegation. Defaults to {@link defaultDelegateBudget}. */\n readonly budget?: Budget\n /** Exact executable authoring supervisor. Model, prompt, harness, and provider live here. */\n readonly supervisorProfile: SupervisorProfile\n /** Router endpoint/auth for a `cli-base` supervisor; contains no behavioral settings. */\n readonly router: RouterTransportConfig\n /** Restrict the run to this subset of models (forwarded to `supervise()`). */\n readonly allowedModels?: readonly string[]\n readonly runId?: string\n}\n\n/**\n * Delegate an INTENT to a default authoring supervisor and return its `SupervisedResult` unchanged.\n *\n * The supervisor authors + spawns whatever worker the intent needs over the conserved-budget pool;\n * `result.spentTotal` reports what the whole delegation actually cost. A `winner` result carries the\n * authored worker's delivered output; a `no-winner` result names why (never a fabricated success).\n */\nexport async function delegate<Out = unknown>(\n intent: string,\n opts: DelegateOptions<Out>,\n): Promise<SupervisedResult<Out>> {\n if (typeof intent !== 'string' || intent.trim().length === 0) {\n throw new ConfigError('delegate: `intent` must be a non-empty string')\n }\n return supervise(opts.supervisorProfile, intent, {\n budget: opts.budget ?? defaultDelegateBudget,\n ...(opts.backend ? { backend: opts.backend } : {}),\n ...(opts.deliverable ? { deliverable: opts.deliverable as DeliverableSpec<unknown> } : {}),\n router: opts.router,\n ...(opts.allowedModels ? { allowedModels: opts.allowedModels } : {}),\n ...(opts.runId ? { runId: opts.runId } : {}),\n }) as Promise<SupervisedResult<Out>>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,kBAAkB,KAAsC;CACtE,MAAM,SAAS,mBAAmB,UAAU,GAAG;CAC/C,IAAI,CAAC,OAAO,SAAS,OAAO;CAC5B,IAAI,CAAC,oBAAoB,OAAO,IAAI,CAAC,CAAC,KAAK,GAAG,OAAO;CACrD,OAAO;EACL,GAAG,OAAO;EACV,MACE,OAAO,OAAO,KAAK,SAAS,YAAY,OAAO,KAAK,KAAK,SAAS,IAC9D,OAAO,KAAK,OACZ;EACN,QAAQ,EAAE,GAAG,OAAO,KAAK,OAAO;CAClC;AACF;;;AAIA,SAAgB,uBAAuB,MAAkC;CACvE,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAI,MAAM,OAAO,CAAC,IAAI,aAAa,KAAK,MAAM,IAAI,CAAC;CACrD,CAAC,CAAC,KAAK,IAAI;AACb;;AAqBA,MAAa,mCAA8D;CACzE,sBAAsB;CACtB,sBAAsB;AACxB;;AAwBA,SAAS,oBAAoB,SAA+B;CAC1D,MAA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AAY,SAAS,SAAS,QAAQ,CAAC;EACzM,CACF;EACA,GAAI,SAAS,OACT,EAAE,oBAAoB,cAAc,SAAS,KAAK,UAAU,SAAS,QAAQ,KAAK,IAAI,EAAE,GAAG,IAC3F,CAAC;EACL,UAAU,iBAAiB;GACzB;GACA,MAAM;GACN;GACA,OAAO,YAAY,SAAS,OAAO,SAAS;EAC9C,CAAC;CACH,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;AC/MA,MAAa,wBAAgC;CAAE,eAAe;CAAI,WAAW;AAAQ;;;;;;;;AA+BrF,eAAsB,SACpB,QACA,MACgC;CAChC,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,CAAC,CAAC,WAAW,GACzD,MAAM,IAAI,YAAY,+CAA+C;CAEvE,OAAO,UAAU,KAAK,mBAAmB,QAAQ;EAC/C,QAAQ,KAAK,UAAU;EACvB,GAAI,KAAK,UAAU,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;EAChD,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,YAAwC,IAAI,CAAC;EACxF,QAAQ,KAAK;EACb,GAAI,KAAK,gBAAgB,EAAE,eAAe,KAAK,cAAc,IAAI,CAAC;EAClE,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC5C,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"delegate-DFLSVjFG.js","names":[],"sources":["../src/runtime/supervise/authoring.ts","../src/runtime/supervise/delegate.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions, tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific guidance are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt\n}\n\n/** Narrow an untyped `spawn_worker` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n if (!resolveSystemPrompt(parsed.data).trim()) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt },\n }\n}\n\n/** The supervisor skill: an explicit profile-authoring instruction, never an implicit Runtime\n * policy. Editing this text changes how a profile designs the descendants it spawns. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_worker with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.appendSystemPrompt: rich additive instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • tools.agent_runtime_coordination_spawn_worker: true ONLY when this child should author and drive descendants. Add only the other agent_runtime_coordination_<verb> tools it will call, such as observe_agent or steer_agent.',\n ' • A child with spawn_worker MUST carry this complete profile-authoring instruction as an immutable resources.skills entry with resources.failOnError: true, so it can author its own descendants from the same contract.',\n ' • metadata may describe the work, but it never grants recursion or selects a Runtime execution path.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n '3. End your turn while your workers run: Runtime wakes you with each settled worker. A settlement says valid:true only if the deployable check passed.',\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.appendSystemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n \"5. read_journal to re-read YOUR OWN record before you decide the next move: every spawn you made, every settle, every question and answer, every steer, every analyst finding — oldest first, this node only, including what you did before a restart. Use it to see what you already tried instead of trying it again. It is paged: pass the returned nextRow as the next call's sinceRow, narrow with kinds, and raise limit/maxBytes only as far as you will actually read. A truncated:true page means a bound cut it short — keep paging before you conclude you have read everything.\",\n '6. AUTHOR YOUR OWN LENS when the questions you can already ask of a settled trace do not cover the failure you are chasing: define_analyst takes an id, a description, an area, the question in your own words, the instructions for answering it with trace evidence, and the smallest toolGroup that can answer it (model is the seat it runs on; omit it for the run default). It is DATA, never code. Then run_analyst it on any settled worker like a lens the run shipped with, and read the finding. list_analysts shows what you have. Define a lens when you need a different question asked — not a second copy of a question already on the menu.',\n '7. EVERY refusal you get back carries a `reason` naming the exact unmet condition. Read it and change that condition — a spawn refused for budget-exhausted needs a smaller budget or the refund of a settled worker, an invalid-profile needs the named field fixed, a submit_result refused because the check THREW is a broken check to report, not a result to resubmit. Never repeat a call that was refused without changing what it was refused for.',\n '8. ask_parent ONLY when you genuinely cannot decide, and then READ ITS OUTCOME. \"queued-for-parent\" means an inbox above you now holds the question. \"no-parent\" means no inbox above you is configured to receive it: the question is still on the run record for anyone watching, but nothing will route an answer back to you, so do not block. Decide it with answer_question, or answer_question with deferReason to record that it stays open, and carry on — a blocking question left undecided also refuses your stop.',\n '9. Once the work is delivered, end your turn with nothing left running.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// receives in its next wake — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** Resolved authored guidance from replacement, addition and instruction sections. */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read authored guidance without requiring replacement of native coding instructions. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n return [\n Reflect.get(o, 'systemPrompt'),\n Reflect.get(o, 'appendSystemPrompt'),\n ...(Array.isArray(Reflect.get(o, 'instructions')) ? Reflect.get(o, 'instructions') : []),\n Reflect.get(o, 'system'),\n ]\n .filter((value) => typeof value === 'string')\n .join('\\n\\n')\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n","/**\n *\n * `delegate` — the one generic delegation verb. You hand it an INTENT (what you want done) and it\n * hands that intent to a default AUTHORING supervisor: a router-brained supervisor whose standing\n * instruction is `supervisorInstructions()` (the authoring-agent-profiles skill). The supervisor\n * DECOMPOSES the intent and AUTHORS the worker profile it needs per sub-task — there is NO hardcoded\n * coder/researcher profile here. That is the whole point: `delegate('fix the failing test', …)` and\n * `delegate('research X and cite sources', …)` route through the SAME front door; the supervisor\n * writes a code-shaped or research-shaped worker on its own.\n *\n * It is a thin wrapper over `supervise()` — the one front door — so the conserved-budget pool, the\n * completion oracle (`deliverable`), the coordination toolbox, and equal-compute accounting all come\n * for free; nothing is hand-rolled. The result is `supervise()`'s `SupervisedResult` returned\n * UNCHANGED, so its `spentTotal` (`{ iterations, tokens, usd, ms }`) rides straight back to the\n * caller on BOTH paths — a `winner` carries the delivered worker's spend, a `no-winner` carries the\n * spend incurred before it failed. That cost channel means a `delegate()` caller always learns what\n * the delegation actually spent.\n *\n * @experimental\n */\n\nimport { ConfigError } from '../../errors'\nimport type { RouterTransportConfig } from '../router-http-transport'\nimport type { DeliverableSpec } from './completion-gate'\nimport type { ExecutorConfig } from './runtime'\nimport { supervise } from './supervise'\nimport type { SupervisorProfile } from './supervisor-agent'\nimport type { Budget, SupervisedResult } from './types'\n\n/** The conserved pool a `delegate()` call applies when the caller does not pass its own `budget`.\n * A modest token ceiling + a small iteration ceiling — generous enough for a few-worker decompose,\n * bounded enough that an unsupervised intent cannot run away. Callers override via `opts.budget`. */\nexport const defaultDelegateBudget: Budget = { maxIterations: 50, maxTokens: 200_000 }\n\n/** Inputs to {@link delegate}. The intent is the first positional arg; everything here is optional\n * with explicit execution identity, so the common call names one exact supervisor profile. */\nexport interface DelegateOptions<Out = unknown> {\n /** The completion oracle (settled ⟺ delivered) the authored workers settle against. Strongly\n * recommended — without it the supervisor trusts a worker's self-report. For a code intent,\n * `patchDelivered()` is the canonical example; for a free-form answer, a content check. */\n readonly deliverable?: DeliverableSpec<Out>\n /** WHERE the authored workers run — the worker-execution backend (`router-tools` / `sandbox` /\n * `cli-worktree` / …). The supervisor authors the worker PROFILE; this is the substrate it runs\n * on. Provide this OR `makeWorkerAgent`-style wiring through `supervise()` is unavailable. */\n readonly backend?: ExecutorConfig\n /** The conserved compute pool for the whole delegation. Defaults to {@link defaultDelegateBudget}. */\n readonly budget?: Budget\n /** Exact executable authoring supervisor. Model, prompt, harness, and provider live here. */\n readonly supervisorProfile: SupervisorProfile\n /** Router endpoint/auth for a `cli-base` supervisor; contains no behavioral settings. */\n readonly router: RouterTransportConfig\n /** Restrict the run to this subset of models (forwarded to `supervise()`). */\n readonly allowedModels?: readonly string[]\n readonly runId?: string\n}\n\n/**\n * Delegate an INTENT to a default authoring supervisor and return its `SupervisedResult` unchanged.\n *\n * The supervisor authors + spawns whatever worker the intent needs over the conserved-budget pool;\n * `result.spentTotal` reports what the whole delegation actually cost. A `winner` result carries the\n * authored worker's delivered output; a `no-winner` result names why (never a fabricated success).\n */\nexport async function delegate<Out = unknown>(\n intent: string,\n opts: DelegateOptions<Out>,\n): Promise<SupervisedResult<Out>> {\n if (typeof intent !== 'string' || intent.trim().length === 0) {\n throw new ConfigError('delegate: `intent` must be a non-empty string')\n }\n return supervise(opts.supervisorProfile, intent, {\n budget: opts.budget ?? defaultDelegateBudget,\n ...(opts.backend ? { backend: opts.backend } : {}),\n ...(opts.deliverable ? { deliverable: opts.deliverable as DeliverableSpec<unknown> } : {}),\n router: opts.router,\n ...(opts.allowedModels ? { allowedModels: opts.allowedModels } : {}),\n ...(opts.runId ? { runId: opts.runId } : {}),\n }) as Promise<SupervisedResult<Out>>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,kBAAkB,KAAsC;CACtE,MAAM,SAAS,mBAAmB,UAAU,GAAG;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K,cAAc,EAAE,aAAa,KAAK,YAAwC,IAAI,CAAC;EACxF,QAAQ,KAAK;EACb,GAAI,KAAK,gBAAgB,EAAE,eAAe,KAAK,cAAc,IAAI,CAAC;EAClE,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC5C,CAAC;AACH"}
|
package/dist/durable.d.ts
CHANGED
|
@@ -1,8 +1,71 @@
|
|
|
1
|
-
import { $l as PursuitNodePlatform, Au as PursuitFork, Bl as VersionJudge, D as RetainedPendingCause, Ed as DriveHarnessOwnerContext, Fl as NextPursuitVersionInput,
|
|
1
|
+
import { $l as PursuitNodePlatform, Au as PursuitFork, Bl as VersionJudge, D as RetainedPendingCause, Ed as DriveHarnessOwnerContext, Fl as NextPursuitVersionInput, Fv as SpawnJournalCursor, Fy as RunParkedError, Gl as SupervisePursuitOptions, Hl as assertPursuitVersions, Hv as readRunState, Id as ManagerWakePolicy, Il as PursuitVersionChain, Iu as AuthorizedSpawn, Iv as SpawnJournalReadOptions, Iy as RunParkingPolicy, Jl as supervisePursuit, Jy as NodeId, Kl as SupervisedPursuitResult, Ku as SelectSeat, Ll as PursuitVersionStop, Lu as AuthorizedSpawnContext, Lv as SpawnJournalReadRecord, Ly as RunParkingRecord, My as WorkerSlots, Nl as JudgedPursuitVersion, Od as ResolveDriveHarness, Pl as NextPursuitVersion, Py as ParkedRun, Qg as WorkerWatchOptions, Ql as PursuitNodeCost, Rl as PursuitVersions, Rv as SpawnJournalReadResult, Ry as readRunParking, S_ as AuthorizedDownMessage, T_ as DownMessageAuthorizationInput, Ul as SuperviseGraphPursuitOptions, Uu as SeatSelection, Vl as VersionVerdict, Vv as RunState, Wl as SupervisePursuitError, Wu as SeatSelectionInput, Xl as PursuitObserverDelivery, Yl as RunReopen, Zl as PursuitCostProvenance, _v as AnalyzeOnSettleRoute, au as PursuitRunTotals, bd as readRootStreamReceipt, cf as CoordinationTransportOptions, cu as FileObserverJournal, db as SupervisedResult, df as CoordinationRejectReason, du as ObserverRecordKind, eu as PursuitNodeProjection, f_ as QuestionEscalationOutcome, fu as observerRecordDigest, iu as PursuitRunProjection, j_ as MapOnSettleRoute, ju as RUN_FORK_CORRELATION_KEYS, jy as DeadlineCheckIn, l_ as EscalateQuestion, lm as ToolLoopCompactionOptions, lu as ObserverJournal, nu as PursuitNodeUsage, of as CoordinationPublicAddress, ou as PursuitStatus, ql as superviseGraphPursuit, rf as CoordinationAuthentication, ru as PursuitProjection, sf as CoordinationReadAccess, su as projectPursuit, tu as PursuitNodeTiming, ub as RootStreamReceipt, uf as CoordinationHttpAudit, uu as ObserverRecord, vd as RootStreamRecord, w_ as ContinuityMode, yd as readRootStream, zl as SettledPursuitVersion, zv as readSpawnJournal } from "./types-Jg274chm.js";
|
|
2
2
|
import { n as RuntimeDecisionKind, r as RuntimeDecisionPoint, t as RuntimeDecisionEvidenceRef } from "./runtime-hooks-DPghSHV7.js";
|
|
3
3
|
import { a as ChatTurnProducer, c as handleChatTurn, i as ChatTurnIdentity, n as ChatStreamEvent, o as ChatTurnResult, r as ChatTurnHooks, s as RunChatTurnInput, t as deriveExecutionId } from "./execution-handle-CujvqgCn.js";
|
|
4
|
+
import { AgentProfile } from "@tangle-network/agent-interface";
|
|
4
5
|
import { ToolSpan } from "@tangle-network/agent-eval";
|
|
5
6
|
import { LockIdentity } from "@tangle-network/agent-eval/lock-holder";
|
|
7
|
+
/**
|
|
8
|
+
* Read each unconfirmed environment of a settled run by the provider's own id, delete only
|
|
9
|
+
* the ones the provider still holds, and report which were already gone, which this call
|
|
10
|
+
* deleted, and which could not be decided. A kept environment is never read or deleted.
|
|
11
|
+
* The port reads and deletes one id at a time; a fleet listing cannot hide a named worker.
|
|
12
|
+
*/
|
|
13
|
+
/** One environment named by the provider that issued it. */
|
|
14
|
+
interface EnvironmentTarget {
|
|
15
|
+
readonly provider: string;
|
|
16
|
+
readonly environmentId: string;
|
|
17
|
+
}
|
|
18
|
+
/** What a direct read of one environment proved. `unknown` means the read did not decide. */
|
|
19
|
+
type EnvironmentPresence = {
|
|
20
|
+
readonly state: 'absent';
|
|
21
|
+
} | {
|
|
22
|
+
readonly state: 'present';
|
|
23
|
+
} | {
|
|
24
|
+
readonly state: 'unknown';
|
|
25
|
+
readonly detail: string;
|
|
26
|
+
};
|
|
27
|
+
/** What a delete of one environment the read found present proved. */
|
|
28
|
+
type EnvironmentDeletion = {
|
|
29
|
+
readonly state: 'deleted';
|
|
30
|
+
} | {
|
|
31
|
+
readonly state: 'absent';
|
|
32
|
+
} | {
|
|
33
|
+
readonly state: 'unknown';
|
|
34
|
+
readonly detail: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* The caller's provider adapter. `read` and `delete` take the provider's own id.
|
|
38
|
+
* A delete that finds the environment already gone reports `absent`.
|
|
39
|
+
*/
|
|
40
|
+
interface UnconfirmedEnvironmentPort {
|
|
41
|
+
read(target: EnvironmentTarget): Promise<EnvironmentPresence>;
|
|
42
|
+
delete(target: EnvironmentTarget): Promise<EnvironmentDeletion>;
|
|
43
|
+
}
|
|
44
|
+
/** An environment this call proved gone. `nodeId` is the teardown record that named it. */
|
|
45
|
+
interface ReconciledEnvironment extends EnvironmentTarget {
|
|
46
|
+
readonly nodeId?: string;
|
|
47
|
+
}
|
|
48
|
+
/** An environment, or a node with no id, this call could not decide. */
|
|
49
|
+
interface UnreconciledEnvironment {
|
|
50
|
+
readonly nodeId?: string;
|
|
51
|
+
readonly provider?: string;
|
|
52
|
+
readonly environmentId?: string;
|
|
53
|
+
readonly detail: string;
|
|
54
|
+
}
|
|
55
|
+
/** The three sets one reconcile call returns. A repeated id is acted on once and reported
|
|
56
|
+
* on every node that names it. */
|
|
57
|
+
interface UnconfirmedTeardownReconcile {
|
|
58
|
+
readonly confirmed: readonly ReconciledEnvironment[];
|
|
59
|
+
readonly deleted: readonly ReconciledEnvironment[];
|
|
60
|
+
readonly unknown: readonly UnreconciledEnvironment[];
|
|
61
|
+
}
|
|
62
|
+
/** The directory has no settle record, so there is no settled run to reconcile. */
|
|
63
|
+
export declare class NoSettleRecordError extends Error {
|
|
64
|
+
readonly runDir: string;
|
|
65
|
+
constructor(runDir: string);
|
|
66
|
+
}
|
|
67
|
+
/** Finish unconfirmed teardowns named by a settled run's `result.json`. */
|
|
68
|
+
export declare function reconcileUnconfirmedTeardowns(runDir: string, port: UnconfirmedEnvironmentPort): Promise<UnconfirmedTeardownReconcile>;
|
|
6
69
|
/** What the lock file records about its holder. */
|
|
7
70
|
interface RunDirectoryLockHolder {
|
|
8
71
|
readonly pid: number;
|
|
@@ -105,9 +168,13 @@ export declare class SettledRunDirectoryError extends Error {
|
|
|
105
168
|
}
|
|
106
169
|
/**
|
|
107
170
|
* Read the settle record a run directory holds, or `undefined` when it holds none. A file that
|
|
108
|
-
* is present but is not a settle record is corruption and fails loud.
|
|
171
|
+
* is present but is not a settle record is corruption and fails loud. `usage` annotates legacy
|
|
172
|
+
* results by replay without changing their sealed fields; recorded usage always wins.
|
|
109
173
|
*/
|
|
110
|
-
export declare function readSettleRecord(runDir: string
|
|
174
|
+
export declare function readSettleRecord(runDir: string, options?: {
|
|
175
|
+
readonly usage?: boolean;
|
|
176
|
+
readonly requestedProfile?: AgentProfile;
|
|
177
|
+
}): Promise<SupervisedResult<unknown> | undefined>;
|
|
111
178
|
/** Read the most recent failure record, or `undefined` when the directory holds none. */
|
|
112
179
|
export declare function readFailureRecord(runDir: string): Promise<DurableFailureRecord | undefined>;
|
|
113
180
|
interface DurableCoordinationStreamIdentity {
|
|
@@ -146,5 +213,5 @@ interface DurableSupervisionDiscovery {
|
|
|
146
213
|
* append is ignored because it was never acknowledged as committed.
|
|
147
214
|
*/
|
|
148
215
|
export declare function discoverDurableSupervisionRun(runDir: string): Promise<DurableSupervisionDiscovery>;
|
|
149
|
-
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 ParkedRun, 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, RunParkedError, type RunParkingPolicy, type RunParkingRecord, type RunReopen, type RunState, type RuntimeDecisionEvidenceRef, type RuntimeDecisionKind, type RuntimeDecisionPoint, type SeatSelection, type SeatSelectionInput, type SelectSeat, type SettledPursuitVersion, type SpawnJournalCursor, type SpawnJournalReadOptions, type SpawnJournalReadRecord, type SpawnJournalReadResult, type SuperviseGraphPursuitOptions, SupervisePursuitError, type SupervisePursuitOptions, type SupervisedPursuitResult, type ToolLoopCompactionOptions, type VersionJudge, type VersionVerdict, type WorkerSlots, type WorkerWatchOptions, assertPursuitVersions, deriveExecutionId, handleChatTurn, observerRecordDigest, projectPursuit, readRootStream, readRootStreamReceipt, readRunParking, readRunState, readSpawnJournal, superviseGraphPursuit, supervisePursuit };
|
|
216
|
+
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 EnvironmentDeletion, type EnvironmentPresence, type EnvironmentTarget, type EscalateQuestion, FileObserverJournal, type JudgedPursuitVersion, type ManagerWakePolicy, type MapOnSettleRoute, type NextPursuitVersion, type NextPursuitVersionInput, type ObserverJournal, type ObserverRecord, type ObserverRecordKind, type ParkedRun, 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 ReconciledEnvironment, type ResolveDriveHarness, type RetainedPendingCause, type RootStreamRecord, type RunChatTurnInput, type RunDirectoryHolderLiveness, type RunDirectoryLock, type RunDirectoryLockHolder, RunParkedError, type RunParkingPolicy, type RunParkingRecord, type RunReopen, type RunState, type RuntimeDecisionEvidenceRef, type RuntimeDecisionKind, type RuntimeDecisionPoint, type SeatSelection, type SeatSelectionInput, type SelectSeat, type SettledPursuitVersion, type SpawnJournalCursor, type SpawnJournalReadOptions, type SpawnJournalReadRecord, type SpawnJournalReadResult, type SuperviseGraphPursuitOptions, SupervisePursuitError, type SupervisePursuitOptions, type SupervisedPursuitResult, type ToolLoopCompactionOptions, type UnconfirmedEnvironmentPort, type UnconfirmedTeardownReconcile, type UnreconciledEnvironment, type VersionJudge, type VersionVerdict, type WorkerSlots, type WorkerWatchOptions, assertPursuitVersions, deriveExecutionId, handleChatTurn, observerRecordDigest, projectPursuit, readRootStream, readRootStreamReceipt, readRunParking, readRunState, readSpawnJournal, superviseGraphPursuit, supervisePursuit };
|
|
150
217
|
//# sourceMappingURL=durable.d.ts.map
|
package/dist/durable.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Jt as loadSpawnForest, Sn as observerRecordDigest, V as FileSpawnJournal, bn as FileObserverJournal, c as readRootStreamReceipt, en as FileResultBlobStore, s as readRootStream, x as workerCancellationsDir, xn as createFileObserverHooks, y as supervisorRunDir, yr as authoredProfileDigest } from "./supervisor-accounting-DxLQ_TQe.js";
|
|
2
2
|
import { f as RuntimeRunStateError, m as ValidationError } from "./errors-AzSuGI23.js";
|
|
3
3
|
import { c as errorMessage } from "./util-C_cdPNC4.js";
|
|
4
|
-
import { $ as assertValidBudget, M as contentAddress, n as runtimeFailureCause } from "./failure-cause-
|
|
5
|
-
import { Dt as isFiniteNumber, Et as failedItems, i as RunParkedError, r as assertResumeLimits, s as readRunParking } from "./supervisor-
|
|
4
|
+
import { $ as assertValidBudget, M as contentAddress, n as runtimeFailureCause } from "./failure-cause-rJTm_Tx8.js";
|
|
5
|
+
import { Dt as isFiniteNumber, Et as failedItems, i as RunParkedError, r as assertResumeLimits, s as readRunParking } from "./supervisor-gC-u_PRk.js";
|
|
6
6
|
import { t as isNoEntError } from "./jsonl-file-DsxVI0E_.js";
|
|
7
7
|
import { i as syncDurableDirectory, r as publishExclusiveDurableFile, s as fenceRunWrite } from "./durable-file-DstVeHcj.js";
|
|
8
8
|
import { a as withPursuitContext, t as composeRuntimeHooks } from "./runtime-hooks-CsW2pfFk.js";
|
|
9
9
|
import { a as applyExactAgentProfileDiff } from "./profile-CNSQjOes.js";
|
|
10
|
-
import { a as runCancelRequestFile, h as rootCoordinationOwner, o as runCancellationFile, v as FileCoordinationLog } from "./run-cancellation-
|
|
11
|
-
import { a as superviseRootProfile, l as runToolSpans, t as supervise } from "./supervise-
|
|
12
|
-
import { a as
|
|
13
|
-
import { a as readFailureRecord, c as writeFailureRecord, i as parseSettleRecord, l as writeSettleRecord, n as SETTLE_RECORD_FILE, o as readSettleRecord, r as SettledRunDirectoryError, s as settleRecordDigest, t as FAILURE_RECORD_FILE } from "./settle-record-
|
|
14
|
-
import { a as graphExecutionOptions, i as superviseAgentGraph } from "./graph-
|
|
10
|
+
import { a as runCancelRequestFile, h as rootCoordinationOwner, o as runCancellationFile, v as FileCoordinationLog } from "./run-cancellation-B84X8ZAP.js";
|
|
11
|
+
import { a as superviseRootProfile, l as runToolSpans, t as supervise } from "./supervise-xwl2D6q3.js";
|
|
12
|
+
import { a as acquireRunDirectoryLock, i as RunDirectoryLockedError, n as readSpawnJournal, o as readRunDirectoryLock, r as RUN_DIRECTORY_LOCK_FILE, s as runDirectoryHolderIsLive, t as readRunState } from "./run-state-Dh1bGERI.js";
|
|
13
|
+
import { a as readFailureRecord, c as writeFailureRecord, i as parseSettleRecord, l as writeSettleRecord, n as SETTLE_RECORD_FILE, o as readSettleRecord, r as SettledRunDirectoryError, s as settleRecordDigest, t as FAILURE_RECORD_FILE } from "./settle-record-C6LdVvok.js";
|
|
14
|
+
import { a as graphExecutionOptions, i as superviseAgentGraph } from "./graph-BjQF2syl.js";
|
|
15
15
|
import { n as handleChatTurn, t as deriveExecutionId } from "./execution-handle-Bd2_nUB6.js";
|
|
16
|
-
import { n as projectPursuit, t as discoverDurableSupervisionRun } from "./supervision-discovery-
|
|
16
|
+
import { n as projectPursuit, t as discoverDurableSupervisionRun } from "./supervision-discovery-B47U8TH5.js";
|
|
17
17
|
import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sha256Bytes } from "@tangle-network/agent-interface";
|
|
18
18
|
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync } from "node:fs";
|
|
19
19
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
@@ -927,6 +927,154 @@ function identicalFailureStreak(versions, count) {
|
|
|
927
927
|
const [first] = failures;
|
|
928
928
|
return first !== null && first !== void 0 && failures.every((failure) => failure === first) ? first : null;
|
|
929
929
|
}
|
|
930
|
+
// src/durable/reconcile-unconfirmed-teardowns.ts
|
|
931
|
+
/** The directory has no settle record, so there is no settled run to reconcile. */
|
|
932
|
+
var NoSettleRecordError = class extends Error {
|
|
933
|
+
runDir;
|
|
934
|
+
constructor(runDir) {
|
|
935
|
+
super(`reconcileUnconfirmedTeardowns: ${runDir} has no settle record`);
|
|
936
|
+
this.name = "NoSettleRecordError";
|
|
937
|
+
this.runDir = runDir;
|
|
938
|
+
}
|
|
939
|
+
};
|
|
940
|
+
const DETAIL_LIMIT = 240;
|
|
941
|
+
/** Finish unconfirmed teardowns named by a settled run's `result.json`. */
|
|
942
|
+
async function reconcileUnconfirmedTeardowns(runDir, port) {
|
|
943
|
+
const directory = resolve(runDir);
|
|
944
|
+
const holder = await runDirectoryHolderIsLive(directory);
|
|
945
|
+
if (holder.live) {
|
|
946
|
+
if (holder.holder === void 0) throw new Error(`reconcileUnconfirmedTeardowns: ${directory} is held by a lock this host cannot read`);
|
|
947
|
+
throw new RunDirectoryLockedError(resolve(directory, RUN_DIRECTORY_LOCK_FILE), holder.holder);
|
|
948
|
+
}
|
|
949
|
+
const settled = await readSettleRecord(directory);
|
|
950
|
+
if (settled === void 0) throw new NoSettleRecordError(directory);
|
|
951
|
+
const lock = await acquireRunDirectoryLock(directory, settled.tree.root);
|
|
952
|
+
try {
|
|
953
|
+
const current = await readSettleRecord(directory);
|
|
954
|
+
if (current === void 0) throw new NoSettleRecordError(directory);
|
|
955
|
+
return await sweep(current, port);
|
|
956
|
+
} finally {
|
|
957
|
+
await lock.release();
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
async function sweep(settled, port) {
|
|
961
|
+
const listed = settled.teardownUnconfirmed;
|
|
962
|
+
if (listed === void 0) return {
|
|
963
|
+
confirmed: [],
|
|
964
|
+
deleted: [],
|
|
965
|
+
unknown: []
|
|
966
|
+
};
|
|
967
|
+
if (!Array.isArray(listed)) throw new Error("reconcileUnconfirmedTeardowns: settle record teardownUnconfirmed is not an array");
|
|
968
|
+
const confirmed = [];
|
|
969
|
+
const deleted = [];
|
|
970
|
+
const unknown = [];
|
|
971
|
+
const decided = /* @__PURE__ */ new Map();
|
|
972
|
+
for (const entry of listed) await oneNode(entry, port, decided, confirmed, deleted, unknown);
|
|
973
|
+
return {
|
|
974
|
+
confirmed,
|
|
975
|
+
deleted,
|
|
976
|
+
unknown
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
async function oneNode(entry, port, decided, confirmed, deleted, unknown) {
|
|
980
|
+
if (typeof entry !== "object" || entry === null) {
|
|
981
|
+
unknown.push({ detail: "unreadable teardown record" });
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
const record = entry;
|
|
985
|
+
const nodeId = typeof record.id === "string" && record.id.length > 0 ? record.id : void 0;
|
|
986
|
+
const environments = Array.isArray(record.environments) ? record.environments : [];
|
|
987
|
+
const keptIds = keptKeys(record.kept);
|
|
988
|
+
const sweepable = [];
|
|
989
|
+
let unnamed = 0;
|
|
990
|
+
for (const item of environments) {
|
|
991
|
+
const named = sweepableEnvironment(item);
|
|
992
|
+
if (named === "kept") continue;
|
|
993
|
+
if (named !== void 0 && keptIds.has(`${named.provider}\0${named.environmentId}`)) continue;
|
|
994
|
+
if (named === void 0) unnamed += 1;
|
|
995
|
+
else sweepable.push(named);
|
|
996
|
+
}
|
|
997
|
+
if (sweepable.length === 0 && unnamed === 0 && environments.length === 0 && keptIds.size === 0) {
|
|
998
|
+
unknown.push({
|
|
999
|
+
...nodeId === void 0 ? {} : { nodeId },
|
|
1000
|
+
detail: "no environment id"
|
|
1001
|
+
});
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
for (let index = 0; index < unnamed; index += 1) unknown.push({
|
|
1005
|
+
...nodeId === void 0 ? {} : { nodeId },
|
|
1006
|
+
detail: "environment record has no provider id"
|
|
1007
|
+
});
|
|
1008
|
+
for (const target of sweepable) {
|
|
1009
|
+
const outcome = await decisionFor(port, decided, target);
|
|
1010
|
+
const row = {
|
|
1011
|
+
...nodeId === void 0 ? {} : { nodeId },
|
|
1012
|
+
...target
|
|
1013
|
+
};
|
|
1014
|
+
if (outcome.kind === "confirmed") confirmed.push(row);
|
|
1015
|
+
else if (outcome.kind === "deleted") deleted.push(row);
|
|
1016
|
+
else unknown.push({
|
|
1017
|
+
...row,
|
|
1018
|
+
detail: outcome.detail
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
function keptKeys(value) {
|
|
1023
|
+
const keys = /* @__PURE__ */ new Set();
|
|
1024
|
+
if (!Array.isArray(value)) return keys;
|
|
1025
|
+
for (const item of value) {
|
|
1026
|
+
if (typeof item !== "object" || item === null) continue;
|
|
1027
|
+
const record = item;
|
|
1028
|
+
if (typeof record.provider !== "string" || typeof record.environmentId !== "string") continue;
|
|
1029
|
+
keys.add(`${record.provider}\0${record.environmentId}`);
|
|
1030
|
+
}
|
|
1031
|
+
return keys;
|
|
1032
|
+
}
|
|
1033
|
+
function sweepableEnvironment(value) {
|
|
1034
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
1035
|
+
const record = value;
|
|
1036
|
+
if (record.keptFor !== void 0) return "kept";
|
|
1037
|
+
if (typeof record.provider !== "string" || record.provider.length === 0) return void 0;
|
|
1038
|
+
if (typeof record.environmentId !== "string" || record.environmentId.length === 0) return;
|
|
1039
|
+
return {
|
|
1040
|
+
provider: record.provider,
|
|
1041
|
+
environmentId: record.environmentId
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
function decisionFor(port, decided, target) {
|
|
1045
|
+
const key = `${target.provider}\0${target.environmentId}`;
|
|
1046
|
+
const cached = decided.get(key);
|
|
1047
|
+
if (cached !== void 0) return cached;
|
|
1048
|
+
const pending = decide(port, target);
|
|
1049
|
+
decided.set(key, pending);
|
|
1050
|
+
return pending;
|
|
1051
|
+
}
|
|
1052
|
+
async function decide(port, target) {
|
|
1053
|
+
try {
|
|
1054
|
+
const read = await port.read(target);
|
|
1055
|
+
if (read?.state === "absent") return { kind: "confirmed" };
|
|
1056
|
+
if (read?.state !== "present") return {
|
|
1057
|
+
kind: "unknown",
|
|
1058
|
+
detail: detailOf(read?.state === "unknown" ? read.detail : void 0)
|
|
1059
|
+
};
|
|
1060
|
+
const removed = await port.delete(target);
|
|
1061
|
+
if (removed?.state === "deleted" || removed?.state === "absent") return { kind: "deleted" };
|
|
1062
|
+
return {
|
|
1063
|
+
kind: "unknown",
|
|
1064
|
+
detail: detailOf(removed?.state === "unknown" ? removed.detail : void 0)
|
|
1065
|
+
};
|
|
1066
|
+
} catch (error) {
|
|
1067
|
+
return {
|
|
1068
|
+
kind: "unknown",
|
|
1069
|
+
detail: detailOf(error)
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
function detailOf(value) {
|
|
1074
|
+
const oneLine = (value instanceof Error ? value.message : typeof value === "string" ? value : "unreadable provider answer").replace(/\s+/g, " ").trim();
|
|
1075
|
+
const bounded = oneLine.length > DETAIL_LIMIT ? `${oneLine.slice(0, 239)}…` : oneLine;
|
|
1076
|
+
return bounded.length > 0 ? bounded : "unreadable provider answer";
|
|
1077
|
+
}
|
|
930
1078
|
// src/durable/run-fork.ts
|
|
931
1079
|
/**
|
|
932
1080
|
* The `execution.correlation` keys a fork records on its root. Runtime writes them; a caller that
|
|
@@ -1458,6 +1606,6 @@ function rootEvent(pursuitId, runId, phase, timestamp, payload) {
|
|
|
1458
1606
|
...payload ? { payload: Object.freeze({ ...payload }) } : {}
|
|
1459
1607
|
});
|
|
1460
1608
|
}
|
|
1461
|
-
export { FileObserverJournal, RUN_FORK_CORRELATION_KEYS, RunDirectoryLockedError, RunParkedError, SettledRunDirectoryError, SupervisePursuitError, acquireRunDirectoryLock, assertPursuitVersions, deriveExecutionId, discoverDurableSupervisionRun, durableRunToolSpans, handleChatTurn, observerRecordDigest, projectPursuit, readFailureRecord, readRootStream, readRootStreamReceipt, readRunDirectoryLock, readRunParking, readRunState, readSettleRecord, readSpawnJournal, runDirectoryHolderIsLive, superviseGraphPursuit, supervisePursuit };
|
|
1609
|
+
export { FileObserverJournal, NoSettleRecordError, RUN_FORK_CORRELATION_KEYS, RunDirectoryLockedError, RunParkedError, SettledRunDirectoryError, SupervisePursuitError, acquireRunDirectoryLock, assertPursuitVersions, deriveExecutionId, discoverDurableSupervisionRun, durableRunToolSpans, handleChatTurn, observerRecordDigest, projectPursuit, readFailureRecord, readRootStream, readRootStreamReceipt, readRunDirectoryLock, readRunParking, readRunState, readSettleRecord, readSpawnJournal, reconcileUnconfirmedTeardowns, runDirectoryHolderIsLive, superviseGraphPursuit, supervisePursuit };
|
|
1462
1610
|
|
|
1463
1611
|
//# sourceMappingURL=durable.js.map
|