@tangle-network/agent-runtime 10.0.2 → 10.0.4
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 +8 -0
- package/dist/{activation-B0DHGRtB.js → activation-38MolXIP.js} +2 -2
- package/dist/{activation-B0DHGRtB.js.map → activation-38MolXIP.js.map} +1 -1
- package/dist/{activation-D0Sp7wMc.d.ts → activation-Ckx0yHjT.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{continuation-CZaeHEzQ.js → continuation-CL4B1Y4M.js} +3 -3
- package/dist/{continuation-CZaeHEzQ.js.map → continuation-CL4B1Y4M.js.map} +1 -1
- package/dist/{delegate-Co5iUyS0.js → delegate-dhNeiaH_.js} +2 -2
- package/dist/{delegate-Co5iUyS0.js.map → delegate-dhNeiaH_.js.map} +1 -1
- package/dist/{driver-control-acknowledgers-B1Qx2JUz.js → driver-control-acknowledgers-C6GaGBf_.js} +98 -55
- package/dist/{driver-control-acknowledgers-B1Qx2JUz.js.map → driver-control-acknowledgers-C6GaGBf_.js.map} +1 -1
- package/dist/durable-file-DJ3JsA4B.js +1 -0
- package/dist/durable-file-lXnojyij.js +509 -0
- package/dist/durable-file-lXnojyij.js.map +1 -0
- package/dist/durable-writer-thread.d.ts +1 -0
- package/dist/durable-writer-thread.js +86 -0
- package/dist/durable-writer-thread.js.map +1 -0
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +15 -128
- package/dist/durable.js.map +1 -1
- package/dist/{graph-uc4eT1wR.js → graph-CwLg3LGC.js} +7 -7
- package/dist/{graph-uc4eT1wR.js.map → graph-CwLg3LGC.js.map} +1 -1
- package/dist/{graph-registry-DxhlgHdA.js → graph-registry-Bs6mGKou.js} +1 -1
- package/dist/{graph-registry-j9t9J0KT.js → graph-registry-DtGd03zk.js} +4 -4
- package/dist/{graph-registry-j9t9J0KT.js.map → graph-registry-DtGd03zk.js.map} +1 -1
- package/dist/{improve-BM0HlzMi.js → improve-C_LKfgH9.js} +7 -7
- package/dist/{improve-BM0HlzMi.js.map → improve-C_LKfgH9.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +9 -9
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +4 -4
- package/dist/{jsonl-file-BhuxeejY.js → jsonl-file-DyzefaZ6.js} +53 -11
- package/dist/jsonl-file-DyzefaZ6.js.map +1 -0
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +18 -16
- package/dist/{loop-runner-CRC-RE4D.js → loop-runner-BS3ru-yj.js} +2 -2
- package/dist/{loop-runner-CRC-RE4D.js.map → loop-runner-BS3ru-yj.js.map} +1 -1
- package/dist/{loop-runner-npLkvCU5.d.ts → loop-runner-LWqWf8FD.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 +5 -5
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-CJrMGyZW.js → provision-supervisor-D8N0l2DM.js} +6 -6
- package/dist/{provision-supervisor-CJrMGyZW.js.map → provision-supervisor-D8N0l2DM.js.map} +1 -1
- package/dist/result-blob-store-DfTcyQ05.js +76 -0
- package/dist/result-blob-store-DfTcyQ05.js.map +1 -0
- package/dist/{run-cancellation-CBP3Bmad.js → run-cancellation-D3qc9wAD.js} +5 -209
- package/dist/run-cancellation-D3qc9wAD.js.map +1 -0
- package/dist/run-lock-D1xnb9ve.js +193 -0
- package/dist/run-lock-D1xnb9ve.js.map +1 -0
- package/dist/run-reopen-DVM5AEKV.js +134 -0
- package/dist/run-reopen-DVM5AEKV.js.map +1 -0
- package/dist/run-state-tgQ-S9Ln.js +180 -0
- package/dist/run-state-tgQ-S9Ln.js.map +1 -0
- package/dist/{runtime-BqSaWTEY.js → runtime-BTECV05R.js} +21 -19
- package/dist/{runtime-BqSaWTEY.js.map → runtime-BTECV05R.js.map} +1 -1
- package/dist/{search-executor-C9TN-KgI.js → search-executor-Uco2_KTB.js} +3 -3
- package/dist/{search-executor-C9TN-KgI.js.map → search-executor-Uco2_KTB.js.map} +1 -1
- package/dist/{server-CcMa8Lt9.js → server-BMp24-xn.js} +3 -3
- package/dist/{server-CcMa8Lt9.js.map → server-BMp24-xn.js.map} +1 -1
- package/dist/{settle-record-BtjYZabI.js → settle-record-au3w7bQG.js} +5 -4
- package/dist/settle-record-au3w7bQG.js.map +1 -0
- package/dist/{structural-rollout-2oRJjwyM.js → structural-rollout-D8wufVJI.js} +4 -4
- package/dist/{structural-rollout-2oRJjwyM.js.map → structural-rollout-D8wufVJI.js.map} +1 -1
- package/dist/{supervise-BrgtzJf3.js → supervise-DtVdvZpr.js} +9 -8
- package/dist/{supervise-BrgtzJf3.js.map → supervise-DtVdvZpr.js.map} +1 -1
- package/dist/supervise-identity-S5XwgaF3.js +210 -0
- package/dist/supervise-identity-S5XwgaF3.js.map +1 -0
- package/dist/{supervision-discovery-DLMm3UOr.js → supervision-discovery-Cqu4NxPV.js} +3 -3
- package/dist/{supervision-discovery-DLMm3UOr.js.map → supervision-discovery-Cqu4NxPV.js.map} +1 -1
- package/dist/{supervisor-ACffs_W4.js → supervisor-CHgCAMjm.js} +13 -176
- package/dist/supervisor-CHgCAMjm.js.map +1 -0
- package/dist/{supervisor-accounting-BlJqoP3k.js → supervisor-accounting-CZ7i4cd5.js} +171 -153
- package/dist/supervisor-accounting-CZ7i4cd5.js.map +1 -0
- package/dist/supervisor-root-contract-D70KTGXF.js +165 -0
- package/dist/supervisor-root-contract-D70KTGXF.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +11 -11
- package/dist/{top-web-PYyzBMsK.js → top-web-COrMqTRC.js} +7 -6
- package/dist/{top-web-PYyzBMsK.js.map → top-web-COrMqTRC.js.map} +1 -1
- package/dist/tui/bin.js +3 -3
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +2 -2
- package/dist/{types-DX1OGeHE.d.ts → types-9xsn2GGY.d.ts} +10 -3
- package/package.json +1 -1
- package/dist/durable-file-CksURHlH.js +0 -1
- package/dist/durable-file-DstVeHcj.js +0 -228
- package/dist/durable-file-DstVeHcj.js.map +0 -1
- package/dist/jsonl-file-BhuxeejY.js.map +0 -1
- package/dist/run-cancellation-CBP3Bmad.js.map +0 -1
- package/dist/run-state-BnhCVbTY.js +0 -357
- package/dist/run-state-BnhCVbTY.js.map +0 -1
- package/dist/settle-record-BtjYZabI.js.map +0 -1
- package/dist/supervisor-ACffs_W4.js.map +0 -1
- package/dist/supervisor-accounting-BlJqoP3k.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"continuation-CZaeHEzQ.js","names":[],"sources":["../src/finite-number.ts","../src/runtime/supervise/continuation.ts"],"sourcesContent":["export function isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value)\n}\n","/**\n * One check ({@link CheckVerdict}; {@link CheckUnavailableError} pauses), one\n * {@link ContinuationPolicy} (`maxBarren`, an optional deadline, no re-prompt default), and one\n * note ({@link composeContinuationNote} owns the facts, {@link ContinuationProfile} owns the\n * words, a play may only append).\n */\n\nimport { mkdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { TraceAnalysisStore } from '@tangle-network/agent-eval'\nimport { sha256 } from '../../content-digest'\nimport { ValidationError } from '../../errors'\nimport { isFiniteNumber } from '../../finite-number'\nimport type { CheckVerdict } from './completion-gate'\nimport type { DriverBudgetReadout, DriverProgressMark } from './driver-retry'\nimport { writeAtomicDurableFile } from './durable-file'\n\n/** Read a check function's return value into a verdict. Anything but `true` or a passing verdict\n * is a failure: a check fails closed. */\nexport function checkVerdictOf(outcome: unknown): CheckVerdict {\n if (outcome === true) return { pass: true }\n if (typeof outcome !== 'object' || outcome === null || Array.isArray(outcome)) {\n return { pass: false }\n }\n const raw = outcome as Record<string, unknown>\n const items =\n typeof raw.items === 'object' && raw.items !== null && !Array.isArray(raw.items)\n ? Object.fromEntries(\n Object.entries(raw.items as Record<string, unknown>).filter(\n (entry): entry is [string, number] =>\n typeof entry[1] === 'number' && Number.isFinite(entry[1]),\n ),\n )\n : undefined\n const failures = Array.isArray(raw.failures)\n ? raw.failures.filter((line): line is string => typeof line === 'string' && line.trim() !== '')\n : undefined\n return Object.freeze({\n pass: raw.pass === true,\n ...(items === undefined ? {} : { items: Object.freeze(items) }),\n ...(isFiniteNumber(raw.composite) ? { composite: raw.composite } : {}),\n ...(isFiniteNumber(raw.threshold) ? { threshold: raw.threshold } : {}),\n ...(failures === undefined ? {} : { failures: Object.freeze(failures) }),\n ...(typeof raw.review === 'string' && raw.review.trim() !== ''\n ? { review: raw.review.trim() }\n : {}),\n })\n}\n\n/** Items that fail in `verdict`: every item below 1, or the named items of its FAIL lines. */\nexport function failedItems(verdict: CheckVerdict): ReadonlyArray<string> {\n if (verdict.items !== undefined) {\n return Object.entries(verdict.items)\n .filter(([, value]) => value < 1)\n .map(([name]) => name)\n }\n return (verdict.failures ?? []).map((line) => line.slice('FAIL '.length).split(/[\\s:]/u)[0] ?? '')\n}\n\n/** Items that pass in `verdict`. */\nexport function passedItems(verdict: CheckVerdict): ReadonlyArray<string> {\n return Object.entries(verdict.items ?? {})\n .filter(([, value]) => value >= 1)\n .map(([name]) => name)\n}\n\n/** One time the check ran inside the run, whatever started it. */\nexport interface CheckRead {\n /** 1-based count of check reads in this manager, the unavailable ones included. */\n readonly read: number\n /** The driver attempt the read belongs to. */\n readonly attempt: number\n /** Epoch ms. */\n readonly at: number\n /** `submit`: a `submit_result` call. `turn-end`: the turn ended with no accepted result. */\n readonly source: 'submit' | 'turn-end'\n /** Absent when the check could not run. */\n readonly verdict?: CheckVerdict\n /** Why the check could not run. */\n readonly unavailable?: string\n}\n\n// ── The resend rule ──────────────────────────────────────────────────────────────────────────────\n\n/**\n * How a manager with a completion check is sent back when its turn ends unmet.\n *\n * Required for an external manager with a check: Runtime supplies no default, because a retry\n * default in source is a research decision the record must make. There is no re-prompt count.\n * The loop re-enters until the check passes or a bound ends it: cancellation, the budget, or\n * this deadline when one is set. After `maxBarren` turns in a row without progress, each further continuation\n * waits a barren pause first (5 minutes, doubling to 60) and is journaled `barren-pause`; a\n * barren streak never ends the run. A tool `report_blocked` shows\n * really failed is recorded and the loop goes on: a blocked tool is not a terminal condition.\n * Progress means the check's best composite rose, an accepted result, or a worker that delivered.\n */\nexport interface ContinuationPolicy {\n /** No re-entry starts at or after this instant: epoch ms, or an ISO 8601 time. Absent: no clock\n * ends the run; it ends when its check passes, on cancellation, or on a spent budget. */\n readonly deadline?: number | string\n /** Re-entered turns in a row that may end without progress before each further continuation\n * waits a barren pause. Minimum 1. The evidence for 2: repair loses most of its effect within\n * two or three attempts, and a fresh start at the same budget scored higher (Debugging Decay\n * Index). */\n readonly maxBarren: number\n /** Every instruction word of the note. */\n readonly profile: ContinuationProfile\n /** `verbatim` sends the check's FAIL lines, the protected items, and what changed. A check with\n * `feedback: 'pass-only'` overrides this to `off`. */\n readonly failures: 'verbatim' | 'off'\n /** `on` runs the question panel at each continuation and puts its admitted findings in the note.\n * Requires `runPanel`. */\n readonly panel: 'on' | 'off'\n /** `on` states the bar: every check item with its state, the best version's verdict and the\n * gap, the reference result, and the check's review. */\n readonly bar: 'on' | 'off'\n /** The play's registered reference result, for the bar. */\n readonly reference?: string\n /** The best version's verdict on the same check, for the bar. The version loop sets it. */\n readonly best?: { readonly label: string; readonly verdict: CheckVerdict }\n /** The panel's dollar caps. Required with `panel: 'on'`. */\n readonly panelUsd?: { readonly perContinuation: number; readonly perRun: number }\n /** The question panel. Required with `panel: 'on'`. */\n readonly runPanel?: ContinuationPanel\n /** A play's own section, appended after Runtime's sections. It cannot remove or rewrite one. */\n readonly append?: ContinuationAppend\n /**\n * What a re-entered manager's harness session is. `native` (the default) sends the next turn\n * into the same harness session wherever the backend proves it, with the unmet items and what\n * changed. `fresh` starts a new harness session on every re-entry (a continuation, a wake, a\n * failure retry, a pause) whose only input is the full re-entry task: the original task, the\n * check's description and the coordinator's run state. The environment and its files are kept\n * while the provider holds them; only the conversation is new, so whatever the next turn needs\n * must be in the journal, the workspace or Knowledge, never in an earlier turn.\n *\n * Runtime's own drive harnesses (bridge and provider) honor it; a caller's `driveHarness`\n * receives it as `session` and must start a new session on each drive that carries `reentry`.\n */\n readonly session?: 'native' | 'fresh'\n}\n\n/** Resolve and check a policy before any compute. Returns the deadline in epoch ms, or undefined\n * when the policy sets none. */\nexport function admitContinuationPolicy(\n policy: ContinuationPolicy,\n context: string,\n): number | undefined {\n if (typeof policy !== 'object' || policy === null) {\n throw new ValidationError(`${context}: continuation must be an object`)\n }\n const deadlineMs =\n typeof policy.deadline === 'string' ? Date.parse(policy.deadline) : policy.deadline\n if (\n deadlineMs !== undefined &&\n (typeof deadlineMs !== 'number' || !Number.isFinite(deadlineMs) || deadlineMs <= 0)\n ) {\n throw new ValidationError(\n `${context}: continuation.deadline, when set, must be a finite time (epoch ms or ISO 8601)`,\n )\n }\n if (!Number.isInteger(policy.maxBarren) || policy.maxBarren < 1) {\n throw new ValidationError(`${context}: continuation.maxBarren must be an integer >= 1`)\n }\n if (policy.failures !== 'verbatim' && policy.failures !== 'off') {\n throw new ValidationError(`${context}: continuation.failures must be 'verbatim' or 'off'`)\n }\n if (policy.panel !== 'on' && policy.panel !== 'off') {\n throw new ValidationError(`${context}: continuation.panel must be 'on' or 'off'`)\n }\n if (policy.bar !== 'on' && policy.bar !== 'off') {\n throw new ValidationError(`${context}: continuation.bar must be 'on' or 'off'`)\n }\n if (policy.panel === 'on') {\n if (typeof policy.runPanel !== 'function') {\n throw new ValidationError(`${context}: continuation.panel 'on' needs runPanel`)\n }\n const usd = policy.panelUsd\n if (\n usd === undefined ||\n !isFiniteNumber(usd.perContinuation) ||\n !isFiniteNumber(usd.perRun) ||\n usd.perContinuation <= 0 ||\n usd.perRun < usd.perContinuation\n ) {\n throw new ValidationError(\n `${context}: continuation.panel 'on' needs panelUsd with 0 < perContinuation <= perRun`,\n )\n }\n }\n if (policy.append !== undefined && typeof policy.append !== 'function') {\n throw new ValidationError(`${context}: continuation.append must be a function`)\n }\n if (policy.session !== undefined && policy.session !== 'native' && policy.session !== 'fresh') {\n throw new ValidationError(`${context}: continuation.session must be 'native' or 'fresh'`)\n }\n if (policy.reference !== undefined && typeof policy.reference !== 'string')\n throw new ValidationError(`${context}: continuation.reference must be a string`)\n admitContinuationProfile(policy.profile, context)\n return deadlineMs\n}\n\n// ── The profile ──────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Every instruction word of the note. Runtime supplies the facts and their order; this data\n * supplies the words, so the note can be improved (by a person, reflection, or GEPA) without a code\n * change. Templates may name the facts in `CONTINUATION_FACTS` as `{name}`.\n */\nexport interface ContinuationProfile {\n /** Recorded with every note, so each continuation names the words it carried. */\n readonly id: string\n /** Section 1, the verdict. The first line should state the failure as a fact. */\n readonly opening: string\n /** Section 7: what to do before the next submit. */\n readonly plan: string\n /** Section 8: what the harness enforces, and the honest exit. */\n readonly rules: string\n /** Section headings; an empty heading prints the section without one. */\n readonly headings: {\n readonly failures: string\n readonly protected: string\n readonly changed: string\n readonly findings: string\n readonly bar: string\n readonly plan: string\n readonly rules: string\n }\n /** The bar's standing instruction, printed under its heading. */\n readonly barRule?: string\n /** The panel's question templates. `{item}` expands over failed items and `{worker}` over\n * settled workers; a template with neither is asked once. */\n readonly questions?: ReadonlyArray<string>\n /** The panel's model, when the profile chooses one. */\n readonly panelModel?: string\n /** What a new version's director reads about the best version's review, for the version\n * chain's `'review-of-best'`. It may name `{version}`, `{path}` and `{score}`. */\n readonly review?: string\n}\n\n/** The facts a profile template may name. */\nexport const CONTINUATION_FACTS = [\n 'composite',\n 'threshold',\n 'failed',\n 'total',\n 'reads',\n 'owed',\n 'settled',\n 'delivered',\n 'continuation',\n] as const\n\ntype ContinuationFact = (typeof CONTINUATION_FACTS)[number]\n\nconst factNames: ReadonlySet<string> = new Set(CONTINUATION_FACTS)\nconst placeholder = /\\{([a-zA-Z]+)\\}/gu\n\nfunction admitContinuationProfile(profile: ContinuationProfile, context: string): void {\n if (typeof profile !== 'object' || profile === null) {\n throw new ValidationError(`${context}: continuation.profile must be an object`)\n }\n if (typeof profile.id !== 'string' || profile.id.trim() === '') {\n throw new ValidationError(`${context}: continuation.profile.id must be non-empty`)\n }\n const texts: Array<[string, unknown]> = [\n ['opening', profile.opening],\n ['plan', profile.plan],\n ['rules', profile.rules],\n ...Object.entries(profile.headings ?? {}).map(([key, value]): [string, unknown] => [\n `headings.${key}`,\n value,\n ]),\n ...(profile.barRule === undefined ? [] : [['barRule', profile.barRule] as [string, unknown]]),\n ]\n for (const key of ['failures', 'protected', 'changed', 'findings', 'bar', 'plan', 'rules']) {\n if (typeof (profile.headings as Record<string, unknown> | undefined)?.[key] !== 'string') {\n throw new ValidationError(`${context}: continuation.profile.headings.${key} must be a string`)\n }\n }\n for (const [key, text] of texts) {\n if (typeof text !== 'string') {\n throw new ValidationError(`${context}: continuation.profile.${key} must be a string`)\n }\n for (const match of text.matchAll(placeholder)) {\n if (!factNames.has(match[1] ?? '')) {\n throw new ValidationError(\n `${context}: continuation.profile.${key} names {${match[1]}}, which is not a fact Runtime supplies (${CONTINUATION_FACTS.join(', ')})`,\n )\n }\n }\n }\n if (profile.review !== undefined) {\n if (typeof profile.review !== 'string' || profile.review.trim() === '') {\n throw new ValidationError(`${context}: continuation.profile.review must be non-empty`)\n }\n for (const match of profile.review.matchAll(placeholder)) {\n if (!['version', 'path', 'score'].includes(match[1] ?? '')) {\n throw new ValidationError(\n `${context}: continuation.profile.review names {${match[1]}}; it may name {version}, {path} and {score}`,\n )\n }\n }\n }\n if (profile.opening.trim() === '') {\n throw new ValidationError(`${context}: continuation.profile.opening must be non-empty`)\n }\n if (profile.panelModel !== undefined && typeof profile.panelModel !== 'string')\n throw new ValidationError(`${context}: continuation.profile.panelModel must be a string`)\n if (profile.questions !== undefined && !Array.isArray(profile.questions))\n throw new ValidationError(`${context}: continuation.profile.questions must be an array`)\n for (const [index, question] of (profile.questions ?? []).entries()) {\n if (typeof question !== 'string' || question.trim() === '') {\n throw new ValidationError(\n `${context}: continuation.profile.questions[${index}] must be a non-empty string`,\n )\n }\n }\n}\n\n// ── The panel ────────────────────────────────────────────────────────────────────────────────────\n\n/** What the question panel reads for one continuation. */\nexport interface ContinuationPanelInput {\n /** 1-based continuation number. */\n readonly continuation: number\n readonly task: unknown\n /** The check's verdict this note reports; absent when no result reached the check. */\n readonly verdict?: CheckVerdict\n /** Every check read so far, oldest first. */\n readonly reads: ReadonlyArray<CheckRead>\n /** The expanded questions, one per atomic question. */\n readonly questions: ReadonlyArray<string>\n /**\n * The run's own traces, one per agent and named by its node id: the manager's root stream, when\n * it is the root, and each settled worker's tool trace (`src/runtime/supervise/run-traces.ts`). The panel runs only\n * when the run has recorded a span.\n */\n readonly traces: TraceAnalysisStore\n /** Settled workers; each one's trace in `traces` is named by its `id`. */\n readonly workers: ReadonlyArray<{ readonly id: string; readonly label: string }>\n readonly bar?: ContinuationPolicy['best']\n readonly reference?: string\n /** The dollars this panel call may spend. */\n readonly usdCap: number\n readonly signal: AbortSignal\n}\n\n/** One answer the panel proposes for the note. */\nexport interface PanelFinding {\n readonly question: string\n /** The finding, stated as a claim about the run. */\n readonly claim: string\n /** Every `trace://` citation in the answer, and whether the trace store holds it. */\n readonly citations: ReadonlyArray<{ readonly uri: string; readonly resolved: boolean }>\n /** Whether an independent verifier, shown only the cited spans, agreed with the claim. */\n readonly verified: boolean\n /** The failed check items the finding explains, when it names any. */\n readonly items?: ReadonlyArray<string>\n}\n\nexport interface ContinuationPanelResult {\n readonly findings: ReadonlyArray<PanelFinding>\n /** Dollars spent; `null` when the provider reported no cost. Unknown is never zero. */\n readonly usd: number | null\n /** Provider receipts, recorded verbatim in `panel.jsonl`. */\n readonly receipts?: unknown\n}\n\n/** Ask the panel's questions over the run's own traces. */\nexport type ContinuationPanel = (input: ContinuationPanelInput) => Promise<ContinuationPanelResult>\n\n/** A play's own section for one note. Return `undefined` to add nothing this time. */\nexport type ContinuationAppend = (context: {\n readonly continuation: number\n readonly verdict?: CheckVerdict\n readonly reads: ReadonlyArray<CheckRead>\n readonly signal: AbortSignal\n}) => Promise<{ readonly heading: string; readonly text: string } | undefined>\n\n/** A finding that reached the note, with the continuation that admitted it. */\nexport interface AdmittedFinding extends PanelFinding {\n readonly admittedAt: number\n /** Set once every item the finding named passes. */\n readonly resolvedAt?: number\n}\n\n/** Findings reach the note only when every citation resolves, at least two distinct spans are\n * cited, and the independent verifier agreed. The best method in Who&When found the failing step\n * 14.2% of the time, so an unverified finding is noise with a citation. */\nexport function admitFinding(finding: PanelFinding): boolean {\n if (!finding.verified) return false\n if (finding.citations.length === 0) return false\n if (!finding.citations.every((citation) => citation.resolved)) return false\n return new Set(finding.citations.map((citation) => citation.uri)).size >= 2\n}\n\n/** About 1,500 tokens of findings. */\nconst FINDINGS_CHAR_CAP = 6_000\n\n/**\n * Rank the admitted findings by how many failed items they explain, drop repeats, and keep them\n * within the note's cap. Earlier findings stay as they were written (ACE: itemized additions keep\n * detail that repeated rewrites lose); a finding whose items all pass now is marked resolved.\n */\nexport function distillFindings(\n prior: ReadonlyArray<AdmittedFinding>,\n proposed: ReadonlyArray<PanelFinding>,\n failing: ReadonlySet<string>,\n continuation: number,\n): ReadonlyArray<AdmittedFinding> {\n const key = (claim: string) => claim.toLowerCase().replace(/\\s+/gu, ' ').trim()\n const known = new Set(prior.map((finding) => key(finding.claim)))\n const carried = prior.map((finding) =>\n finding.resolvedAt === undefined &&\n (finding.items?.length ?? 0) > 0 &&\n (finding.items ?? []).every((item) => !failing.has(item))\n ? { ...finding, resolvedAt: continuation }\n : finding,\n )\n const fresh = proposed\n .filter(admitFinding)\n .filter((finding) => {\n const k = key(finding.claim)\n if (known.has(k)) return false\n known.add(k)\n return true\n })\n .map((finding) => ({\n finding,\n links: (finding.items ?? []).filter((item) => failing.has(item)).length,\n }))\n .sort((a, b) => b.links - a.links)\n const out: AdmittedFinding[] = [...carried]\n let used = carried\n .filter((finding) => finding.resolvedAt === undefined)\n .reduce((sum, finding) => sum + finding.claim.length, 0)\n for (const { finding } of fresh) {\n if (used + finding.claim.length > FINDINGS_CHAR_CAP) break\n used += finding.claim.length\n out.push({ ...finding, admittedAt: continuation })\n }\n return out\n}\n\n/** Expand the profile's question templates over the failed items and the settled workers. */\nexport function expandQuestions(\n templates: ReadonlyArray<string>,\n failing: ReadonlyArray<string>,\n workers: ReadonlyArray<{ readonly id: string; readonly label: string }>,\n): ReadonlyArray<string> {\n const out: string[] = []\n for (const template of templates) {\n const hasItem = template.includes('{item}')\n const hasWorker = template.includes('{worker}')\n if (!hasItem && !hasWorker) {\n out.push(template)\n continue\n }\n const items = hasItem ? failing : ['']\n const each = hasWorker ? workers.map((worker) => `${worker.id} (${worker.label})`) : ['']\n for (const item of items) {\n for (const worker of each) {\n out.push(template.replaceAll('{item}', item).replaceAll('{worker}', worker))\n }\n }\n }\n return out\n}\n\n// ── The note ─────────────────────────────────────────────────────────────────────────────────────\n\n/** The facts one note is written from. */\nexport interface ContinuationNoteInput {\n readonly profile: ContinuationProfile\n /** 1-based. */\n readonly continuation: number\n /** The verdict this turn ended on; absent when no result has reached the check. */\n readonly verdict?: CheckVerdict\n /** The verdict the previous note reported, for what changed. */\n readonly previous?: CheckVerdict\n /** Check reads so far, the unavailable ones included. */\n readonly reads: number\n /** `verbatim` only when the policy and the check both allow the FAIL lines. */\n readonly failures: 'verbatim' | 'off'\n readonly findings?: ReadonlyArray<AdmittedFinding>\n readonly bar?: {\n readonly best?: ContinuationPolicy['best']\n readonly reference?: string\n }\n readonly appended?: ReadonlyArray<{ readonly heading: string; readonly text: string }>\n /** What the run owes, from the check's description. */\n readonly owed?: string\n readonly progress: DriverProgressMark\n /** Whether `read_continuation` is served to this manager. */\n readonly canReadMore: boolean\n /** Whether submit_result is served to this manager. Absent means unavailable. */\n readonly canSubmitResult?: boolean\n /** Whether the check's score comes from cases the director cannot see. */\n readonly sealed?: boolean\n}\n\n/** At most this many FAIL lines in the note; the rest through `read_continuation`. */\nexport const NOTE_FAILURE_LINES = 40\n\n/**\n * Write one continuation note, sections 1 to 8 of docs/38. Section 9, the run's state, is\n * `composeReentryTask`, which wraps this text. Pure: the same input writes the same note.\n */\nexport function composeContinuationNote(input: ContinuationNoteInput): string {\n const { profile, verdict } = input\n const items = verdict?.items ?? {}\n const total = Object.keys(items).length\n const failing = verdict === undefined ? [] : failedItems(verdict)\n const facts: Record<ContinuationFact, string> = {\n composite: verdict?.composite === undefined ? 'unknown' : format(verdict.composite),\n threshold: verdict?.threshold === undefined ? 'unknown' : format(verdict.threshold),\n failed:\n verdict === undefined || (total === 0 && (verdict.failures?.length ?? 0) === 0)\n ? 'unknown'\n : String(failing.length),\n total: total === 0 ? 'unknown' : String(total),\n reads: String(input.reads),\n owed: input.owed?.trim() || 'not described',\n settled: String(input.progress.settledCount),\n delivered: String(input.progress.deliveredCount ?? 0),\n continuation: String(input.continuation),\n }\n const fill = (text: string) =>\n text.replace(placeholder, (_, name: string) => facts[name as ContinuationFact] ?? `{${name}}`)\n // The opening states a failed verdict. When there is no verdict, or the check passes on a state\n // no result was submitted for, the fact replaces it: the profile cannot state a verdict that\n // does not exist.\n const sections: string[] = [\n verdict === undefined\n ? 'No check verdict is available yet.' +\n (input.canSubmitResult === true\n ? ' Submit a result through submit_result to request the check.'\n : '')\n : verdict.pass\n ? 'The check passes on the current state, but no result has been accepted.' +\n (input.canSubmitResult === true ? ' Call submit_result to request acceptance.' : '')\n : fill(profile.opening).trim(),\n ]\n const section = (heading: string, body: ReadonlyArray<string>) => {\n if (body.length === 0) return\n sections.push([...(heading.trim() === '' ? [] : [`## ${fill(heading)}`]), ...body].join('\\n'))\n }\n if (input.failures === 'verbatim' && verdict !== undefined) {\n const lines = verdict.failures ?? []\n const shown = lines.slice(0, NOTE_FAILURE_LINES)\n const more = lines.length - shown.length\n section(profile.headings.failures, [\n ...shown,\n ...(more > 0\n ? [\n input.canReadMore\n ? `${more} more failure lines: call read_continuation with continuation ${input.continuation}.`\n : `${more} more failure lines are not shown.`,\n ]\n : []),\n ])\n const passing = passedItems(verdict)\n section(profile.headings.protected, passing.length === 0 ? [] : [passing.join(', ')])\n if (input.previous !== undefined) {\n const before = new Set(failedItems(input.previous))\n const now = new Set(failing)\n const fixed = [...before].filter((item) => !now.has(item))\n const broke = [...now].filter((item) => !before.has(item))\n section(profile.headings.changed, [\n ...(fixed.length === 0 ? [] : [`Now passing: ${fixed.join(', ')}.`]),\n ...(broke.length === 0 ? [] : [`Newly failing: ${broke.join(', ')}.`]),\n ...(fixed.length === 0 && broke.length === 0\n ? ['No item changed since the last note.']\n : []),\n ...(input.previous.composite !== undefined && verdict.composite !== undefined\n ? [`Composite: ${format(input.previous.composite)} then ${format(verdict.composite)}.`]\n : []),\n ])\n }\n }\n if (input.findings !== undefined) {\n const open = input.findings.filter((finding) => finding.resolvedAt === undefined)\n const resolved = input.findings.filter((finding) => finding.resolvedAt === input.continuation)\n section(profile.headings.findings, [\n ...open.map(\n (finding) =>\n `- [hypothesis] ${finding.claim}` +\n (finding.items?.length ? ` (items: ${finding.items.join(', ')})` : '') +\n ` Evidence: ${finding.citations.map((citation) => citation.uri).join(', ')}`,\n ),\n ...resolved.map((finding) => `- [resolved] ${finding.claim}`),\n ])\n }\n if (input.bar !== undefined && verdict !== undefined) {\n const body: string[] = []\n if (profile.barRule?.trim()) body.push(fill(profile.barRule).trim())\n for (const [item, value] of Object.entries(items)) {\n const best = input.bar.best?.verdict.items?.[item]\n body.push(\n `- ${item}: ${value >= 1 ? 'passes' : `fails (${format(value)})`}` +\n (best === undefined\n ? ''\n : ` / ${input.bar.best?.label}: ${best >= 1 ? 'passes' : `fails (${format(best)})`}`),\n )\n }\n if (input.bar.best?.verdict.composite !== undefined) {\n body.push(\n `Best version ${input.bar.best.label}: composite ${format(input.bar.best.verdict.composite)}.`,\n )\n }\n if (input.bar.reference?.trim()) body.push(`Reference result: ${input.bar.reference.trim()}`)\n if (verdict.review?.trim()) body.push(`The check's review: ${verdict.review.trim()}`)\n section(profile.headings.bar, body)\n }\n section(profile.headings.plan, profile.plan.trim() === '' ? [] : [fill(profile.plan).trim()])\n section(profile.headings.rules, [\n ...(profile.rules.trim() === '' ? [] : [fill(profile.rules).trim()]),\n ...(input.sealed ? ['The score comes from cases you cannot see.'] : []),\n ])\n for (const appended of input.appended ?? []) {\n section(appended.heading, appended.text.trim() === '' ? [] : [appended.text.trim()])\n }\n return sections.join('\\n\\n')\n}\n\n// ── The record ───────────────────────────────────────────────────────────────────────────────────\n\n/** One continuation as the settle record carries it (`DriverContinuationRecord.continuations`). */\nexport interface ContinuationEntry {\n /** 1-based. */\n readonly continuation: number\n /** The driver attempt whose end this note answered. */\n readonly attempt: number\n /** sha256 of the note's text. */\n readonly noteDigest: string\n readonly profile: string\n readonly switches: {\n readonly failures: 'verbatim' | 'off'\n readonly panel: 'on' | 'off'\n readonly bar: 'on' | 'off'\n }\n /** The verdict the note reported: `null` when no result had reached the check. */\n readonly before: VerdictSummary | null\n /** The verdict at the director's next turn end: `null` when the run ended first. */\n readonly after: VerdictSummary | null\n /** The panel's part: questions asked, findings admitted, dollars (`null` = unknown). */\n readonly panel?: {\n readonly asked: number\n readonly proposed: number\n readonly admitted: number\n readonly usd: number | null\n /** Why the panel asked nothing this time, when it could not run. */\n readonly unavailable?: string\n }\n /** Sections a play appended. */\n readonly appended: number\n}\n\nexport interface VerdictSummary {\n readonly pass: boolean\n readonly composite?: number\n readonly failed?: number\n readonly total?: number\n}\n\nfunction summarizeVerdict(verdict: CheckVerdict | undefined): VerdictSummary | null {\n if (verdict === undefined) return null\n const total = Object.keys(verdict.items ?? {}).length\n return {\n pass: verdict.pass,\n ...(verdict.composite === undefined ? {} : { composite: verdict.composite }),\n ...(total === 0 ? {} : { failed: failedItems(verdict).length, total }),\n }\n}\n\nfunction noteDigest(note: string): string {\n return `sha256:${sha256(note)}`\n}\n\n/** A run directory's continuation files: the root's at `<runDir>/continuations/<n>/`, a nested\n * manager's at `<runDir>/continuations/managers/<owner>/<n>/`. */\nexport const CONTINUATIONS_DIR = 'continuations'\n\n/**\n * Write one continuation's files under `<dir>/<n>/`: `note.md`, `verdict.json`, and\n * `panel.jsonl` when the panel ran. The director reads them through `read_continuation`, because\n * its box cannot read the driver's run directory.\n */\nasync function writeContinuationFiles(\n dir: string,\n continuation: number,\n files: {\n readonly note: string\n readonly verdict?: CheckVerdict\n readonly panel?: ReadonlyArray<unknown>\n },\n): Promise<void> {\n const at = join(dir, String(continuation))\n await mkdir(at, { recursive: true })\n writeAtomicDurableFile(join(at, 'note.md'), `${files.note}\\n`)\n writeAtomicDurableFile(\n join(at, 'verdict.json'),\n `${JSON.stringify(files.verdict ?? null, null, 2)}\\n`,\n )\n if (files.panel !== undefined) {\n writeAtomicDurableFile(\n join(at, 'panel.jsonl'),\n files.panel.map((line) => JSON.stringify(line)).join('\\n') + (files.panel.length ? '\\n' : ''),\n )\n }\n}\n\n// ── The progress reading ─────────────────────────────────────────────────────────────────────────\n\n/** The best composite across `reads`, or `undefined` when no read scored. */\nexport function bestComposite(reads: ReadonlyArray<CheckRead>): number | undefined {\n let best: number | undefined\n for (const read of reads) {\n const value = read.verdict?.composite\n if (value !== undefined && (best === undefined || value > best)) best = value\n }\n return best\n}\n\n/** The readout a continuation is composed from. */\nexport interface ContinuationContext {\n /** The attempt that just completed, 1-based. */\n readonly attempt: number\n /** Continuations this run has already sent. */\n readonly continuations: number\n /** The mark read after the completed drive. */\n readonly progress: DriverProgressMark\n readonly budget: DriverBudgetReadout\n /** Re-entered drives in a row, this one included, that ended without progress. */\n readonly barrenReentries: number\n readonly signal: AbortSignal\n}\n\nfunction format(value: number): string {\n return Number.isInteger(value) ? String(value) : value.toFixed(3).replace(/0+$/u, '')\n}\n\n// ── One manager's continuations ──────────────────────────────────────────────────────────────────\n\n/** What a manager's continuation keeper reads from its run. */\ninterface ContinuationKeeperInput {\n readonly policy: ContinuationPolicy\n readonly task: unknown\n /** What the run owes, from the check's description. */\n readonly owed?: string\n /** The check's feedback mode: `pass-only` keeps the FAIL lines out of every note. */\n readonly feedback?: 'verbatim' | 'pass-only'\n readonly sealed?: boolean\n /** Every check read so far, oldest first. */\n readonly reads: () => ReadonlyArray<CheckRead>\n /** Settled workers, for the panel's `{worker}` questions. */\n readonly workers: () => ReadonlyArray<{ readonly id: string; readonly label: string }>\n /** Where each continuation's files go (`<dir>/<n>/`). Omit to keep them in memory only. */\n readonly dir?: string\n /** The run's own traces for the panel, read at each continuation; `undefined` when none yet. */\n readonly traces?: () => Promise<TraceAnalysisStore | undefined>\n /** Whether `read_continuation` is served to this manager. */\n readonly canReadMore: boolean\n /** Whether submit_result is served to this manager. Absent means unavailable. */\n readonly canSubmitResult?: boolean\n}\n\n/** One manager's continuation state: the notes it was sent and the panel's running ledger. */\nexport interface ContinuationKeeper {\n /** Write the next note. The driver loop calls it only when the check is unmet. */\n compose(context: ContinuationContext): Promise<string>\n /** `read_continuation`: the full record of continuation `n`, or the latest. */\n read(continuation: number | undefined): unknown\n /** The settle record's `continuations`, with the last note's `after` read from the final check. */\n entries(): ReadonlyArray<ContinuationEntry>\n}\n\n/** Build the continuation state for one manager with a check. */\nexport function createContinuationKeeper(input: ContinuationKeeperInput): ContinuationKeeper {\n const { policy } = input\n const failures: 'verbatim' | 'off' = input.feedback === 'pass-only' ? 'off' : policy.failures\n const entries: ContinuationEntry[] = []\n const notes: Array<{\n readonly note: string\n readonly verdict?: CheckVerdict\n readonly panel?: ReadonlyArray<unknown>\n /** The check read the note answered, for the `after` reading. */\n readonly read: number\n }> = []\n let findings: ReadonlyArray<AdmittedFinding> = []\n let panelUsd = 0\n let panelUsdKnown = true\n\n const latestVerdict = (): { verdict?: CheckVerdict; read: number } => {\n const reads = input.reads()\n for (let i = reads.length - 1; i >= 0; i -= 1) {\n const read = reads[i]\n if (read?.verdict !== undefined) return { verdict: read.verdict, read: read.read }\n }\n return { read: 0 }\n }\n\n const closePrevious = (): void => {\n const last = entries.at(-1)\n const lastNote = notes.at(-1)\n if (last === undefined || lastNote === undefined) return\n const latest = latestVerdict()\n entries[entries.length - 1] = {\n ...last,\n after: latest.read > lastNote.read ? summarizeVerdict(latest.verdict) : null,\n }\n }\n\n return {\n async compose(context) {\n closePrevious()\n const continuation = entries.length + 1\n const { verdict, read } = latestVerdict()\n const failing = verdict === undefined ? [] : failedItems(verdict)\n let panelRecord: ContinuationEntry['panel'] | undefined\n let panelLines: unknown[] | undefined\n if (policy.panel === 'on' && policy.runPanel !== undefined && policy.panelUsd !== undefined) {\n const workers = input.workers()\n const questions = expandQuestions(policy.profile.questions ?? [], failing, workers)\n const left = policy.panelUsd.perRun - panelUsd\n const usdCap = Math.min(policy.panelUsd.perContinuation, left)\n // An unknown cost closes the panel for the rest of the run: its cap can no longer be\n // proven, and an unmeasured spend is never read as zero.\n const asking = questions.length > 0 && usdCap > 0 && panelUsdKnown\n let traces: TraceAnalysisStore | undefined\n let unavailable: string | undefined\n if (asking) {\n try {\n traces = await input.traces?.()\n if (traces === undefined) unavailable = 'the run has recorded no trace yet'\n } catch (error) {\n // A trace that cannot be read is the evidence's failure, not the director's: the note\n // goes out without findings, and the record says why.\n unavailable = `the run's traces could not be read: ${error instanceof Error ? error.message : String(error)}`\n }\n }\n if (asking && traces !== undefined) {\n const result = await policy.runPanel({\n continuation,\n task: input.task,\n ...(verdict === undefined ? {} : { verdict }),\n reads: input.reads(),\n questions,\n traces,\n workers,\n ...(policy.best === undefined ? {} : { bar: policy.best }),\n ...(policy.reference === undefined ? {} : { reference: policy.reference }),\n usdCap,\n signal: context.signal,\n })\n if (result.usd === null) panelUsdKnown = false\n else panelUsd += result.usd\n findings = distillFindings(findings, result.findings, new Set(failing), continuation)\n panelRecord = {\n asked: questions.length,\n proposed: result.findings.length,\n admitted: findings.filter((finding) => finding.admittedAt === continuation).length,\n usd: result.usd,\n }\n panelLines = [\n ...result.findings.map((finding) => ({\n kind: 'finding',\n admitted: admitFinding(finding),\n ...finding,\n })),\n ...(result.receipts === undefined\n ? []\n : [{ kind: 'receipts', receipts: result.receipts }]),\n ]\n } else {\n panelRecord = {\n asked: 0,\n proposed: 0,\n admitted: 0,\n usd: 0,\n ...(unavailable === undefined ? {} : { unavailable }),\n }\n }\n }\n const appended = policy.append\n ? await policy.append({\n continuation,\n ...(verdict === undefined ? {} : { verdict }),\n reads: input.reads(),\n signal: context.signal,\n })\n : undefined\n const note = composeContinuationNote({\n profile: policy.profile,\n continuation,\n ...(verdict === undefined ? {} : { verdict }),\n ...(notes.at(-1)?.verdict === undefined ? {} : { previous: notes.at(-1)?.verdict }),\n reads: input.reads().length,\n failures,\n ...(policy.panel === 'on' ? { findings } : {}),\n ...(policy.bar === 'on'\n ? {\n bar: {\n ...(policy.best === undefined ? {} : { best: policy.best }),\n ...(policy.reference === undefined ? {} : { reference: policy.reference }),\n },\n }\n : {}),\n ...(appended === undefined ? {} : { appended: [appended] }),\n ...(input.owed === undefined ? {} : { owed: input.owed }),\n progress: context.progress,\n canReadMore: input.canReadMore,\n canSubmitResult: input.canSubmitResult === true,\n ...(input.sealed === true ? { sealed: true } : {}),\n })\n notes.push({\n note,\n ...(verdict === undefined ? {} : { verdict }),\n ...(panelLines === undefined ? {} : { panel: panelLines }),\n read,\n })\n entries.push({\n continuation,\n attempt: context.attempt,\n noteDigest: noteDigest(note),\n profile: policy.profile.id,\n switches: { failures, panel: policy.panel, bar: policy.bar },\n before: summarizeVerdict(verdict),\n after: null,\n ...(panelRecord === undefined ? {} : { panel: panelRecord }),\n appended: appended === undefined ? 0 : 1,\n })\n if (input.dir !== undefined) {\n await writeContinuationFiles(input.dir, continuation, {\n note,\n ...(verdict === undefined ? {} : { verdict }),\n ...(panelLines === undefined ? {} : { panel: panelLines }),\n })\n }\n return note\n },\n read(continuation) {\n const index = continuation === undefined ? notes.length - 1 : continuation - 1\n const entry = notes[index]\n if (entry === undefined) {\n return {\n found: false,\n reason:\n notes.length === 0\n ? 'no continuation has been sent in this run'\n : `continuations run from 1 to ${notes.length}`,\n }\n }\n return {\n found: true,\n continuation: index + 1,\n note: entry.note,\n // Under `pass-only` the check's lines stay hidden here too.\n verdict:\n failures === 'off' && entry.verdict !== undefined\n ? { pass: entry.verdict.pass }\n : (entry.verdict ?? null),\n findings: findings.filter((finding) => finding.admittedAt <= index + 1),\n }\n },\n entries() {\n closePrevious()\n return entries.map((entry) => ({ ...entry }))\n },\n }\n}\n"],"mappings":";;;;;;AAAA,SAAgB,eAAe,OAAiC;CAC9D,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;AAC3D;;;;;;;;;;ACiBA,SAAgB,eAAe,SAAgC;CAC7D,IAAI,YAAY,MAAM,OAAO,EAAE,MAAM,KAAK;CAC1C,IAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,MAAM,QAAQ,OAAO,GAC1E,OAAO,EAAE,MAAM,MAAM;CAEvB,MAAM,MAAM;CACZ,MAAM,QACJ,OAAO,IAAI,UAAU,YAAY,IAAI,UAAU,QAAQ,CAAC,MAAM,QAAQ,IAAI,KAAK,IAC3E,OAAO,YACL,OAAO,QAAQ,IAAI,KAAgC,CAAC,CAAC,QAClD,UACC,OAAO,MAAM,OAAO,YAAY,OAAO,SAAS,MAAM,EAAE,CAC5D,CACF,IACA,KAAA;CACN,MAAM,WAAW,MAAM,QAAQ,IAAI,QAAQ,IACvC,IAAI,SAAS,QAAQ,SAAyB,OAAO,SAAS,YAAY,KAAK,KAAK,MAAM,EAAE,IAC5F,KAAA;CACJ,OAAO,OAAO,OAAO;EACnB,MAAM,IAAI,SAAS;EACnB,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,OAAO,OAAO,KAAK,EAAE;EAC7D,GAAI,eAAe,IAAI,SAAS,IAAI,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;EACpE,GAAI,eAAe,IAAI,SAAS,IAAI,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;EACpE,GAAI,a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AS,MAAM,YAAY,KAAA,IACpC,EAAE,MAAM,MAAM,QAAQ,KAAK,IAC1B,MAAM,WAAW;IACxB,UAAU,SAAS,QAAQ,YAAY,QAAQ,cAAc,QAAQ,CAAC;GACxE;EACF;EACA,UAAU;GACR,cAAc;GACd,OAAO,QAAQ,KAAK,WAAW,EAAE,GAAG,MAAM,EAAE;EAC9C;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"continuation-CL4B1Y4M.js","names":[],"sources":["../src/finite-number.ts","../src/runtime/supervise/continuation.ts"],"sourcesContent":["export function isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value)\n}\n","/**\n * One check ({@link CheckVerdict}; {@link CheckUnavailableError} pauses), one\n * {@link ContinuationPolicy} (`maxBarren`, an optional deadline, no re-prompt default), and one\n * note ({@link composeContinuationNote} owns the facts, {@link ContinuationProfile} owns the\n * words, a play may only append).\n */\n\nimport { mkdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { TraceAnalysisStore } from '@tangle-network/agent-eval'\nimport { sha256 } from '../../content-digest'\nimport { ValidationError } from '../../errors'\nimport { isFiniteNumber } from '../../finite-number'\nimport type { CheckVerdict } from './completion-gate'\nimport type { DriverBudgetReadout, DriverProgressMark } from './driver-retry'\nimport { writeAtomicDurableFile } from './durable-file'\n\n/** Read a check function's return value into a verdict. Anything but `true` or a passing verdict\n * is a failure: a check fails closed. */\nexport function checkVerdictOf(outcome: unknown): CheckVerdict {\n if (outcome === true) return { pass: true }\n if (typeof outcome !== 'object' || outcome === null || Array.isArray(outcome)) {\n return { pass: false }\n }\n const raw = outcome as Record<string, unknown>\n const items =\n typeof raw.items === 'object' && raw.items !== null && !Array.isArray(raw.items)\n ? Object.fromEntries(\n Object.entries(raw.items as Record<string, unknown>).filter(\n (entry): entry is [string, number] =>\n typeof entry[1] === 'number' && Number.isFinite(entry[1]),\n ),\n )\n : undefined\n const failures = Array.isArray(raw.failures)\n ? raw.failures.filter((line): line is string => typeof line === 'string' && line.trim() !== '')\n : undefined\n return Object.freeze({\n pass: raw.pass === true,\n ...(items === undefined ? {} : { items: Object.freeze(items) }),\n ...(isFiniteNumber(raw.composite) ? { composite: raw.composite } : {}),\n ...(isFiniteNumber(raw.threshold) ? { threshold: raw.threshold } : {}),\n ...(failures === undefined ? {} : { failures: Object.freeze(failures) }),\n ...(typeof raw.review === 'string' && raw.review.trim() !== ''\n ? { review: raw.review.trim() }\n : {}),\n })\n}\n\n/** Items that fail in `verdict`: every item below 1, or the named items of its FAIL lines. */\nexport function failedItems(verdict: CheckVerdict): ReadonlyArray<string> {\n if (verdict.items !== undefined) {\n return Object.entries(verdict.items)\n .filter(([, value]) => value < 1)\n .map(([name]) => name)\n }\n return (verdict.failures ?? []).map((line) => line.slice('FAIL '.length).split(/[\\s:]/u)[0] ?? '')\n}\n\n/** Items that pass in `verdict`. */\nexport function passedItems(verdict: CheckVerdict): ReadonlyArray<string> {\n return Object.entries(verdict.items ?? {})\n .filter(([, value]) => value >= 1)\n .map(([name]) => name)\n}\n\n/** One time the check ran inside the run, whatever started it. */\nexport interface CheckRead {\n /** 1-based count of check reads in this manager, the unavailable ones included. */\n readonly read: number\n /** The driver attempt the read belongs to. */\n readonly attempt: number\n /** Epoch ms. */\n readonly at: number\n /** `submit`: a `submit_result` call. `turn-end`: the turn ended with no accepted result. */\n readonly source: 'submit' | 'turn-end'\n /** Absent when the check could not run. */\n readonly verdict?: CheckVerdict\n /** Why the check could not run. */\n readonly unavailable?: string\n}\n\n// ── The resend rule ──────────────────────────────────────────────────────────────────────────────\n\n/**\n * How a manager with a completion check is sent back when its turn ends unmet.\n *\n * Required for an external manager with a check: Runtime supplies no default, because a retry\n * default in source is a research decision the record must make. There is no re-prompt count.\n * The loop re-enters until the check passes or a bound ends it: cancellation, the budget, or\n * this deadline when one is set. After `maxBarren` turns in a row without progress, each further continuation\n * waits a barren pause first (5 minutes, doubling to 60) and is journaled `barren-pause`; a\n * barren streak never ends the run. A tool `report_blocked` shows\n * really failed is recorded and the loop goes on: a blocked tool is not a terminal condition.\n * Progress means the check's best composite rose, an accepted result, or a worker that delivered.\n */\nexport interface ContinuationPolicy {\n /** No re-entry starts at or after this instant: epoch ms, or an ISO 8601 time. Absent: no clock\n * ends the run; it ends when its check passes, on cancellation, or on a spent budget. */\n readonly deadline?: number | string\n /** Re-entered turns in a row that may end without progress before each further continuation\n * waits a barren pause. Minimum 1. The evidence for 2: repair loses most of its effect within\n * two or three attempts, and a fresh start at the same budget scored higher (Debugging Decay\n * Index). */\n readonly maxBarren: number\n /** Every instruction word of the note. */\n readonly profile: ContinuationProfile\n /** `verbatim` sends the check's FAIL lines, the protected items, and what changed. A check with\n * `feedback: 'pass-only'` overrides this to `off`. */\n readonly failures: 'verbatim' | 'off'\n /** `on` runs the question panel at each continuation and puts its admitted findings in the note.\n * Requires `runPanel`. */\n readonly panel: 'on' | 'off'\n /** `on` states the bar: every check item with its state, the best version's verdict and the\n * gap, the reference result, and the check's review. */\n readonly bar: 'on' | 'off'\n /** The play's registered reference result, for the bar. */\n readonly reference?: string\n /** The best version's verdict on the same check, for the bar. The version loop sets it. */\n readonly best?: { readonly label: string; readonly verdict: CheckVerdict }\n /** The panel's dollar caps. Required with `panel: 'on'`. */\n readonly panelUsd?: { readonly perContinuation: number; readonly perRun: number }\n /** The question panel. Required with `panel: 'on'`. */\n readonly runPanel?: ContinuationPanel\n /** A play's own section, appended after Runtime's sections. It cannot remove or rewrite one. */\n readonly append?: ContinuationAppend\n /**\n * What a re-entered manager's harness session is. `native` (the default) sends the next turn\n * into the same harness session wherever the backend proves it, with the unmet items and what\n * changed. `fresh` starts a new harness session on every re-entry (a continuation, a wake, a\n * failure retry, a pause) whose only input is the full re-entry task: the original task, the\n * check's description and the coordinator's run state. The environment and its files are kept\n * while the provider holds them; only the conversation is new, so whatever the next turn needs\n * must be in the journal, the workspace or Knowledge, never in an earlier turn.\n *\n * Runtime's own drive harnesses (bridge and provider) honor it; a caller's `driveHarness`\n * receives it as `session` and must start a new session on each drive that carries `reentry`.\n */\n readonly session?: 'native' | 'fresh'\n}\n\n/** Resolve and check a policy before any compute. Returns the deadline in epoch ms, or undefined\n * when the policy sets none. */\nexport function admitContinuationPolicy(\n policy: ContinuationPolicy,\n context: string,\n): number | undefined {\n if (typeof policy !== 'object' || policy === null) {\n throw new ValidationError(`${context}: continuation must be an object`)\n }\n const deadlineMs =\n typeof policy.deadline === 'string' ? Date.parse(policy.deadline) : policy.deadline\n if (\n deadlineMs !== undefined &&\n (typeof deadlineMs !== 'number' || !Number.isFinite(deadlineMs) || deadlineMs <= 0)\n ) {\n throw new ValidationError(\n `${context}: continuation.deadline, when set, must be a finite time (epoch ms or ISO 8601)`,\n )\n }\n if (!Number.isInteger(policy.maxBarren) || policy.maxBarren < 1) {\n throw new ValidationError(`${context}: continuation.maxBarren must be an integer >= 1`)\n }\n if (policy.failures !== 'verbatim' && policy.failures !== 'off') {\n throw new ValidationError(`${context}: continuation.failures must be 'verbatim' or 'off'`)\n }\n if (policy.panel !== 'on' && policy.panel !== 'off') {\n throw new ValidationError(`${context}: continuation.panel must be 'on' or 'off'`)\n }\n if (policy.bar !== 'on' && policy.bar !== 'off') {\n throw new ValidationError(`${context}: continuation.bar must be 'on' or 'off'`)\n }\n if (policy.panel === 'on') {\n if (typeof policy.runPanel !== 'function') {\n throw new ValidationError(`${context}: continuation.panel 'on' needs runPanel`)\n }\n const usd = policy.panelUsd\n if (\n usd === undefined ||\n !isFiniteNumber(usd.perContinuation) ||\n !isFiniteNumber(usd.perRun) ||\n usd.perContinuation <= 0 ||\n usd.perRun < usd.perContinuation\n ) {\n throw new ValidationError(\n `${context}: continuation.panel 'on' needs panelUsd with 0 < perContinuation <= perRun`,\n )\n }\n }\n if (policy.append !== undefined && typeof policy.append !== 'function') {\n throw new ValidationError(`${context}: continuation.append must be a function`)\n }\n if (policy.session !== undefined && policy.session !== 'native' && policy.session !== 'fresh') {\n throw new ValidationError(`${context}: continuation.session must be 'native' or 'fresh'`)\n }\n if (policy.reference !== undefined && typeof policy.reference !== 'string')\n throw new ValidationError(`${context}: continuation.reference must be a string`)\n admitContinuationProfile(policy.profile, context)\n return deadlineMs\n}\n\n// ── The profile ──────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Every instruction word of the note. Runtime supplies the facts and their order; this data\n * supplies the words, so the note can be improved (by a person, reflection, or GEPA) without a code\n * change. Templates may name the facts in `CONTINUATION_FACTS` as `{name}`.\n */\nexport interface ContinuationProfile {\n /** Recorded with every note, so each continuation names the words it carried. */\n readonly id: string\n /** Section 1, the verdict. The first line should state the failure as a fact. */\n readonly opening: string\n /** Section 7: what to do before the next submit. */\n readonly plan: string\n /** Section 8: what the harness enforces, and the honest exit. */\n readonly rules: string\n /** Section headings; an empty heading prints the section without one. */\n readonly headings: {\n readonly failures: string\n readonly protected: string\n readonly changed: string\n readonly findings: string\n readonly bar: string\n readonly plan: string\n readonly rules: string\n }\n /** The bar's standing instruction, printed under its heading. */\n readonly barRule?: string\n /** The panel's question templates. `{item}` expands over failed items and `{worker}` over\n * settled workers; a template with neither is asked once. */\n readonly questions?: ReadonlyArray<string>\n /** The panel's model, when the profile chooses one. */\n readonly panelModel?: string\n /** What a new version's director reads about the best version's review, for the version\n * chain's `'review-of-best'`. It may name `{version}`, `{path}` and `{score}`. */\n readonly review?: string\n}\n\n/** The facts a profile template may name. */\nexport const CONTINUATION_FACTS = [\n 'composite',\n 'threshold',\n 'failed',\n 'total',\n 'reads',\n 'owed',\n 'settled',\n 'delivered',\n 'continuation',\n] as const\n\ntype ContinuationFact = (typeof CONTINUATION_FACTS)[number]\n\nconst factNames: ReadonlySet<string> = new Set(CONTINUATION_FACTS)\nconst placeholder = /\\{([a-zA-Z]+)\\}/gu\n\nfunction admitContinuationProfile(profile: ContinuationProfile, context: string): void {\n if (typeof profile !== 'object' || profile === null) {\n throw new ValidationError(`${context}: continuation.profile must be an object`)\n }\n if (typeof profile.id !== 'string' || profile.id.trim() === '') {\n throw new ValidationError(`${context}: continuation.profile.id must be non-empty`)\n }\n const texts: Array<[string, unknown]> = [\n ['opening', profile.opening],\n ['plan', profile.plan],\n ['rules', profile.rules],\n ...Object.entries(profile.headings ?? {}).map(([key, value]): [string, unknown] => [\n `headings.${key}`,\n value,\n ]),\n ...(profile.barRule === undefined ? [] : [['barRule', profile.barRule] as [string, unknown]]),\n ]\n for (const key of ['failures', 'protected', 'changed', 'findings', 'bar', 'plan', 'rules']) {\n if (typeof (profile.headings as Record<string, unknown> | undefined)?.[key] !== 'string') {\n throw new ValidationError(`${context}: continuation.profile.headings.${key} must be a string`)\n }\n }\n for (const [key, text] of texts) {\n if (typeof text !== 'string') {\n throw new ValidationError(`${context}: continuation.profile.${key} must be a string`)\n }\n for (const match of text.matchAll(placeholder)) {\n if (!factNames.has(match[1] ?? '')) {\n throw new ValidationError(\n `${context}: continuation.profile.${key} names {${match[1]}}, which is not a fact Runtime supplies (${CONTINUATION_FACTS.join(', ')})`,\n )\n }\n }\n }\n if (profile.review !== undefined) {\n if (typeof profile.review !== 'string' || profile.review.trim() === '') {\n throw new ValidationError(`${context}: continuation.profile.review must be non-empty`)\n }\n for (const match of profile.review.matchAll(placeholder)) {\n if (!['version', 'path', 'score'].includes(match[1] ?? '')) {\n throw new ValidationError(\n `${context}: continuation.profile.review names {${match[1]}}; it may name {version}, {path} and {score}`,\n )\n }\n }\n }\n if (profile.opening.trim() === '') {\n throw new ValidationError(`${context}: continuation.profile.opening must be non-empty`)\n }\n if (profile.panelModel !== undefined && typeof profile.panelModel !== 'string')\n throw new ValidationError(`${context}: continuation.profile.panelModel must be a string`)\n if (profile.questions !== undefined && !Array.isArray(profile.questions))\n throw new ValidationError(`${context}: continuation.profile.questions must be an array`)\n for (const [index, question] of (profile.questions ?? []).entries()) {\n if (typeof question !== 'string' || question.trim() === '') {\n throw new ValidationError(\n `${context}: continuation.profile.questions[${index}] must be a non-empty string`,\n )\n }\n }\n}\n\n// ── The panel ────────────────────────────────────────────────────────────────────────────────────\n\n/** What the question panel reads for one continuation. */\nexport interface ContinuationPanelInput {\n /** 1-based continuation number. */\n readonly continuation: number\n readonly task: unknown\n /** The check's verdict this note reports; absent when no result reached the check. */\n readonly verdict?: CheckVerdict\n /** Every check read so far, oldest first. */\n readonly reads: ReadonlyArray<CheckRead>\n /** The expanded questions, one per atomic question. */\n readonly questions: ReadonlyArray<string>\n /**\n * The run's own traces, one per agent and named by its node id: the manager's root stream, when\n * it is the root, and each settled worker's tool trace (`src/runtime/supervise/run-traces.ts`). The panel runs only\n * when the run has recorded a span.\n */\n readonly traces: TraceAnalysisStore\n /** Settled workers; each one's trace in `traces` is named by its `id`. */\n readonly workers: ReadonlyArray<{ readonly id: string; readonly label: string }>\n readonly bar?: ContinuationPolicy['best']\n readonly reference?: string\n /** The dollars this panel call may spend. */\n readonly usdCap: number\n readonly signal: AbortSignal\n}\n\n/** One answer the panel proposes for the note. */\nexport interface PanelFinding {\n readonly question: string\n /** The finding, stated as a claim about the run. */\n readonly claim: string\n /** Every `trace://` citation in the answer, and whether the trace store holds it. */\n readonly citations: ReadonlyArray<{ readonly uri: string; readonly resolved: boolean }>\n /** Whether an independent verifier, shown only the cited spans, agreed with the claim. */\n readonly verified: boolean\n /** The failed check items the finding explains, when it names any. */\n readonly items?: ReadonlyArray<string>\n}\n\nexport interface ContinuationPanelResult {\n readonly findings: ReadonlyArray<PanelFinding>\n /** Dollars spent; `null` when the provider reported no cost. Unknown is never zero. */\n readonly usd: number | null\n /** Provider receipts, recorded verbatim in `panel.jsonl`. */\n readonly receipts?: unknown\n}\n\n/** Ask the panel's questions over the run's own traces. */\nexport type ContinuationPanel = (input: ContinuationPanelInput) => Promise<ContinuationPanelResult>\n\n/** A play's own section for one note. Return `undefined` to add nothing this time. */\nexport type ContinuationAppend = (context: {\n readonly continuation: number\n readonly verdict?: CheckVerdict\n readonly reads: ReadonlyArray<CheckRead>\n readonly signal: AbortSignal\n}) => Promise<{ readonly heading: string; readonly text: string } | undefined>\n\n/** A finding that reached the note, with the continuation that admitted it. */\nexport interface AdmittedFinding extends PanelFinding {\n readonly admittedAt: number\n /** Set once every item the finding named passes. */\n readonly resolvedAt?: number\n}\n\n/** Findings reach the note only when every citation resolves, at least two distinct spans are\n * cited, and the independent verifier agreed. The best method in Who&When found the failing step\n * 14.2% of the time, so an unverified finding is noise with a citation. */\nexport function admitFinding(finding: PanelFinding): boolean {\n if (!finding.verified) return false\n if (finding.citations.length === 0) return false\n if (!finding.citations.every((citation) => citation.resolved)) return false\n return new Set(finding.citations.map((citation) => citation.uri)).size >= 2\n}\n\n/** About 1,500 tokens of findings. */\nconst FINDINGS_CHAR_CAP = 6_000\n\n/**\n * Rank the admitted findings by how many failed items they explain, drop repeats, and keep them\n * within the note's cap. Earlier findings stay as they were written (ACE: itemized additions keep\n * detail that repeated rewrites lose); a finding whose items all pass now is marked resolved.\n */\nexport function distillFindings(\n prior: ReadonlyArray<AdmittedFinding>,\n proposed: ReadonlyArray<PanelFinding>,\n failing: ReadonlySet<string>,\n continuation: number,\n): ReadonlyArray<AdmittedFinding> {\n const key = (claim: string) => claim.toLowerCase().replace(/\\s+/gu, ' ').trim()\n const known = new Set(prior.map((finding) => key(finding.claim)))\n const carried = prior.map((finding) =>\n finding.resolvedAt === undefined &&\n (finding.items?.length ?? 0) > 0 &&\n (finding.items ?? []).every((item) => !failing.has(item))\n ? { ...finding, resolvedAt: continuation }\n : finding,\n )\n const fresh = proposed\n .filter(admitFinding)\n .filter((finding) => {\n const k = key(finding.claim)\n if (known.has(k)) return false\n known.add(k)\n return true\n })\n .map((finding) => ({\n finding,\n links: (finding.items ?? []).filter((item) => failing.has(item)).length,\n }))\n .sort((a, b) => b.links - a.links)\n const out: AdmittedFinding[] = [...carried]\n let used = carried\n .filter((finding) => finding.resolvedAt === undefined)\n .reduce((sum, finding) => sum + finding.claim.length, 0)\n for (const { finding } of fresh) {\n if (used + finding.claim.length > FINDINGS_CHAR_CAP) break\n used += finding.claim.length\n out.push({ ...finding, admittedAt: continuation })\n }\n return out\n}\n\n/** Expand the profile's question templates over the failed items and the settled workers. */\nexport function expandQuestions(\n templates: ReadonlyArray<string>,\n failing: ReadonlyArray<string>,\n workers: ReadonlyArray<{ readonly id: string; readonly label: string }>,\n): ReadonlyArray<string> {\n const out: string[] = []\n for (const template of templates) {\n const hasItem = template.includes('{item}')\n const hasWorker = template.includes('{worker}')\n if (!hasItem && !hasWorker) {\n out.push(template)\n continue\n }\n const items = hasItem ? failing : ['']\n const each = hasWorker ? workers.map((worker) => `${worker.id} (${worker.label})`) : ['']\n for (const item of items) {\n for (const worker of each) {\n out.push(template.replaceAll('{item}', item).replaceAll('{worker}', worker))\n }\n }\n }\n return out\n}\n\n// ── The note ─────────────────────────────────────────────────────────────────────────────────────\n\n/** The facts one note is written from. */\nexport interface ContinuationNoteInput {\n readonly profile: ContinuationProfile\n /** 1-based. */\n readonly continuation: number\n /** The verdict this turn ended on; absent when no result has reached the check. */\n readonly verdict?: CheckVerdict\n /** The verdict the previous note reported, for what changed. */\n readonly previous?: CheckVerdict\n /** Check reads so far, the unavailable ones included. */\n readonly reads: number\n /** `verbatim` only when the policy and the check both allow the FAIL lines. */\n readonly failures: 'verbatim' | 'off'\n readonly findings?: ReadonlyArray<AdmittedFinding>\n readonly bar?: {\n readonly best?: ContinuationPolicy['best']\n readonly reference?: string\n }\n readonly appended?: ReadonlyArray<{ readonly heading: string; readonly text: string }>\n /** What the run owes, from the check's description. */\n readonly owed?: string\n readonly progress: DriverProgressMark\n /** Whether `read_continuation` is served to this manager. */\n readonly canReadMore: boolean\n /** Whether submit_result is served to this manager. Absent means unavailable. */\n readonly canSubmitResult?: boolean\n /** Whether the check's score comes from cases the director cannot see. */\n readonly sealed?: boolean\n}\n\n/** At most this many FAIL lines in the note; the rest through `read_continuation`. */\nexport const NOTE_FAILURE_LINES = 40\n\n/**\n * Write one continuation note, sections 1 to 8 of docs/38. Section 9, the run's state, is\n * `composeReentryTask`, which wraps this text. Pure: the same input writes the same note.\n */\nexport function composeContinuationNote(input: ContinuationNoteInput): string {\n const { profile, verdict } = input\n const items = verdict?.items ?? {}\n const total = Object.keys(items).length\n const failing = verdict === undefined ? [] : failedItems(verdict)\n const facts: Record<ContinuationFact, string> = {\n composite: verdict?.composite === undefined ? 'unknown' : format(verdict.composite),\n threshold: verdict?.threshold === undefined ? 'unknown' : format(verdict.threshold),\n failed:\n verdict === undefined || (total === 0 && (verdict.failures?.length ?? 0) === 0)\n ? 'unknown'\n : String(failing.length),\n total: total === 0 ? 'unknown' : String(total),\n reads: String(input.reads),\n owed: input.owed?.trim() || 'not described',\n settled: String(input.progress.settledCount),\n delivered: String(input.progress.deliveredCount ?? 0),\n continuation: String(input.continuation),\n }\n const fill = (text: string) =>\n text.replace(placeholder, (_, name: string) => facts[name as ContinuationFact] ?? `{${name}}`)\n // The opening states a failed verdict. When there is no verdict, or the check passes on a state\n // no result was submitted for, the fact replaces it: the profile cannot state a verdict that\n // does not exist.\n const sections: string[] = [\n verdict === undefined\n ? 'No check verdict is available yet.' +\n (input.canSubmitResult === true\n ? ' Submit a result through submit_result to request the check.'\n : '')\n : verdict.pass\n ? 'The check passes on the current state, but no result has been accepted.' +\n (input.canSubmitResult === true ? ' Call submit_result to request acceptance.' : '')\n : fill(profile.opening).trim(),\n ]\n const section = (heading: string, body: ReadonlyArray<string>) => {\n if (body.length === 0) return\n sections.push([...(heading.trim() === '' ? [] : [`## ${fill(heading)}`]), ...body].join('\\n'))\n }\n if (input.failures === 'verbatim' && verdict !== undefined) {\n const lines = verdict.failures ?? []\n const shown = lines.slice(0, NOTE_FAILURE_LINES)\n const more = lines.length - shown.length\n section(profile.headings.failures, [\n ...shown,\n ...(more > 0\n ? [\n input.canReadMore\n ? `${more} more failure lines: call read_continuation with continuation ${input.continuation}.`\n : `${more} more failure lines are not shown.`,\n ]\n : []),\n ])\n const passing = passedItems(verdict)\n section(profile.headings.protected, passing.length === 0 ? [] : [passing.join(', ')])\n if (input.previous !== undefined) {\n const before = new Set(failedItems(input.previous))\n const now = new Set(failing)\n const fixed = [...before].filter((item) => !now.has(item))\n const broke = [...now].filter((item) => !before.has(item))\n section(profile.headings.changed, [\n ...(fixed.length === 0 ? [] : [`Now passing: ${fixed.join(', ')}.`]),\n ...(broke.length === 0 ? [] : [`Newly failing: ${broke.join(', ')}.`]),\n ...(fixed.length === 0 && broke.length === 0\n ? ['No item changed since the last note.']\n : []),\n ...(input.previous.composite !== undefined && verdict.composite !== undefined\n ? [`Composite: ${format(input.previous.composite)} then ${format(verdict.composite)}.`]\n : []),\n ])\n }\n }\n if (input.findings !== undefined) {\n const open = input.findings.filter((finding) => finding.resolvedAt === undefined)\n const resolved = input.findings.filter((finding) => finding.resolvedAt === input.continuation)\n section(profile.headings.findings, [\n ...open.map(\n (finding) =>\n `- [hypothesis] ${finding.claim}` +\n (finding.items?.length ? ` (items: ${finding.items.join(', ')})` : '') +\n ` Evidence: ${finding.citations.map((citation) => citation.uri).join(', ')}`,\n ),\n ...resolved.map((finding) => `- [resolved] ${finding.claim}`),\n ])\n }\n if (input.bar !== undefined && verdict !== undefined) {\n const body: string[] = []\n if (profile.barRule?.trim()) body.push(fill(profile.barRule).trim())\n for (const [item, value] of Object.entries(items)) {\n const best = input.bar.best?.verdict.items?.[item]\n body.push(\n `- ${item}: ${value >= 1 ? 'passes' : `fails (${format(value)})`}` +\n (best === undefined\n ? ''\n : ` / ${input.bar.best?.label}: ${best >= 1 ? 'passes' : `fails (${format(best)})`}`),\n )\n }\n if (input.bar.best?.verdict.composite !== undefined) {\n body.push(\n `Best version ${input.bar.best.label}: composite ${format(input.bar.best.verdict.composite)}.`,\n )\n }\n if (input.bar.reference?.trim()) body.push(`Reference result: ${input.bar.reference.trim()}`)\n if (verdict.review?.trim()) body.push(`The check's review: ${verdict.review.trim()}`)\n section(profile.headings.bar, body)\n }\n section(profile.headings.plan, profile.plan.trim() === '' ? [] : [fill(profile.plan).trim()])\n section(profile.headings.rules, [\n ...(profile.rules.trim() === '' ? [] : [fill(profile.rules).trim()]),\n ...(input.sealed ? ['The score comes from cases you cannot see.'] : []),\n ])\n for (const appended of input.appended ?? []) {\n section(appended.heading, appended.text.trim() === '' ? [] : [appended.text.trim()])\n }\n return sections.join('\\n\\n')\n}\n\n// ── The record ───────────────────────────────────────────────────────────────────────────────────\n\n/** One continuation as the settle record carries it (`DriverContinuationRecord.continuations`). */\nexport interface ContinuationEntry {\n /** 1-based. */\n readonly continuation: number\n /** The driver attempt whose end this note answered. */\n readonly attempt: number\n /** sha256 of the note's text. */\n readonly noteDigest: string\n readonly profile: string\n readonly switches: {\n readonly failures: 'verbatim' | 'off'\n readonly panel: 'on' | 'off'\n readonly bar: 'on' | 'off'\n }\n /** The verdict the note reported: `null` when no result had reached the check. */\n readonly before: VerdictSummary | null\n /** The verdict at the director's next turn end: `null` when the run ended first. */\n readonly after: VerdictSummary | null\n /** The panel's part: questions asked, findings admitted, dollars (`null` = unknown). */\n readonly panel?: {\n readonly asked: number\n readonly proposed: number\n readonly admitted: number\n readonly usd: number | null\n /** Why the panel asked nothing this time, when it could not run. */\n readonly unavailable?: string\n }\n /** Sections a play appended. */\n readonly appended: number\n}\n\nexport interface VerdictSummary {\n readonly pass: boolean\n readonly composite?: number\n readonly failed?: number\n readonly total?: number\n}\n\nfunction summarizeVerdict(verdict: CheckVerdict | undefined): VerdictSummary | null {\n if (verdict === undefined) return null\n const total = Object.keys(verdict.items ?? {}).length\n return {\n pass: verdict.pass,\n ...(verdict.composite === undefined ? {} : { composite: verdict.composite }),\n ...(total === 0 ? {} : { failed: failedItems(verdict).length, total }),\n }\n}\n\nfunction noteDigest(note: string): string {\n return `sha256:${sha256(note)}`\n}\n\n/** A run directory's continuation files: the root's at `<runDir>/continuations/<n>/`, a nested\n * manager's at `<runDir>/continuations/managers/<owner>/<n>/`. */\nexport const CONTINUATIONS_DIR = 'continuations'\n\n/**\n * Write one continuation's files under `<dir>/<n>/`: `note.md`, `verdict.json`, and\n * `panel.jsonl` when the panel ran. The director reads them through `read_continuation`, because\n * its box cannot read the driver's run directory.\n */\nasync function writeContinuationFiles(\n dir: string,\n continuation: number,\n files: {\n readonly note: string\n readonly verdict?: CheckVerdict\n readonly panel?: ReadonlyArray<unknown>\n },\n): Promise<void> {\n const at = join(dir, String(continuation))\n await mkdir(at, { recursive: true })\n writeAtomicDurableFile(join(at, 'note.md'), `${files.note}\\n`)\n writeAtomicDurableFile(\n join(at, 'verdict.json'),\n `${JSON.stringify(files.verdict ?? null, null, 2)}\\n`,\n )\n if (files.panel !== undefined) {\n writeAtomicDurableFile(\n join(at, 'panel.jsonl'),\n files.panel.map((line) => JSON.stringify(line)).join('\\n') + (files.panel.length ? '\\n' : ''),\n )\n }\n}\n\n// ── The progress reading ─────────────────────────────────────────────────────────────────────────\n\n/** The best composite across `reads`, or `undefined` when no read scored. */\nexport function bestComposite(reads: ReadonlyArray<CheckRead>): number | undefined {\n let best: number | undefined\n for (const read of reads) {\n const value = read.verdict?.composite\n if (value !== undefined && (best === undefined || value > best)) best = value\n }\n return best\n}\n\n/** The readout a continuation is composed from. */\nexport interface ContinuationContext {\n /** The attempt that just completed, 1-based. */\n readonly attempt: number\n /** Continuations this run has already sent. */\n readonly continuations: number\n /** The mark read after the completed drive. */\n readonly progress: DriverProgressMark\n readonly budget: DriverBudgetReadout\n /** Re-entered drives in a row, this one included, that ended without progress. */\n readonly barrenReentries: number\n readonly signal: AbortSignal\n}\n\nfunction format(value: number): string {\n return Number.isInteger(value) ? String(value) : value.toFixed(3).replace(/0+$/u, '')\n}\n\n// ── One manager's continuations ──────────────────────────────────────────────────────────────────\n\n/** What a manager's continuation keeper reads from its run. */\ninterface ContinuationKeeperInput {\n readonly policy: ContinuationPolicy\n readonly task: unknown\n /** What the run owes, from the check's description. */\n readonly owed?: string\n /** The check's feedback mode: `pass-only` keeps the FAIL lines out of every note. */\n readonly feedback?: 'verbatim' | 'pass-only'\n readonly sealed?: boolean\n /** Every check read so far, oldest first. */\n readonly reads: () => ReadonlyArray<CheckRead>\n /** Settled workers, for the panel's `{worker}` questions. */\n readonly workers: () => ReadonlyArray<{ readonly id: string; readonly label: string }>\n /** Where each continuation's files go (`<dir>/<n>/`). Omit to keep them in memory only. */\n readonly dir?: string\n /** The run's own traces for the panel, read at each continuation; `undefined` when none yet. */\n readonly traces?: () => Promise<TraceAnalysisStore | undefined>\n /** Whether `read_continuation` is served to this manager. */\n readonly canReadMore: boolean\n /** Whether submit_result is served to this manager. Absent means unavailable. */\n readonly canSubmitResult?: boolean\n}\n\n/** One manager's continuation state: the notes it was sent and the panel's running ledger. */\nexport interface ContinuationKeeper {\n /** Write the next note. The driver loop calls it only when the check is unmet. */\n compose(context: ContinuationContext): Promise<string>\n /** `read_continuation`: the full record of continuation `n`, or the latest. */\n read(continuation: number | undefined): unknown\n /** The settle record's `continuations`, with the last note's `after` read from the final check. */\n entries(): ReadonlyArray<ContinuationEntry>\n}\n\n/** Build the continuation state for one manager with a check. */\nexport function createContinuationKeeper(input: ContinuationKeeperInput): ContinuationKeeper {\n const { policy } = input\n const failures: 'verbatim' | 'off' = input.feedback === 'pass-only' ? 'off' : policy.failures\n const entries: ContinuationEntry[] = []\n const notes: Array<{\n readonly note: string\n readonly verdict?: CheckVerdict\n readonly panel?: ReadonlyArray<unknown>\n /** The check read the note answered, for the `after` reading. */\n readonly read: number\n }> = []\n let findings: ReadonlyArray<AdmittedFinding> = []\n let panelUsd = 0\n let panelUsdKnown = true\n\n const latestVerdict = (): { verdict?: CheckVerdict; read: number } => {\n const reads = input.reads()\n for (let i = reads.length - 1; i >= 0; i -= 1) {\n const read = reads[i]\n if (read?.verdict !== undefined) return { verdict: read.verdict, read: read.read }\n }\n return { read: 0 }\n }\n\n const closePrevious = (): void => {\n const last = entries.at(-1)\n const lastNote = notes.at(-1)\n if (last === undefined || lastNote === undefined) return\n const latest = latestVerdict()\n entries[entries.length - 1] = {\n ...last,\n after: latest.read > lastNote.read ? summarizeVerdict(latest.verdict) : null,\n }\n }\n\n return {\n async compose(context) {\n closePrevious()\n const continuation = entries.length + 1\n const { verdict, read } = latestVerdict()\n const failing = verdict === undefined ? [] : failedItems(verdict)\n let panelRecord: ContinuationEntry['panel'] | undefined\n let panelLines: unknown[] | undefined\n if (policy.panel === 'on' && policy.runPanel !== undefined && policy.panelUsd !== undefined) {\n const workers = input.workers()\n const questions = expandQuestions(policy.profile.questions ?? [], failing, workers)\n const left = policy.panelUsd.perRun - panelUsd\n const usdCap = Math.min(policy.panelUsd.perContinuation, left)\n // An unknown cost closes the panel for the rest of the run: its cap can no longer be\n // proven, and an unmeasured spend is never read as zero.\n const asking = questions.length > 0 && usdCap > 0 && panelUsdKnown\n let traces: TraceAnalysisStore | undefined\n let unavailable: string | undefined\n if (asking) {\n try {\n traces = await input.traces?.()\n if (traces === undefined) unavailable = 'the run has recorded no trace yet'\n } catch (error) {\n // A trace that cannot be read is the evidence's failure, not the director's: the note\n // goes out without findings, and the record says why.\n unavailable = `the run's traces could not be read: ${error instanceof Error ? error.message : String(error)}`\n }\n }\n if (asking && traces !== undefined) {\n const result = await policy.runPanel({\n continuation,\n task: input.task,\n ...(verdict === undefined ? {} : { verdict }),\n reads: input.reads(),\n questions,\n traces,\n workers,\n ...(policy.best === undefined ? {} : { bar: policy.best }),\n ...(policy.reference === undefined ? {} : { reference: policy.reference }),\n usdCap,\n signal: context.signal,\n })\n if (result.usd === null) panelUsdKnown = false\n else panelUsd += result.usd\n findings = distillFindings(findings, result.findings, new Set(failing), continuation)\n panelRecord = {\n asked: questions.length,\n proposed: result.findings.length,\n admitted: findings.filter((finding) => finding.admittedAt === continuation).length,\n usd: result.usd,\n }\n panelLines = [\n ...result.findings.map((finding) => ({\n kind: 'finding',\n admitted: admitFinding(finding),\n ...finding,\n })),\n ...(result.receipts === undefined\n ? []\n : [{ kind: 'receipts', receipts: result.receipts }]),\n ]\n } else {\n panelRecord = {\n asked: 0,\n proposed: 0,\n admitted: 0,\n usd: 0,\n ...(unavailable === undefined ? {} : { unavailable }),\n }\n }\n }\n const appended = policy.append\n ? await policy.append({\n continuation,\n ...(verdict === undefined ? {} : { verdict }),\n reads: input.reads(),\n signal: context.signal,\n })\n : undefined\n const note = composeContinuationNote({\n profile: policy.profile,\n continuation,\n ...(verdict === undefined ? {} : { verdict }),\n ...(notes.at(-1)?.verdict === undefined ? {} : { previous: notes.at(-1)?.verdict }),\n reads: input.reads().length,\n failures,\n ...(policy.panel === 'on' ? { findings } : {}),\n ...(policy.bar === 'on'\n ? {\n bar: {\n ...(policy.best === undefined ? {} : { best: policy.best }),\n ...(policy.reference === undefined ? {} : { reference: policy.reference }),\n },\n }\n : {}),\n ...(appended === undefined ? {} : { appended: [appended] }),\n ...(input.owed === undefined ? {} : { owed: input.owed }),\n progress: context.progress,\n canReadMore: input.canReadMore,\n canSubmitResult: input.canSubmitResult === true,\n ...(input.sealed === true ? { sealed: true } : {}),\n })\n notes.push({\n note,\n ...(verdict === undefined ? {} : { verdict }),\n ...(panelLines === undefined ? {} : { panel: panelLines }),\n read,\n })\n entries.push({\n continuation,\n attempt: context.attempt,\n noteDigest: noteDigest(note),\n profile: policy.profile.id,\n switches: { failures, panel: policy.panel, bar: policy.bar },\n before: summarizeVerdict(verdict),\n after: null,\n ...(panelRecord === undefined ? {} : { panel: panelRecord }),\n appended: appended === undefined ? 0 : 1,\n })\n if (input.dir !== undefined) {\n await writeContinuationFiles(input.dir, continuation, {\n note,\n ...(verdict === undefined ? {} : { verdict }),\n ...(panelLines === undefined ? {} : { panel: panelLines }),\n })\n }\n return note\n },\n read(continuation) {\n const index = continuation === undefined ? notes.length - 1 : continuation - 1\n const entry = notes[index]\n if (entry === undefined) {\n return {\n found: false,\n reason:\n notes.length === 0\n ? 'no continuation has been sent in this run'\n : `continuations run from 1 to ${notes.length}`,\n }\n }\n return {\n found: true,\n continuation: index + 1,\n note: entry.note,\n // Under `pass-only` the check's lines stay hidden here too.\n verdict:\n failures === 'off' && entry.verdict !== undefined\n ? { pass: entry.verdict.pass }\n : (entry.verdict ?? null),\n findings: findings.filter((finding) => finding.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AG,MAAM,EAAE;EAC9C;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as ConfigError } from "./errors-DG8yufqX.js";
|
|
2
|
-
import { t as supervise } from "./supervise-
|
|
2
|
+
import { t as supervise } from "./supervise-DtVdvZpr.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-dhNeiaH_.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"delegate-Co5iUyS0.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,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":"delegate-dhNeiaH_.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,MAAM,KAAM,QAAiC;CAC7C,IAAI,OAAO,OAAO,UAAU,OAAO;CACnC,IAAI,MAAM,OAAO,OAAO,UAAU;EAChC,MAAM,IAAI;EACV,OAAO;GACL,QAAQ,IAAI,GAAG,cAAc;GAC7B,QAAQ,IAAI,GAAG,oBAAoB;GACnC,GAAI,MAAM,QAAQ,QAAQ,IAAI,GAAG,cA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