@tangle-network/agent-runtime 9.0.7 → 9.0.10
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 +16 -0
- package/dist/{activation-BA4WLqwN.js → activation-BuKAzxZB.js} +4 -4
- package/dist/{activation-BA4WLqwN.js.map → activation-BuKAzxZB.js.map} +1 -1
- package/dist/{activation-OSYxeVWi.d.ts → activation-CVVpVGyG.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +4 -4
- package/dist/{bundle-CcpL2lfr.js → bundle-9NLb1WO3.js} +2 -2
- package/dist/{bundle-CcpL2lfr.js.map → bundle-9NLb1WO3.js.map} +1 -1
- package/dist/candidate-execution/index.js +5 -4
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/{continuation-DDPfLw2w.js → continuation-CZaeHEzQ.js} +2 -2
- package/dist/{continuation-DDPfLw2w.js.map → continuation-CZaeHEzQ.js.map} +1 -1
- package/dist/{coordination-manager-CawAzVwE.js → coordination-manager-B-Ugh18D.js} +6 -6
- package/dist/{coordination-manager-CawAzVwE.js.map → coordination-manager-B-Ugh18D.js.map} +1 -1
- package/dist/deadline-CySmJ_0S.js +134 -0
- package/dist/deadline-CySmJ_0S.js.map +1 -0
- package/dist/{delegate-CXtDKuZm.js → delegate-Dizy-1ZC.js} +2 -2
- package/dist/{delegate-CXtDKuZm.js.map → delegate-Dizy-1ZC.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +13 -13
- package/dist/{failure-cause-W0o778qO.js → failure-cause-WifbY42M.js} +2 -2
- package/dist/{failure-cause-W0o778qO.js.map → failure-cause-WifbY42M.js.map} +1 -1
- package/dist/{graph-wQhBJwV_.js → graph-Bf3axJxp.js} +210 -300
- package/dist/graph-Bf3axJxp.js.map +1 -0
- package/dist/{graph-registry-Dbm8QhbA.js → graph-registry-B_1C7qye.js} +1 -1
- package/dist/{graph-registry-D0FE9VpR.js → graph-registry-BbZN5deo.js} +282 -6
- package/dist/graph-registry-BbZN5deo.js.map +1 -0
- package/dist/{improve-CKQwcCz1.js → improve-JThdxpGB.js} +8 -9
- package/dist/{improve-CKQwcCz1.js.map → improve-JThdxpGB.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +15 -102
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +7 -7
- package/dist/{jsonl-file-DsxVI0E_.js → jsonl-file-BhuxeejY.js} +114 -2
- package/dist/jsonl-file-BhuxeejY.js.map +1 -0
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +17 -16
- package/dist/{loop-runner-CCdQ1pmE.d.ts → loop-runner-40_tD2d4.d.ts} +2 -2
- package/dist/{loop-runner-3Acu4nGM.js → loop-runner-D8FP4oEN.js} +2 -2
- package/dist/{loop-runner-3Acu4nGM.js.map → loop-runner-D8FP4oEN.js.map} +1 -1
- 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 +7 -7
- package/dist/mcp/memory-bin.js +1 -1
- package/dist/output-artifacts-AqkZ8lO2.js +331 -0
- package/dist/output-artifacts-AqkZ8lO2.js.map +1 -0
- package/dist/{prepare-D7WwIddG.js → prepare-Cw4ZaN01.js} +5 -4
- package/dist/{prepare-D7WwIddG.js.map → prepare-Cw4ZaN01.js.map} +1 -1
- package/dist/{profile-BT0X-dm5.js → profile-Cxl_Ajl2.js} +2 -2
- package/dist/{profile-BT0X-dm5.js.map → profile-Cxl_Ajl2.js.map} +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-Cm6RLHuw.js → provision-supervisor-BDAXc65B.js} +8 -6
- package/dist/{provision-supervisor-Cm6RLHuw.js.map → provision-supervisor-BDAXc65B.js.map} +1 -1
- package/dist/{run-cancellation-B4-1Rt4u.js → run-cancellation-Cy9ie5cQ.js} +3 -3
- package/dist/{run-cancellation-B4-1Rt4u.js.map → run-cancellation-Cy9ie5cQ.js.map} +1 -1
- package/dist/{run-state-D1LkVTBQ.js → run-state-9FP-wBWK.js} +6 -6
- package/dist/{run-state-D1LkVTBQ.js.map → run-state-9FP-wBWK.js.map} +1 -1
- package/dist/{runtime-Bpad93aK.js → runtime-Czu2SSMy.js} +50 -25
- package/dist/{runtime-Bpad93aK.js.map → runtime-Czu2SSMy.js.map} +1 -1
- package/dist/{search-executor-D8TxXXSY.js → search-executor-Dl_WUQeH.js} +6 -6
- package/dist/{search-executor-D8TxXXSY.js.map → search-executor-Dl_WUQeH.js.map} +1 -1
- package/dist/{server-ctFbmRE5.js → server-Dbge7VDj.js} +5 -5
- package/dist/{server-ctFbmRE5.js.map → server-Dbge7VDj.js.map} +1 -1
- package/dist/{settle-record-BmXd-_3O.js → settle-record-tgpwk6QF.js} +3 -3
- package/dist/{settle-record-BmXd-_3O.js.map → settle-record-tgpwk6QF.js.map} +1 -1
- package/dist/{structural-rollout-DXymZ3go.js → structural-rollout-DUMYWwZ3.js} +7 -6
- package/dist/{structural-rollout-DXymZ3go.js.map → structural-rollout-DUMYWwZ3.js.map} +1 -1
- package/dist/{supervise-BTjv6h7v.js → supervise-BpcWjDMr.js} +12 -10
- package/dist/{supervise-BTjv6h7v.js.map → supervise-BpcWjDMr.js.map} +1 -1
- package/dist/{supervision-discovery-DzYBmrJC.js → supervision-discovery-Hekh50FG.js} +5 -5
- package/dist/{supervision-discovery-DzYBmrJC.js.map → supervision-discovery-Hekh50FG.js.map} +1 -1
- package/dist/{supervisor-Cnn37lon.js → supervisor-CdrDXnOJ.js} +9 -8
- package/dist/{supervisor-Cnn37lon.js.map → supervisor-CdrDXnOJ.js.map} +1 -1
- package/dist/{supervisor-accounting-BMrdsYxz.js → supervisor-accounting-us4w7tG6.js} +65 -154
- package/dist/supervisor-accounting-us4w7tG6.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +13 -13
- package/dist/{tool-server-Df-Uy99W.js → tool-server-CirrqFlr.js} +2 -2
- package/dist/{tool-server-Df-Uy99W.js.map → tool-server-CirrqFlr.js.map} +1 -1
- package/dist/{top-web-Qk6x-A9O.js → top-web-xSGEh02D.js} +7 -7
- package/dist/{top-web-Qk6x-A9O.js.map → top-web-xSGEh02D.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-KQkbyDmn.d.ts → types-DRijOelA.d.ts} +189 -164
- package/dist/{util-fcckrkKp.js → util-qsH5cC9S.js} +3 -132
- package/dist/util-qsH5cC9S.js.map +1 -0
- package/dist/{workspace-streams-DA9R3j-p.js → workspace-streams-BakRr-Pl.js} +9 -330
- package/dist/workspace-streams-BakRr-Pl.js.map +1 -0
- package/package.json +1 -1
- package/dist/graph-registry-D0FE9VpR.js.map +0 -1
- package/dist/graph-wQhBJwV_.js.map +0 -1
- package/dist/jsonl-file-DsxVI0E_.js.map +0 -1
- package/dist/supervisor-accounting-BMrdsYxz.js.map +0 -1
- package/dist/util-fcckrkKp.js.map +0 -1
- package/dist/workspace-streams-DA9R3j-p.js.map +0 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as sealAgentCandidateBundle } from "../bundle-
|
|
3
|
-
import { a as applyExactAgentProfileDiff, b as parseExactCandidateProfile, i as agentCandidateProfileAsAgentProfile, o as assertCandidateProfileBinding, p as freezeGenericAgentCandidateProfile, v as parseExactAgentProfile, y as parseExactAgentProfileDiff } from "../profile-
|
|
4
|
-
import { _ as sealTerminalDigest, a as consumePreparedCandidateExecution, b as sealAgentCandidateModelSettlement, c as withinCandidateCleanupDeadline, d as assertTerminalMatchesClaim, f as assertTerminalMatchesStaged, g as requireStagedTerminal, h as rejectedStage, i as beginPreparedCandidateDisposal, l as assertRecoveryMatchesStaged, m as rejectedFinish, n as executePreparedAgentCandidate, o as candidateClaimFileInternals, p as recoveredTerminalRecord, r as assertPreparedCandidateIntegrity, s as candidateCleanupDeadline, t as prepareAgentCandidateExecution, u as assertTerminalAllowedInPhase, v as terminalRecord, w as verifyAgentCandidateBundle, x as exactProcessProviderAsCandidateExecutor, y as createProtectedAgentCandidateModelPort } from "../prepare-
|
|
1
|
+
import { _ as embeddedCandidateArtifact, g as deepFreezeCandidate, i as candidateWorkspaceManifest, p as canonicalCandidateBytes$1 } from "../output-artifacts-AqkZ8lO2.js";
|
|
2
|
+
import { t as sealAgentCandidateBundle } from "../bundle-9NLb1WO3.js";
|
|
3
|
+
import { a as applyExactAgentProfileDiff, b as parseExactCandidateProfile, i as agentCandidateProfileAsAgentProfile, o as assertCandidateProfileBinding, p as freezeGenericAgentCandidateProfile, v as parseExactAgentProfile, y as parseExactAgentProfileDiff } from "../profile-Cxl_Ajl2.js";
|
|
4
|
+
import { _ as sealTerminalDigest, a as consumePreparedCandidateExecution, b as sealAgentCandidateModelSettlement, c as withinCandidateCleanupDeadline, d as assertTerminalMatchesClaim, f as assertTerminalMatchesStaged, g as requireStagedTerminal, h as rejectedStage, i as beginPreparedCandidateDisposal, l as assertRecoveryMatchesStaged, m as rejectedFinish, n as executePreparedAgentCandidate, o as candidateClaimFileInternals, p as recoveredTerminalRecord, r as assertPreparedCandidateIntegrity, s as candidateCleanupDeadline, t as prepareAgentCandidateExecution, u as assertTerminalAllowedInPhase, v as terminalRecord, w as verifyAgentCandidateBundle, x as exactProcessProviderAsCandidateExecutor, y as createProtectedAgentCandidateModelPort } from "../prepare-Cw4ZaN01.js";
|
|
5
|
+
import { a as verifyAgentCandidateWorkspaceArtifacts, c as createAgentCandidateWorkspacePort, h as workspaceLimits, i as readAgentCandidateWorkspaceArtifactFiles, n as captureAgentCandidateWorkspaceTreeToArtifacts, o as verifyAgentCandidateWorkspaceTree, p as captureAgentCandidateWorkspaceFiles, r as materializeAgentCandidateWorkspaceFromArtifacts, s as captureAgentCandidateWorkspace, t as captureAgentCandidateWorkspaceToArtifacts, y as verifiedArtifactChunks } from "../workspace-streams-BakRr-Pl.js";
|
|
5
6
|
import { agentCandidateArtifactRefSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema } from "@tangle-network/agent-interface";
|
|
6
7
|
import { randomUUID } from "node:crypto";
|
|
7
8
|
import { linkSync } from "node:fs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["canonicalCandidateBytes","canonicalCandidateBytes"],"sources":["../../src/candidate-execution/builder.ts","../../src/candidate-execution/claim-file-store.ts","../../src/candidate-execution/dispose.ts","../../src/candidate-execution/protected-model-grant.ts","../../src/candidate-execution/workspace-transfer.ts"],"sourcesContent":["import type { CodeSurface } from '@tangle-network/agent-eval/campaign'\nimport { verifyCodeSurface } from '@tangle-network/agent-eval/campaign'\nimport type {\n AgentCandidateCodeDisabled,\n AgentCandidateCodeNoOp,\n AgentCandidateExecution,\n AgentCandidateGitHubRepository,\n AgentCandidateKnowledge,\n AgentCandidateMemoryPolicy,\n AgentCandidateProfile,\n AgentProfile,\n AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { type AgentCandidateBundleInput, sealAgentCandidateBundle } from './bundle'\nimport { embeddedCandidateArtifact } from './digest'\nimport {\n applyExactAgentProfileDiff,\n freezeGenericAgentCandidateProfile,\n parseExactAgentProfile,\n parseExactAgentProfileDiff,\n parseExactCandidateProfile,\n} from './profile'\n\n/** A complete profile that can be frozen without losing behavior. */\nexport type AgentCandidateProfileSource =\n | {\n kind: 'profile'\n profile: AgentProfile\n }\n | {\n kind: 'profile-diffs'\n base: AgentProfile\n /** Applied in order before the resulting profile is frozen into the bundle. */\n diffs: readonly AgentProfileDiff[]\n }\n | {\n kind: 'candidate-profile'\n /** Already converted to the closed, secret-free candidate profile contract. */\n profile: AgentCandidateProfile\n }\n\n/** The only accepted path from an agent-eval code candidate to executable bytes. */\nexport interface AgentCandidateCodeSurfaceSource {\n kind: 'code-surface'\n surface: CodeSurface\n repository: AgentCandidateGitHubRepository\n /** Optional parent directory used to resolve a relative `surface.worktreeRef`. */\n worktreeDir?: string\n}\n\n/** Explicit control/no-op code or one finalized CodeSurface whose bytes must still verify. */\nexport type AgentCandidateCodeSource =\n | AgentCandidateCodeDisabled\n | AgentCandidateCodeNoOp\n | AgentCandidateCodeSurfaceSource\n\n/** Complete measured surfaces and execution policy compiled into one candidate bundle. */\nexport interface BuildAgentCandidateBundleInput {\n profile: AgentCandidateProfileSource\n code: AgentCandidateCodeSource\n execution: AgentCandidateExecution\n knowledge?: AgentCandidateKnowledge\n memory: AgentCandidateMemoryPolicy\n}\n\n/**\n * Compile one measured profile/code candidate into the immutable execution\n * contract. Code bytes are re-read and verified by agent-eval before they are\n * embedded. The returned bundle is schema-validated, canonically digested, and\n * deeply immutable; call `verifyAgentCandidateBundle` at the execution boundary\n * to re-read external memory, repository, and workspace artifacts.\n */\nexport function buildAgentCandidateBundle(\n input: BuildAgentCandidateBundleInput,\n): ReturnType<typeof sealAgentCandidateBundle> {\n const bundle: AgentCandidateBundleInput = {\n kind: 'agent-candidate-bundle',\n digestAlgorithm: 'rfc8785-sha256',\n profile: compileCandidateProfile(input.profile),\n code: compileCandidateCode(input.code),\n execution: input.execution,\n ...(input.knowledge !== undefined ? { knowledge: input.knowledge } : {}),\n memory: input.memory,\n }\n return sealAgentCandidateBundle(bundle)\n}\n\nfunction compileCandidateProfile(source: AgentCandidateProfileSource): AgentCandidateProfile {\n if (source.kind === 'candidate-profile') {\n return parseExactCandidateProfile(source.profile)\n }\n\n if (source.kind === 'profile') {\n return freezeGenericAgentCandidateProfile(source.profile)\n }\n\n if (source.kind !== 'profile-diffs') {\n throw new Error(\n `unsupported candidate profile source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n if (source.diffs.length === 0) {\n throw new Error('profile-diffs source requires at least one AgentProfileDiff')\n }\n let profile = parseExactAgentProfile(source.base, 'base profile')\n for (const [index, inputDiff] of source.diffs.entries()) {\n const diff = parseExactAgentProfileDiff(inputDiff, `profile diff ${index}`)\n profile = applyExactAgentProfileDiff(profile, diff, `profile diff ${index}`)\n }\n return freezeGenericAgentCandidateProfile(profile)\n}\n\nfunction compileCandidateCode(source: AgentCandidateCodeSource): AgentCandidateBundleInput['code'] {\n if (source.kind === 'disabled' || source.kind === 'no-op') return source\n if (source.kind !== 'code-surface') {\n throw new Error(\n `unsupported candidate code source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n\n const verified = verifyCodeSurface(source.surface, source.worktreeDir)\n const patch = embeddedCandidateArtifact(verified.patchBytes)\n if (\n patch.sha256 !== source.surface.patch.sha256 ||\n patch.byteLength !== source.surface.patch.byteLength\n ) {\n throw new Error('verified CodeSurface patch bytes do not match its content identity')\n }\n return {\n kind: 'git-patch',\n repository: source.repository,\n baseCommit: source.surface.baseCommit,\n baseTree: source.surface.baseTree,\n candidateTree: source.surface.candidateTree,\n patch: { format: 'git-diff-binary', artifact: patch },\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { linkSync } from 'node:fs'\nimport { mkdir, open, unlink } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\n\nimport {\n type AgentCandidateExecutionAttemptRecord,\n type AgentCandidateExecutionAttemptRef,\n type AgentCandidateExecutionClaim,\n type AgentCandidateExecutionClaimResult,\n type AgentCandidateExecutionClaimStore,\n type AgentCandidateExecutionFinishResult,\n type AgentCandidateExecutionLease,\n type AgentCandidateExecutionPhase,\n type AgentCandidateExecutionPhaseResult,\n type AgentCandidateExecutionRecoveryEvidence,\n type AgentCandidateExecutionStageResult,\n type AgentCandidateExecutionTerminalRecord,\n type AgentCandidateExecutionTerminalResult,\n type AgentCandidateRetryRejection,\n candidateClaimFileInternals,\n} from './claim'\nimport {\n assertRecoveryMatchesStaged,\n assertTerminalAllowedInPhase,\n assertTerminalMatchesClaim,\n assertTerminalMatchesStaged,\n recoveredTerminalRecord,\n rejectedFinish,\n rejectedStage,\n requireStagedTerminal,\n sealTerminalDigest,\n terminalRecord,\n} from './claim-terminal'\nimport { canonicalCandidateBytes } from './digest'\n\nconst {\n assertExpiredLease,\n assertLease,\n assertSameSlot,\n assertUnexpiredLease,\n attemptRecord,\n claimSlot,\n leaseDigest,\n newLease,\n readClaim,\n readClaimIfPresent,\n readTerminal,\n readTerminalIfPresent,\n readTransitionIfPresent,\n rejectedExistingClaim,\n rejectedRetry,\n retryRejection,\n sealAttemptRef,\n sealClaim,\n sealLease,\n} = candidateClaimFileInternals\n\nexport interface FileAgentCandidateExecutionClaimStoreOptions {\n /** Evaluator-owned directory shared by every process allowed to execute candidates. */\n directory: string\n /** Testable evaluator clock; defaults to `Date.now`. */\n now?: () => number\n}\n\n/** Cross-process lifecycle implemented as fsynced, create-if-absent records. */\nexport class FileAgentCandidateExecutionClaimStore implements AgentCandidateExecutionClaimStore {\n private readonly directory: string\n private readonly now: () => number\n\n constructor(options: FileAgentCandidateExecutionClaimStoreOptions) {\n if (options.directory.length === 0) {\n throw new Error('candidate execution claim directory must not be empty')\n }\n this.directory = options.directory\n this.now = options.now ?? Date.now\n }\n\n async tryClaim(\n requested: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateExecutionClaimResult> {\n const claim = sealClaim(requested)\n await mkdir(this.directory, { recursive: true })\n const claimPath = this.claimPath(claim)\n const existing = await readClaimIfPresent(claimPath)\n if (existing) {\n assertSameSlot(existing.claim, claim, claimPath)\n return rejectedExistingClaim(existing.claim, claim)\n }\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n const retryFailure = await this.retryFailure(claim)\n if (retryFailure) return rejectedRetry(claim, retryFailure)\n\n const lease = newLease(claim)\n const acquired = await writeRecordIfAbsent(this.directory, claimPath, {\n ...claim,\n phase: 'claimed',\n leaseDigest: leaseDigest(lease),\n })\n if (acquired) return Object.freeze({ acquired: true, claim, lease })\n\n const winner = await readClaim(claimPath)\n assertSameSlot(winner.claim, claim, claimPath)\n return rejectedExistingClaim(winner.claim, claim)\n }\n\n async getAttempt(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n return await this.storedAttempt(sealAttemptRef(requestedAttempt))\n }\n\n async markCandidateMayRun(\n requestedLease: AgentCandidateExecutionLease,\n ): Promise<AgentCandidateExecutionPhaseResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n if (state.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n if (state.staged) {\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const marked = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, 1),\n {\n kind: 'candidate-execution-phase',\n executionId: stored.claim.executionId,\n attempt: stored.claim.attempt,\n executionPlanDigest: stored.claim.executionPlanDigest,\n phase: 'candidate-may-run',\n },\n this.ownerPublication(stored.claim),\n )\n if (marked) return Object.freeze({ marked: true, phase: 'candidate-may-run' })\n const winner = await this.transitionState(stored.claim)\n if (winner.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n\n async stageTerminal(\n requestedLease: AgentCandidateExecutionLease,\n result: AgentCandidateExecutionTerminalResult,\n ): Promise<AgentCandidateExecutionStageResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const terminal = terminalRecord(stored.claim, result)\n const state = await this.transitionState(stored.claim)\n if (state.staged) return rejectedStage(state.staged, terminal)\n assertTerminalAllowedInPhase(state.phase, terminal)\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const transition = state.phase === 'claimed' ? 1 : 2\n const staged = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, transition),\n {\n kind: 'candidate-execution-pending-terminal',\n terminal,\n },\n this.ownerPublication(stored.claim),\n )\n if (staged) return Object.freeze({ staged: true, terminal })\n const winner = await this.transitionState(stored.claim)\n if (!winner.staged) {\n throw new Error('candidate execution phase transition won while staging terminal')\n }\n return rejectedStage(winner.staged, terminal)\n }\n\n async finish(\n requestedLease: AgentCandidateExecutionLease,\n requestedTerminalDigest: Sha256Digest,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const lease = sealLease(requestedLease)\n const terminalDigest = sealTerminalDigest(requestedTerminalDigest)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n const staged = requireStagedTerminal(state.staged, terminalDigest)\n const terminalPath = this.terminalPath(lease)\n const existing = await readTerminalIfPresent(terminalPath)\n if (existing) {\n assertTerminalMatchesClaim(existing, stored.claim, terminalPath)\n assertTerminalMatchesStaged(existing, staged, terminalPath)\n return rejectedFinish(existing, terminalDigest)\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const finished = await writeRecordIfAbsent(\n this.directory,\n terminalPath,\n {\n terminal: staged,\n },\n this.ownerPublication(stored.claim),\n )\n if (finished) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, lease, terminalPath)\n assertTerminalMatchesClaim(winner, stored.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, terminalDigest)\n }\n\n async recoverExpired(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const attempt = sealAttemptRef(requestedAttempt)\n const record = await this.storedAttempt(attempt)\n if (!record) throw new Error('candidate execution recovery does not name an acquired attempt')\n const recovered = recoveredTerminalRecord(record.claim, record.phase, evidence)\n if (record.staged) assertRecoveryMatchesStaged(record.staged, recovered)\n const requestedDigest = record.staged?.terminalDigest ?? recovered.terminalDigest\n if (record.terminal) return rejectedFinish(record.terminal, requestedDigest)\n assertExpiredLease(record.claim.leaseExpiresAtMs, this.now())\n\n let staged = record.staged\n if (!staged) {\n const transition = record.phase === 'claimed' ? 1 : 2\n const didStage = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(record.claim, transition),\n {\n kind: 'candidate-execution-pending-terminal',\n terminal: recovered,\n },\n )\n if (didStage) {\n staged = recovered\n } else {\n const winner = await this.transitionState(record.claim)\n if (!winner.staged) {\n throw new Error(\n 'candidate execution recovery lost terminal staging to a phase transition',\n )\n }\n assertRecoveryMatchesStaged(winner.staged, recovered)\n staged = winner.staged\n }\n }\n\n const terminalPath = this.terminalPath(attempt)\n const didFinish = await writeRecordIfAbsent(this.directory, terminalPath, {\n terminal: staged,\n })\n if (didFinish) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, attempt, terminalPath)\n assertTerminalMatchesClaim(winner, record.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, staged.terminalDigest)\n }\n\n private async storedAttempt(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n const claimPath = this.claimPath(claim)\n const stored = await readClaimIfPresent(claimPath)\n if (!stored) return undefined\n assertSameSlot(stored.claim, claim, claimPath)\n const terminalPath = this.terminalPath(claim)\n const terminal = await readTerminalIfPresent(terminalPath)\n // Terminal publication follows its immutable staged outbox, so read that prerequisite later.\n const state = await this.transitionState(stored.claim)\n if (terminal) {\n assertTerminalMatchesClaim(terminal, stored.claim, terminalPath)\n if (!state.staged) {\n throw new Error(\n `candidate execution terminal record at ${terminalPath} has no staged outbox`,\n )\n }\n assertTerminalMatchesStaged(terminal, state.staged, terminalPath)\n }\n return attemptRecord(stored.claim, state.phase, state.staged, terminal)\n }\n\n private async transitionState(claim: AgentCandidateExecutionClaim): Promise<{\n phase: AgentCandidateExecutionPhase\n staged?: AgentCandidateExecutionTerminalRecord\n }> {\n const firstPath = this.transitionPath(claim, 1)\n const first = await readTransitionIfPresent(firstPath, claim)\n if (!first) return { phase: 'claimed' }\n if (first.kind === 'pending') return { phase: 'claimed', staged: first.terminal }\n const secondPath = this.transitionPath(claim, 2)\n const second = await readTransitionIfPresent(secondPath, claim)\n if (!second) return { phase: 'candidate-may-run' }\n if (second.kind !== 'pending') {\n throw new Error(`candidate execution transition at ${secondPath} repeats the phase marker`)\n }\n return { phase: 'candidate-may-run', staged: second.terminal }\n }\n\n private async retryFailure(\n claim: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateRetryRejection | undefined> {\n if (claim.attempt === 1) return undefined\n return retryRejection(\n claim,\n await this.storedAttempt({\n executionId: claim.executionId,\n attempt: claim.attempt - 1,\n }),\n )\n }\n\n private ownerPublication(claim: AgentCandidateExecutionClaim): {\n authorizePublish: () => true\n } {\n return {\n authorizePublish: () => {\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n return true\n },\n }\n }\n\n private claimPath(claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>): string {\n return join(this.directory, `${claimSlot(claim)}.claim.json`)\n }\n\n private terminalPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.terminal.json`)\n }\n\n private transitionPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ordinal: 1 | 2,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.transition-${ordinal}.json`)\n }\n}\n\n/**\n * Candidate records keep this async writer because lease authorization must run after the\n * asynchronous temp-file fsync and immediately before synchronous link publication. The\n * supervisor durability helper is synchronous and has no lease hook, so combining them would\n * either move authorization earlier or add an async race to the claim boundary.\n */\nasync function writeRecordIfAbsent(\n directory: string,\n destination: string,\n record: object,\n options: {\n /** Synchronous authorization checked after temp fsync, immediately before atomic publication. */\n authorizePublish?: () => true\n } = {},\n): Promise<boolean> {\n const temporaryPath = join(directory, `.candidate-execution-${process.pid}-${randomUUID()}.tmp`)\n const handle = await open(temporaryPath, 'wx', 0o600)\n try {\n await handle.writeFile(\n Buffer.concat([Buffer.from(canonicalCandidateBytes(record)), Buffer.from('\\n')]),\n )\n await handle.sync()\n } finally {\n await handle.close()\n }\n\n let written = false\n try {\n if (options.authorizePublish && options.authorizePublish() !== true) {\n throw new Error('candidate execution record publication was not authorized')\n }\n // Authorization and the atomic filesystem call are one synchronous critical\n // section so the event loop cannot advance an injected lease clock between them.\n linkSync(temporaryPath, destination)\n written = true\n await syncDirectory(directory)\n } catch (error) {\n if (!isNodeError(error, 'EEXIST')) throw error\n } finally {\n await unlink(temporaryPath).catch((error: unknown) => {\n if (!isNodeError(error, 'ENOENT')) throw error\n })\n }\n return written\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n const handle = await open(directory, 'r')\n try {\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === code\n )\n}\n","import { candidateCleanupDeadline, withinCandidateCleanupDeadline } from './cleanup'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport {\n assertPreparedCandidateIntegrity,\n beginPreparedCandidateDisposal,\n consumePreparedCandidateExecution,\n} from './prepared-state'\nimport type { PreparedAgentCandidateExecution } from './types'\n\nexport interface DisposePreparedAgentCandidateOptions {\n cleanupTimeoutMs?: number\n}\n\n/** Revoke reservations held by a prepared candidate that will not be executed. */\nexport async function disposePreparedAgentCandidateExecution(\n prepared: PreparedAgentCandidateExecution,\n options: DisposePreparedAgentCandidateOptions = {},\n): Promise<{ disposed: true }> {\n const initialState = assertPreparedCandidateIntegrity(prepared)\n const cleanupTimeoutMs = options.cleanupTimeoutMs ?? initialState.cleanupTimeoutMs\n if (cleanupTimeoutMs > initialState.cleanupTimeoutMs) {\n throw new Error('disposal cleanup timeout exceeds the frozen preparation bound')\n }\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const state = beginPreparedCandidateDisposal(prepared)\n const cleanup: Array<Promise<unknown>> = []\n\n if (state.memory.mode === 'isolated') {\n const reservation = state.memoryReservation\n if (!reservation) throw new Error('isolated memory reservation is missing')\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const closed = await state.ports.memory.close({\n executionId: state.executionId,\n preparationId: reservation.preparationId,\n accessDigest: reservation.accessDigest,\n effectiveNamespace: reservation.effectiveNamespace,\n reason: 'abandoned',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('abandoned isolated memory access did not acknowledge closure')\n }\n },\n cleanupDeadlineAtMs,\n 'isolated memory disposal',\n ),\n )\n }\n\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const settlement = sealAgentCandidateModelSettlement(\n await state.ports.models.settleGrant({\n executionId: state.executionId,\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n resolved: state.resolvedModel,\n reason: 'abandoned',\n }),\n {\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n model: state.resolvedModel.model,\n },\n )\n if (settlement.usage.modelCalls !== 0) {\n throw new Error('unexecuted model reservation unexpectedly contains calls')\n }\n },\n cleanupDeadlineAtMs,\n 'model reservation disposal',\n ),\n )\n\n const results = await Promise.allSettled(cleanup)\n const failures = results\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason)\n if (failures.length > 0) {\n consumePreparedCandidateExecution(prepared, 'disposal-failed')\n throw new AggregateError(failures, 'candidate preparation disposal failed')\n }\n\n consumePreparedCandidateExecution(prepared, 'disposed')\n return Object.freeze({ disposed: true as const })\n}\n","import type { AgentCandidateResolvedModel } from '@tangle-network/agent-interface'\n\nimport type {\n AgentCandidateModelGrantActivateInput,\n AgentCandidateModelGrantReserveInput,\n AgentCandidateModelGrantSettleInput,\n} from './protected-model-port'\nimport type {\n AgentCandidateModelPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\n/** Reservation fields supplied by a caller before Runtime resolves the model. */\nexport type AgentCandidateModelGrantRunReservationInput = Omit<\n AgentCandidateModelGrantReserveInput,\n 'resolved'\n>\n\n/** Values available only while one protected model grant is active. */\nexport interface ProtectedAgentCandidateModelGrantContext {\n readonly activation: AgentCandidateProtectedModelActivation\n readonly reservation: AgentCandidateProtectedModelReservation\n readonly resolved: AgentCandidateResolvedModel\n}\n\n/** Inputs for one protected grant scoped to one bounded caller unit. */\nexport interface RunProtectedAgentCandidateModelGrantOptions<TResult> {\n /** Runtime port that validates and settles the evaluator-owned grant. */\n readonly port: AgentCandidateModelPort\n /** Provider-neutral model request resolved before any grant is reserved. */\n readonly resolve: Parameters<AgentCandidateModelPort['resolve']>[0]\n /** One bounded unit's immutable identity, attempt, expiry, and limits. */\n readonly reserve: AgentCandidateModelGrantRunReservationInput\n /** Must be no later than the reservation expiry. */\n readonly deadlineAtMs: AgentCandidateModelGrantActivateInput['deadlineAtMs']\n /** Execute exactly one bounded unit while the activated environment is valid. */\n readonly execute: (context: ProtectedAgentCandidateModelGrantContext) => Promise<TResult>\n}\n\n/** Result and sealed settlement returned after one protected grant closes. */\nexport interface RunProtectedAgentCandidateModelGrantResult<TResult> {\n readonly value: TResult\n readonly resolved: AgentCandidateResolvedModel\n readonly reservation: AgentCandidateProtectedModelReservation\n readonly settlement: AgentCandidateProtectedModelSettlement\n}\n\nconst SETTLEMENT_RETRY_INITIAL_DELAY_MS = 25\nconst SETTLEMENT_RETRY_MAX_DELAY_MS = 1_000\n\n/**\n * Run one bounded unit under a protected model grant.\n *\n * Runtime owns the grant lifecycle; callers own the unit boundary and any\n * durable scheduling or accounting around it. A reserved grant is settled\n * after activation failure or callback failure, and the callback error is\n * preserved when settlement also fails.\n */\nexport async function runProtectedAgentCandidateModelGrant<TResult>(\n options: RunProtectedAgentCandidateModelGrantOptions<TResult>,\n): Promise<RunProtectedAgentCandidateModelGrantResult<TResult>> {\n if (typeof options.execute !== 'function') {\n throw new TypeError('protected model grant execute callback is required')\n }\n\n const resolved = await options.port.resolve(options.resolve)\n const reservation = await options.port.reserveGrant({\n ...options.reserve,\n resolved,\n })\n\n let value!: TResult\n let executionError: unknown\n let executionFailed = false\n let activated = false\n let reason: AgentCandidateModelGrantSettleInput['reason'] = 'preparation-failed'\n\n try {\n const activation = await options.port.activateGrant({\n executionId: options.reserve.executionId,\n preparationId: options.reserve.preparationId,\n grantDigest: reservation.digest,\n resolved,\n deadlineAtMs: options.deadlineAtMs,\n })\n activated = true\n value = await options.execute({ activation, reservation, resolved })\n reason = 'completed'\n } catch (error) {\n executionError = error\n executionFailed = true\n if (activated) reason = 'failed'\n }\n\n let settlement: AgentCandidateProtectedModelSettlement\n try {\n settlement = await settleProtectedModelGrant(options, {\n executionId: options.reserve.executionId,\n preparationId: options.reserve.preparationId,\n grantDigest: reservation.digest,\n resolved,\n reason,\n })\n } catch (settlementError) {\n if (executionFailed) {\n throw new AggregateError(\n [executionError, settlementError],\n 'protected model execution failed and its grant did not settle',\n )\n }\n throw settlementError\n }\n\n if (executionFailed) throw executionError\n return { value, resolved, reservation, settlement }\n}\n\nasync function settleProtectedModelGrant<TResult>(\n options: RunProtectedAgentCandidateModelGrantOptions<TResult>,\n input: AgentCandidateModelGrantSettleInput,\n): Promise<AgentCandidateProtectedModelSettlement> {\n let delayMs = SETTLEMENT_RETRY_INITIAL_DELAY_MS\n for (;;) {\n try {\n return await options.port.settleGrant(input)\n } catch (error) {\n if (!isCandidateGrantDrainingError(error)) throw error\n const remainingMs = options.deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw error\n await waitForSettlementRetry(Math.min(delayMs, remainingMs))\n if (Date.now() >= options.deadlineAtMs) throw error\n delayMs = Math.min(delayMs * 2, SETTLEMENT_RETRY_MAX_DELAY_MS)\n }\n }\n}\n\nfunction waitForSettlementRetry(delayMs: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, delayMs))\n}\n\n/** Only the gateway's explicit draining state is retryable; auth and ledger errors fail closed. */\nfunction isCandidateGrantDrainingError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false\n const candidate = error as { code?: unknown; message?: unknown }\n if (candidate.code === 'candidate_grant_draining') return true\n return (\n typeof candidate.message === 'string' && /\\bcandidate_grant_draining\\b/u.test(candidate.message)\n )\n}\n","import { lstat } from 'node:fs/promises'\nimport { isAbsolute, resolve } from 'node:path'\nimport {\n type AgentCandidateArtifactRef,\n type AgentCandidateWorkspaceSnapshotEvidence,\n agentCandidateArtifactRefSchema,\n agentCandidateWorkspaceManifestMaterialSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n} from '@tangle-network/agent-interface'\nimport { verifiedArtifactChunks } from './artifact-streams'\nimport { canonicalCandidateBytes, deepFreezeCandidate } from './digest'\nimport type { AgentCandidateArtifactPort } from './types'\nimport { type AgentCandidateWorkspaceArchiveLimits, workspaceLimits } from './workspace-archive'\nimport {\n type CaptureAgentCandidateWorkspaceOptions,\n captureAgentCandidateWorkspace,\n createAgentCandidateWorkspacePort,\n} from './workspace-archive-local'\n\n/** The canonical workspace evidence without manifest material or embedded file bytes. */\nexport type AgentCandidateWorkspaceSnapshotReferences = Pick<\n AgentCandidateWorkspaceSnapshotEvidence,\n 'kind' | 'digest'\n> & {\n readonly manifest: AgentCandidateArtifactRef\n readonly archive: AgentCandidateArtifactRef\n}\n\nexport type CaptureAgentWorkspaceSnapshotOptions = Omit<\n CaptureAgentCandidateWorkspaceOptions,\n 'artifactPersistence'\n> & {\n artifactPersistence: NonNullable<CaptureAgentCandidateWorkspaceOptions['artifactPersistence']>\n}\n\n/**\n * Capture through the canonical archive owner and return references only.\n * The caller holds its existing private source workspace lease throughout capture, and binds\n * its public source provenance at the SDK boundary. Choose includeRepository and working-tree\n * explicitly when staged, dirty, deleted and unignored untracked Git files must travel.\n */\nexport async function captureAgentWorkspaceSnapshot(\n root: string,\n options: CaptureAgentWorkspaceSnapshotOptions,\n): Promise<AgentCandidateWorkspaceSnapshotReferences> {\n if (!options?.artifactPersistence) {\n throw new Error('portable workspace capture requires artifactPersistence')\n }\n const captured = await captureAgentCandidateWorkspace(root, {\n ...options,\n ...(options.limits ? { limits: { ...options.limits } } : {}),\n artifactPersistence: { ...options.artifactPersistence },\n })\n return workspaceReferences(captured.snapshot)\n}\n\nexport interface MaterializeAgentWorkspaceSnapshotOptions {\n snapshot: AgentCandidateWorkspaceSnapshotReferences\n /** Authorizes each immutable reference for the accepted transfer owner; must stream reads. */\n artifacts: AgentCandidateArtifactPort\n /** Absent destination inside a caller-owned private allocation scope. */\n destination: string\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n signal?: AbortSignal\n}\n\n/**\n * Restore canonical workspace references before an agent starts.\n * The SDK boundary validates source provenance and the accepted snapshot digest before this\n * byte-level composition runs. Artifact references identify content; the injected port owns\n * authorization. The archive owner verifies all files and Git state before publishing fresh\n * staging. Destinations present before or during artifact reads are refused. The caller owns\n * the allocation scope against other writers; Node directory rename is not atomic no-replace.\n */\nexport async function materializeAgentWorkspaceSnapshot(\n input: MaterializeAgentWorkspaceSnapshotOptions,\n): Promise<void> {\n input.signal?.throwIfAborted()\n const snapshot = workspaceReferences(input.snapshot)\n const limits = workspaceLimits(input.limits)\n if (!input.artifacts.readStream) {\n throw new Error('portable workspace restore requires an authorized readStream')\n }\n if (!isAbsolute(input.destination)) {\n throw new Error('portable workspace destination must be absolute')\n }\n const destination = resolve(input.destination)\n await assertAbsentDestination(destination)\n for (const artifact of [snapshot.manifest, snapshot.archive]) {\n if (artifact.byteLength > limits.maxArchiveBytes) {\n throw new Error('portable workspace artifact exceeds maxArchiveBytes')\n }\n }\n const manifest = await readArtifact(snapshot.manifest, input.artifacts, input.signal)\n const material = agentCandidateWorkspaceManifestMaterialSchema.parse(\n JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(manifest)),\n )\n if (!Buffer.from(canonicalCandidateBytes(material)).equals(manifest)) {\n throw new Error('workspace manifest artifact is not the exact canonical manifest material')\n }\n const evidence = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({ ...snapshot, material })\n const archive = await readArtifact(snapshot.archive, input.artifacts, input.signal)\n input.signal?.throwIfAborted()\n // The artifact resolver may await remote storage. A destination that appeared while waiting\n // belongs to its creator, even when it is empty.\n await assertAbsentDestination(destination)\n input.signal?.throwIfAborted()\n await createAgentCandidateWorkspacePort({ limits }).materialize({\n role: 'task',\n snapshot: evidence,\n archive,\n destination,\n ...(input.signal ? { signal: input.signal } : {}),\n })\n}\n\nfunction workspaceReferences(\n snapshot: Pick<\n AgentCandidateWorkspaceSnapshotEvidence,\n 'kind' | 'digest' | 'manifest' | 'archive'\n >,\n): AgentCandidateWorkspaceSnapshotReferences {\n if (snapshot.kind !== 'agent-candidate-workspace-snapshot') {\n throw new Error('portable workspace snapshot kind is invalid')\n }\n const manifest = agentCandidateArtifactRefSchema.parse(snapshot.manifest)\n const archive = agentCandidateArtifactRefSchema.parse(snapshot.archive)\n for (const artifact of [manifest, archive]) {\n if (!Number.isSafeInteger(artifact.byteLength) || artifact.byteLength < 1) {\n throw new Error('portable workspace artifacts require positive safe byte lengths')\n }\n }\n if (snapshot.digest !== manifest.sha256) {\n throw new Error('workspace digest must equal the canonical manifest hash')\n }\n return deepFreezeCandidate({ kind: snapshot.kind, digest: snapshot.digest, manifest, archive })\n}\n\nasync function readArtifact(\n reference: AgentCandidateArtifactRef,\n artifacts: AgentCandidateArtifactPort,\n signal?: AbortSignal,\n): Promise<Buffer> {\n const chunks: Buffer[] = []\n for await (const chunk of verifiedArtifactChunks(reference, artifacts, signal)) {\n chunks.push(Buffer.from(chunk))\n }\n return Buffer.concat(chunks)\n}\n\nasync function assertAbsentDestination(destination: string): Promise<void> {\n try {\n await lstat(destination)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n throw new Error('portable workspace destination already exists')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwEA,SAAgB,0BACd,OAC6C;CAC7C,MAAM,SAAoC;EACxC,MAAM;EACN,iBAAiB;EACjB,SAAS,wBAAwB,MAAM,OAAO;EAC9C,MAAM,qBAAqB,MAAM,IAAI;EACrC,WAAW,MAAM;EACjB,GAAI,MAAM,cAAc,KAAA,IAAY,EAAE,WAAW,MAAM,UAAU,IAAI,CAAC;EACtE,QAAQ,MAAM;CAChB;CACA,OAAO,yBAAyB,MAAM;AACxC;AAEA,SAAS,wBAAwB,QAA4D;CAC3F,IAAI,OAAO,SAAS,qBAClB,OAAO,2BAA2B,OAAO,OAAO;CAGlD,IAAI,OAAO,SAAS,WAClB,OAAO,mCAAmC,OAAO,OAAO;CAG1D,IAAI,OAAO,SAAS,iBAClB,MAAM,IAAI,MACR,yCAAyC,OAAQ,OAA8B,IAAI,GACrF;CAEF,IAAI,OAAO,MAAM,WAAW,GAC1B,MAAM,IAAI,MAAM,6DAA6D;CAE/E,IAAI,UAAU,uBAAuB,OAAO,MAAM,cAAc;CAChE,KAAK,MAAM,CAAC,OAAO,cAAc,OAAO,MAAM,QAAQ,GAAG;EACvD,MAAM,OAAO,2BAA2B,WAAW,gBAAgB,OAAO;EAC1E,UAAU,2BAA2B,SAAS,MAAM,gBAAgB,OAAO;CAC7E;CACA,OAAO,mCAAmC,OAAO;AACnD;AAEA,SAAS,qBAAqB,QAAqE;CACjG,IAAI,OAAO,SAAS,cAAc,OAAO,SAAS,SAAS,OAAO;CAClE,IAAI,OAAO,SAAS,gBAClB,MAAM,IAAI,MACR,sCAAsC,OAAQ,OAA8B,IA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Aa,SAAS,SAAS,MAAM,WAAW,MAAM,MAAM;CAClF,MAAM,QAAQ,eAAe;CAG7B,MAAM,wBAAwB,WAAW;CACzC,MAAM,QAAQ,eAAe;CAC7B,MAAM,kCAAkC,EAAE,OAAO,CAAC,CAAC,CAAC,YAAY;EAC9D,MAAM;EACN,UAAU;EACV;EACA;EACA,GAAI,MAAM,SAAS,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;CACjD,CAAC;AACH;AAEA,SAAS,oBACP,UAI2C;CAC3C,IAAI,SAAS,SAAS,sCACpB,MAAM,IAAI,MAAM,6CAA6C;CAE/D,MAAM,WAAW,gCAAgC,MAAM,SAAS,QAAQ;CACxE,MAAM,UAAU,gCAAgC,MAAM,SAAS,OAAO;CACtE,KAAK,MAAM,YAAY,CAAC,UAAU,OAAO,GACvC,IAAI,CAAC,OAAO,cAAc,SAAS,UAAU,KAAK,SAAS,aAAa,GACtE,MAAM,IAAI,MAAM,iEAAiE;CAGrF,IAAI,SAAS,WAAW,SAAS,QAC/B,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO,oBAAoB;EAAE,MAAM,SAAS;EAAM,QAAQ,SAAS;EAAQ;EAAU;CAAQ,CAAC;AAChG;AAEA,eAAe,aACb,WACA,WACA,QACiB;CACjB,MAAM,SAAmB,CAAC;CAC1B,WAAW,MAAM,SAAS,uBAAuB,WAAW,WAAW,MAAM,GAC3E,OAAO,KAAK,OAAO,KAAK,KAAK,CAAC;CAEhC,OAAO,OAAO,OAAO,MAAM;AAC7B;AAEA,eAAe,wBAAwB,aAAoC;CACzE,IAAI;EACF,MAAM,MAAM,WAAW;CACzB,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAAU;EACxD,MAAM;CACR;CACA,MAAM,IAAI,MAAM,+CAA+C;AACjE"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["canonicalCandidateBytes","canonicalCandidateBytes"],"sources":["../../src/candidate-execution/builder.ts","../../src/candidate-execution/claim-file-store.ts","../../src/candidate-execution/dispose.ts","../../src/candidate-execution/protected-model-grant.ts","../../src/candidate-execution/workspace-transfer.ts"],"sourcesContent":["import type { CodeSurface } from '@tangle-network/agent-eval/campaign'\nimport { verifyCodeSurface } from '@tangle-network/agent-eval/campaign'\nimport type {\n AgentCandidateCodeDisabled,\n AgentCandidateCodeNoOp,\n AgentCandidateExecution,\n AgentCandidateGitHubRepository,\n AgentCandidateKnowledge,\n AgentCandidateMemoryPolicy,\n AgentCandidateProfile,\n AgentProfile,\n AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { type AgentCandidateBundleInput, sealAgentCandidateBundle } from './bundle'\nimport { embeddedCandidateArtifact } from './digest'\nimport {\n applyExactAgentProfileDiff,\n freezeGenericAgentCandidateProfile,\n parseExactAgentProfile,\n parseExactAgentProfileDiff,\n parseExactCandidateProfile,\n} from './profile'\n\n/** A complete profile that can be frozen without losing behavior. */\nexport type AgentCandidateProfileSource =\n | {\n kind: 'profile'\n profile: AgentProfile\n }\n | {\n kind: 'profile-diffs'\n base: AgentProfile\n /** Applied in order before the resulting profile is frozen into the bundle. */\n diffs: readonly AgentProfileDiff[]\n }\n | {\n kind: 'candidate-profile'\n /** Already converted to the closed, secret-free candidate profile contract. */\n profile: AgentCandidateProfile\n }\n\n/** The only accepted path from an agent-eval code candidate to executable bytes. */\nexport interface AgentCandidateCodeSurfaceSource {\n kind: 'code-surface'\n surface: CodeSurface\n repository: AgentCandidateGitHubRepository\n /** Optional parent directory used to resolve a relative `surface.worktreeRef`. */\n worktreeDir?: string\n}\n\n/** Explicit control/no-op code or one finalized CodeSurface whose bytes must still verify. */\nexport type AgentCandidateCodeSource =\n | AgentCandidateCodeDisabled\n | AgentCandidateCodeNoOp\n | AgentCandidateCodeSurfaceSource\n\n/** Complete measured surfaces and execution policy compiled into one candidate bundle. */\nexport interface BuildAgentCandidateBundleInput {\n profile: AgentCandidateProfileSource\n code: AgentCandidateCodeSource\n execution: AgentCandidateExecution\n knowledge?: AgentCandidateKnowledge\n memory: AgentCandidateMemoryPolicy\n}\n\n/**\n * Compile one measured profile/code candidate into the immutable execution\n * contract. Code bytes are re-read and verified by agent-eval before they are\n * embedded. The returned bundle is schema-validated, canonically digested, and\n * deeply immutable; call `verifyAgentCandidateBundle` at the execution boundary\n * to re-read external memory, repository, and workspace artifacts.\n */\nexport function buildAgentCandidateBundle(\n input: BuildAgentCandidateBundleInput,\n): ReturnType<typeof sealAgentCandidateBundle> {\n const bundle: AgentCandidateBundleInput = {\n kind: 'agent-candidate-bundle',\n digestAlgorithm: 'rfc8785-sha256',\n profile: compileCandidateProfile(input.profile),\n code: compileCandidateCode(input.code),\n execution: input.execution,\n ...(input.knowledge !== undefined ? { knowledge: input.knowledge } : {}),\n memory: input.memory,\n }\n return sealAgentCandidateBundle(bundle)\n}\n\nfunction compileCandidateProfile(source: AgentCandidateProfileSource): AgentCandidateProfile {\n if (source.kind === 'candidate-profile') {\n return parseExactCandidateProfile(source.profile)\n }\n\n if (source.kind === 'profile') {\n return freezeGenericAgentCandidateProfile(source.profile)\n }\n\n if (source.kind !== 'profile-diffs') {\n throw new Error(\n `unsupported candidate profile source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n if (source.diffs.length === 0) {\n throw new Error('profile-diffs source requires at least one AgentProfileDiff')\n }\n let profile = parseExactAgentProfile(source.base, 'base profile')\n for (const [index, inputDiff] of source.diffs.entries()) {\n const diff = parseExactAgentProfileDiff(inputDiff, `profile diff ${index}`)\n profile = applyExactAgentProfileDiff(profile, diff, `profile diff ${index}`)\n }\n return freezeGenericAgentCandidateProfile(profile)\n}\n\nfunction compileCandidateCode(source: AgentCandidateCodeSource): AgentCandidateBundleInput['code'] {\n if (source.kind === 'disabled' || source.kind === 'no-op') return source\n if (source.kind !== 'code-surface') {\n throw new Error(\n `unsupported candidate code source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n\n const verified = verifyCodeSurface(source.surface, source.worktreeDir)\n const patch = embeddedCandidateArtifact(verified.patchBytes)\n if (\n patch.sha256 !== source.surface.patch.sha256 ||\n patch.byteLength !== source.surface.patch.byteLength\n ) {\n throw new Error('verified CodeSurface patch bytes do not match its content identity')\n }\n return {\n kind: 'git-patch',\n repository: source.repository,\n baseCommit: source.surface.baseCommit,\n baseTree: source.surface.baseTree,\n candidateTree: source.surface.candidateTree,\n patch: { format: 'git-diff-binary', artifact: patch },\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { linkSync } from 'node:fs'\nimport { mkdir, open, unlink } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\n\nimport {\n type AgentCandidateExecutionAttemptRecord,\n type AgentCandidateExecutionAttemptRef,\n type AgentCandidateExecutionClaim,\n type AgentCandidateExecutionClaimResult,\n type AgentCandidateExecutionClaimStore,\n type AgentCandidateExecutionFinishResult,\n type AgentCandidateExecutionLease,\n type AgentCandidateExecutionPhase,\n type AgentCandidateExecutionPhaseResult,\n type AgentCandidateExecutionRecoveryEvidence,\n type AgentCandidateExecutionStageResult,\n type AgentCandidateExecutionTerminalRecord,\n type AgentCandidateExecutionTerminalResult,\n type AgentCandidateRetryRejection,\n candidateClaimFileInternals,\n} from './claim'\nimport {\n assertRecoveryMatchesStaged,\n assertTerminalAllowedInPhase,\n assertTerminalMatchesClaim,\n assertTerminalMatchesStaged,\n recoveredTerminalRecord,\n rejectedFinish,\n rejectedStage,\n requireStagedTerminal,\n sealTerminalDigest,\n terminalRecord,\n} from './claim-terminal'\nimport { canonicalCandidateBytes } from './digest'\n\nconst {\n assertExpiredLease,\n assertLease,\n assertSameSlot,\n assertUnexpiredLease,\n attemptRecord,\n claimSlot,\n leaseDigest,\n newLease,\n readClaim,\n readClaimIfPresent,\n readTerminal,\n readTerminalIfPresent,\n readTransitionIfPresent,\n rejectedExistingClaim,\n rejectedRetry,\n retryRejection,\n sealAttemptRef,\n sealClaim,\n sealLease,\n} = candidateClaimFileInternals\n\nexport interface FileAgentCandidateExecutionClaimStoreOptions {\n /** Evaluator-owned directory shared by every process allowed to execute candidates. */\n directory: string\n /** Testable evaluator clock; defaults to `Date.now`. */\n now?: () => number\n}\n\n/** Cross-process lifecycle implemented as fsynced, create-if-absent records. */\nexport class FileAgentCandidateExecutionClaimStore implements AgentCandidateExecutionClaimStore {\n private readonly directory: string\n private readonly now: () => number\n\n constructor(options: FileAgentCandidateExecutionClaimStoreOptions) {\n if (options.directory.length === 0) {\n throw new Error('candidate execution claim directory must not be empty')\n }\n this.directory = options.directory\n this.now = options.now ?? Date.now\n }\n\n async tryClaim(\n requested: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateExecutionClaimResult> {\n const claim = sealClaim(requested)\n await mkdir(this.directory, { recursive: true })\n const claimPath = this.claimPath(claim)\n const existing = await readClaimIfPresent(claimPath)\n if (existing) {\n assertSameSlot(existing.claim, claim, claimPath)\n return rejectedExistingClaim(existing.claim, claim)\n }\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n const retryFailure = await this.retryFailure(claim)\n if (retryFailure) return rejectedRetry(claim, retryFailure)\n\n const lease = newLease(claim)\n const acquired = await writeRecordIfAbsent(this.directory, claimPath, {\n ...claim,\n phase: 'claimed',\n leaseDigest: leaseDigest(lease),\n })\n if (acquired) return Object.freeze({ acquired: true, claim, lease })\n\n const winner = await readClaim(claimPath)\n assertSameSlot(winner.claim, claim, claimPath)\n return rejectedExistingClaim(winner.claim, claim)\n }\n\n async getAttempt(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n return await this.storedAttempt(sealAttemptRef(requestedAttempt))\n }\n\n async markCandidateMayRun(\n requestedLease: AgentCandidateExecutionLease,\n ): Promise<AgentCandidateExecutionPhaseResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n if (state.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n if (state.staged) {\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const marked = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, 1),\n {\n kind: 'candidate-execution-phase',\n executionId: stored.claim.executionId,\n attempt: stored.claim.attempt,\n executionPlanDigest: stored.claim.executionPlanDigest,\n phase: 'candidate-may-run',\n },\n this.ownerPublication(stored.claim),\n )\n if (marked) return Object.freeze({ marked: true, phase: 'candidate-may-run' })\n const winner = await this.transitionState(stored.claim)\n if (winner.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n\n async stageTerminal(\n requestedLease: AgentCandidateExecutionLease,\n result: AgentCandidateExecutionTerminalResult,\n ): Promise<AgentCandidateExecutionStageResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const terminal = terminalRecord(stored.claim, result)\n const state = await this.transitionState(stored.claim)\n if (state.staged) return rejectedStage(state.staged, terminal)\n assertTerminalAllowedInPhase(state.phase, terminal)\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const transition = state.phase === 'claimed' ? 1 : 2\n const staged = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, transition),\n {\n kind: 'candidate-execution-pending-terminal',\n terminal,\n },\n this.ownerPublication(stored.claim),\n )\n if (staged) return Object.freeze({ staged: true, terminal })\n const winner = await this.transitionState(stored.claim)\n if (!winner.staged) {\n throw new Error('candidate execution phase transition won while staging terminal')\n }\n return rejectedStage(winner.staged, terminal)\n }\n\n async finish(\n requestedLease: AgentCandidateExecutionLease,\n requestedTerminalDigest: Sha256Digest,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const lease = sealLease(requestedLease)\n const terminalDigest = sealTerminalDigest(requestedTerminalDigest)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n const staged = requireStagedTerminal(state.staged, terminalDigest)\n const terminalPath = this.terminalPath(lease)\n const existing = await readTerminalIfPresent(terminalPath)\n if (existing) {\n assertTerminalMatchesClaim(existing, stored.claim, terminalPath)\n assertTerminalMatchesStaged(existing, staged, terminalPath)\n return rejectedFinish(existing, terminalDigest)\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const finished = await writeRecordIfAbsent(\n this.directory,\n terminalPath,\n {\n terminal: staged,\n },\n this.ownerPublication(stored.claim),\n )\n if (finished) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, lease, terminalPath)\n assertTerminalMatchesClaim(winner, stored.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, terminalDigest)\n }\n\n async recoverExpired(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const attempt = sealAttemptRef(requestedAttempt)\n const record = await this.storedAttempt(attempt)\n if (!record) throw new Error('candidate execution recovery does not name an acquired attempt')\n const recovered = recoveredTerminalRecord(record.claim, record.phase, evidence)\n if (record.staged) assertRecoveryMatchesStaged(record.staged, recovered)\n const requestedDigest = record.staged?.terminalDigest ?? recovered.terminalDigest\n if (record.terminal) return rejectedFinish(record.terminal, requestedDigest)\n assertExpiredLease(record.claim.leaseExpiresAtMs, this.now())\n\n let staged = record.staged\n if (!staged) {\n const transition = record.phase === 'claimed' ? 1 : 2\n const didStage = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(record.claim, transition),\n {\n kind: 'candidate-execution-pending-terminal',\n terminal: recovered,\n },\n )\n if (didStage) {\n staged = recovered\n } else {\n const winner = await this.transitionState(record.claim)\n if (!winner.staged) {\n throw new Error(\n 'candidate execution recovery lost terminal staging to a phase transition',\n )\n }\n assertRecoveryMatchesStaged(winner.staged, recovered)\n staged = winner.staged\n }\n }\n\n const terminalPath = this.terminalPath(attempt)\n const didFinish = await writeRecordIfAbsent(this.directory, terminalPath, {\n terminal: staged,\n })\n if (didFinish) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, attempt, terminalPath)\n assertTerminalMatchesClaim(winner, record.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, staged.terminalDigest)\n }\n\n private async storedAttempt(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n const claimPath = this.claimPath(claim)\n const stored = await readClaimIfPresent(claimPath)\n if (!stored) return undefined\n assertSameSlot(stored.claim, claim, claimPath)\n const terminalPath = this.terminalPath(claim)\n const terminal = await readTerminalIfPresent(terminalPath)\n // Terminal publication follows its immutable staged outbox, so read that prerequisite later.\n const state = await this.transitionState(stored.claim)\n if (terminal) {\n assertTerminalMatchesClaim(terminal, stored.claim, terminalPath)\n if (!state.staged) {\n throw new Error(\n `candidate execution terminal record at ${terminalPath} has no staged outbox`,\n )\n }\n assertTerminalMatchesStaged(terminal, state.staged, terminalPath)\n }\n return attemptRecord(stored.claim, state.phase, state.staged, terminal)\n }\n\n private async transitionState(claim: AgentCandidateExecutionClaim): Promise<{\n phase: AgentCandidateExecutionPhase\n staged?: AgentCandidateExecutionTerminalRecord\n }> {\n const firstPath = this.transitionPath(claim, 1)\n const first = await readTransitionIfPresent(firstPath, claim)\n if (!first) return { phase: 'claimed' }\n if (first.kind === 'pending') return { phase: 'claimed', staged: first.terminal }\n const secondPath = this.transitionPath(claim, 2)\n const second = await readTransitionIfPresent(secondPath, claim)\n if (!second) return { phase: 'candidate-may-run' }\n if (second.kind !== 'pending') {\n throw new Error(`candidate execution transition at ${secondPath} repeats the phase marker`)\n }\n return { phase: 'candidate-may-run', staged: second.terminal }\n }\n\n private async retryFailure(\n claim: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateRetryRejection | undefined> {\n if (claim.attempt === 1) return undefined\n return retryRejection(\n claim,\n await this.storedAttempt({\n executionId: claim.executionId,\n attempt: claim.attempt - 1,\n }),\n )\n }\n\n private ownerPublication(claim: AgentCandidateExecutionClaim): {\n authorizePublish: () => true\n } {\n return {\n authorizePublish: () => {\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n return true\n },\n }\n }\n\n private claimPath(claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>): string {\n return join(this.directory, `${claimSlot(claim)}.claim.json`)\n }\n\n private terminalPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.terminal.json`)\n }\n\n private transitionPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ordinal: 1 | 2,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.transition-${ordinal}.json`)\n }\n}\n\n/**\n * Candidate records keep this async writer because lease authorization must run after the\n * asynchronous temp-file fsync and immediately before synchronous link publication. The\n * supervisor durability helper is synchronous and has no lease hook, so combining them would\n * either move authorization earlier or add an async race to the claim boundary.\n */\nasync function writeRecordIfAbsent(\n directory: string,\n destination: string,\n record: object,\n options: {\n /** Synchronous authorization checked after temp fsync, immediately before atomic publication. */\n authorizePublish?: () => true\n } = {},\n): Promise<boolean> {\n const temporaryPath = join(directory, `.candidate-execution-${process.pid}-${randomUUID()}.tmp`)\n const handle = await open(temporaryPath, 'wx', 0o600)\n try {\n await handle.writeFile(\n Buffer.concat([Buffer.from(canonicalCandidateBytes(record)), Buffer.from('\\n')]),\n )\n await handle.sync()\n } finally {\n await handle.close()\n }\n\n let written = false\n try {\n if (options.authorizePublish && options.authorizePublish() !== true) {\n throw new Error('candidate execution record publication was not authorized')\n }\n // Authorization and the atomic filesystem call are one synchronous critical\n // section so the event loop cannot advance an injected lease clock between them.\n linkSync(temporaryPath, destination)\n written = true\n await syncDirectory(directory)\n } catch (error) {\n if (!isNodeError(error, 'EEXIST')) throw error\n } finally {\n await unlink(temporaryPath).catch((error: unknown) => {\n if (!isNodeError(error, 'ENOENT')) throw error\n })\n }\n return written\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n const handle = await open(directory, 'r')\n try {\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === code\n )\n}\n","import { candidateCleanupDeadline, withinCandidateCleanupDeadline } from './cleanup'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport {\n assertPreparedCandidateIntegrity,\n beginPreparedCandidateDisposal,\n consumePreparedCandidateExecution,\n} from './prepared-state'\nimport type { PreparedAgentCandidateExecution } from './types'\n\nexport interface DisposePreparedAgentCandidateOptions {\n cleanupTimeoutMs?: number\n}\n\n/** Revoke reservations held by a prepared candidate that will not be executed. */\nexport async function disposePreparedAgentCandidateExecution(\n prepared: PreparedAgentCandidateExecution,\n options: DisposePreparedAgentCandidateOptions = {},\n): Promise<{ disposed: true }> {\n const initialState = assertPreparedCandidateIntegrity(prepared)\n const cleanupTimeoutMs = options.cleanupTimeoutMs ?? initialState.cleanupTimeoutMs\n if (cleanupTimeoutMs > initialState.cleanupTimeoutMs) {\n throw new Error('disposal cleanup timeout exceeds the frozen preparation bound')\n }\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const state = beginPreparedCandidateDisposal(prepared)\n const cleanup: Array<Promise<unknown>> = []\n\n if (state.memory.mode === 'isolated') {\n const reservation = state.memoryReservation\n if (!reservation) throw new Error('isolated memory reservation is missing')\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const closed = await state.ports.memory.close({\n executionId: state.executionId,\n preparationId: reservation.preparationId,\n accessDigest: reservation.accessDigest,\n effectiveNamespace: reservation.effectiveNamespace,\n reason: 'abandoned',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('abandoned isolated memory access did not acknowledge closure')\n }\n },\n cleanupDeadlineAtMs,\n 'isolated memory disposal',\n ),\n )\n }\n\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const settlement = sealAgentCandidateModelSettlement(\n await state.ports.models.settleGrant({\n executionId: state.executionId,\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n resolved: state.resolvedModel,\n reason: 'abandoned',\n }),\n {\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n model: state.resolvedModel.model,\n },\n )\n if (settlement.usage.modelCalls !== 0) {\n throw new Error('unexecuted model reservation unexpectedly contains calls')\n }\n },\n cleanupDeadlineAtMs,\n 'model reservation disposal',\n ),\n )\n\n const results = await Promise.allSettled(cleanup)\n const failures = results\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason)\n if (failures.length > 0) {\n consumePreparedCandidateExecution(prepared, 'disposal-failed')\n throw new AggregateError(failures, 'candidate preparation disposal failed')\n }\n\n consumePreparedCandidateExecution(prepared, 'disposed')\n return Object.freeze({ disposed: true as const })\n}\n","import type { AgentCandidateResolvedModel } from '@tangle-network/agent-interface'\n\nimport type {\n AgentCandidateModelGrantActivateInput,\n AgentCandidateModelGrantReserveInput,\n AgentCandidateModelGrantSettleInput,\n} from './protected-model-port'\nimport type {\n AgentCandidateModelPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\n/** Reservation fields supplied by a caller before Runtime resolves the model. */\nexport type AgentCandidateModelGrantRunReservationInput = Omit<\n AgentCandidateModelGrantReserveInput,\n 'resolved'\n>\n\n/** Values available only while one protected model grant is active. */\nexport interface ProtectedAgentCandidateModelGrantContext {\n readonly activation: AgentCandidateProtectedModelActivation\n readonly reservation: AgentCandidateProtectedModelReservation\n readonly resolved: AgentCandidateResolvedModel\n}\n\n/** Inputs for one protected grant scoped to one bounded caller unit. */\nexport interface RunProtectedAgentCandidateModelGrantOptions<TResult> {\n /** Runtime port that validates and settles the evaluator-owned grant. */\n readonly port: AgentCandidateModelPort\n /** Provider-neutral model request resolved before any grant is reserved. */\n readonly resolve: Parameters<AgentCandidateModelPort['resolve']>[0]\n /** One bounded unit's immutable identity, attempt, expiry, and limits. */\n readonly reserve: AgentCandidateModelGrantRunReservationInput\n /** Must be no later than the reservation expiry. */\n readonly deadlineAtMs: AgentCandidateModelGrantActivateInput['deadlineAtMs']\n /** Execute exactly one bounded unit while the activated environment is valid. */\n readonly execute: (context: ProtectedAgentCandidateModelGrantContext) => Promise<TResult>\n}\n\n/** Result and sealed settlement returned after one protected grant closes. */\nexport interface RunProtectedAgentCandidateModelGrantResult<TResult> {\n readonly value: TResult\n readonly resolved: AgentCandidateResolvedModel\n readonly reservation: AgentCandidateProtectedModelReservation\n readonly settlement: AgentCandidateProtectedModelSettlement\n}\n\nconst SETTLEMENT_RETRY_INITIAL_DELAY_MS = 25\nconst SETTLEMENT_RETRY_MAX_DELAY_MS = 1_000\n\n/**\n * Run one bounded unit under a protected model grant.\n *\n * Runtime owns the grant lifecycle; callers own the unit boundary and any\n * durable scheduling or accounting around it. A reserved grant is settled\n * after activation failure or callback failure, and the callback error is\n * preserved when settlement also fails.\n */\nexport async function runProtectedAgentCandidateModelGrant<TResult>(\n options: RunProtectedAgentCandidateModelGrantOptions<TResult>,\n): Promise<RunProtectedAgentCandidateModelGrantResult<TResult>> {\n if (typeof options.execute !== 'function') {\n throw new TypeError('protected model grant execute callback is required')\n }\n\n const resolved = await options.port.resolve(options.resolve)\n const reservation = await options.port.reserveGrant({\n ...options.reserve,\n resolved,\n })\n\n let value!: TResult\n let executionError: unknown\n let executionFailed = false\n let activated = false\n let reason: AgentCandidateModelGrantSettleInput['reason'] = 'preparation-failed'\n\n try {\n const activation = await options.port.activateGrant({\n executionId: options.reserve.executionId,\n preparationId: options.reserve.preparationId,\n grantDigest: reservation.digest,\n resolved,\n deadlineAtMs: options.deadlineAtMs,\n })\n activated = true\n value = await options.execute({ activation, reservation, resolved })\n reason = 'completed'\n } catch (error) {\n executionError = error\n executionFailed = true\n if (activated) reason = 'failed'\n }\n\n let settlement: AgentCandidateProtectedModelSettlement\n try {\n settlement = await settleProtectedModelGrant(options, {\n executionId: options.reserve.executionId,\n preparationId: options.reserve.preparationId,\n grantDigest: reservation.digest,\n resolved,\n reason,\n })\n } catch (settlementError) {\n if (executionFailed) {\n throw new AggregateError(\n [executionError, settlementError],\n 'protected model execution failed and its grant did not settle',\n )\n }\n throw settlementError\n }\n\n if (executionFailed) throw executionError\n return { value, resolved, reservation, settlement }\n}\n\nasync function settleProtectedModelGrant<TResult>(\n options: RunProtectedAgentCandidateModelGrantOptions<TResult>,\n input: AgentCandidateModelGrantSettleInput,\n): Promise<AgentCandidateProtectedModelSettlement> {\n let delayMs = SETTLEMENT_RETRY_INITIAL_DELAY_MS\n for (;;) {\n try {\n return await options.port.settleGrant(input)\n } catch (error) {\n if (!isCandidateGrantDrainingError(error)) throw error\n const remainingMs = options.deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw error\n await waitForSettlementRetry(Math.min(delayMs, remainingMs))\n if (Date.now() >= options.deadlineAtMs) throw error\n delayMs = Math.min(delayMs * 2, SETTLEMENT_RETRY_MAX_DELAY_MS)\n }\n }\n}\n\nfunction waitForSettlementRetry(delayMs: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, delayMs))\n}\n\n/** Only the gateway's explicit draining state is retryable; auth and ledger errors fail closed. */\nfunction isCandidateGrantDrainingError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false\n const candidate = error as { code?: unknown; message?: unknown }\n if (candidate.code === 'candidate_grant_draining') return true\n return (\n typeof candidate.message === 'string' && /\\bcandidate_grant_draining\\b/u.test(candidate.message)\n )\n}\n","import { lstat } from 'node:fs/promises'\nimport { isAbsolute, resolve } from 'node:path'\nimport {\n type AgentCandidateArtifactRef,\n type AgentCandidateWorkspaceSnapshotEvidence,\n agentCandidateArtifactRefSchema,\n agentCandidateWorkspaceManifestMaterialSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n} from '@tangle-network/agent-interface'\nimport { verifiedArtifactChunks } from './artifact-streams'\nimport { canonicalCandidateBytes, deepFreezeCandidate } from './digest'\nimport type { AgentCandidateArtifactPort } from './types'\nimport { type AgentCandidateWorkspaceArchiveLimits, workspaceLimits } from './workspace-archive'\nimport {\n type CaptureAgentCandidateWorkspaceOptions,\n captureAgentCandidateWorkspace,\n createAgentCandidateWorkspacePort,\n} from './workspace-archive-local'\n\n/** The canonical workspace evidence without manifest material or embedded file bytes. */\nexport type AgentCandidateWorkspaceSnapshotReferences = Pick<\n AgentCandidateWorkspaceSnapshotEvidence,\n 'kind' | 'digest'\n> & {\n readonly manifest: AgentCandidateArtifactRef\n readonly archive: AgentCandidateArtifactRef\n}\n\nexport type CaptureAgentWorkspaceSnapshotOptions = Omit<\n CaptureAgentCandidateWorkspaceOptions,\n 'artifactPersistence'\n> & {\n artifactPersistence: NonNullable<CaptureAgentCandidateWorkspaceOptions['artifactPersistence']>\n}\n\n/**\n * Capture through the canonical archive owner and return references only.\n * The caller holds its existing private source workspace lease throughout capture, and binds\n * its public source provenance at the SDK boundary. Choose includeRepository and working-tree\n * explicitly when staged, dirty, deleted and unignored untracked Git files must travel.\n */\nexport async function captureAgentWorkspaceSnapshot(\n root: string,\n options: CaptureAgentWorkspaceSnapshotOptions,\n): Promise<AgentCandidateWorkspaceSnapshotReferences> {\n if (!options?.artifactPersistence) {\n throw new Error('portable workspace capture requires artifactPersistence')\n }\n const captured = await captureAgentCandidateWorkspace(root, {\n ...options,\n ...(options.limits ? { limits: { ...options.limits } } : {}),\n artifactPersistence: { ...options.artifactPersistence },\n })\n return workspaceReferences(captured.snapshot)\n}\n\nexport interface MaterializeAgentWorkspaceSnapshotOptions {\n snapshot: AgentCandidateWorkspaceSnapshotReferences\n /** Authorizes each immutable reference for the accepted transfer owner; must stream reads. */\n artifacts: AgentCandidateArtifactPort\n /** Absent destination inside a caller-owned private allocation scope. */\n destination: string\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n signal?: AbortSignal\n}\n\n/**\n * Restore canonical workspace references before an agent starts.\n * The SDK boundary validates source provenance and the accepted snapshot digest before this\n * byte-level composition runs. Artifact references identify content; the injected port owns\n * authorization. The archive owner verifies all files and Git state before publishing fresh\n * staging. Destinations present before or during artifact reads are refused. The caller owns\n * the allocation scope against other writers; Node directory rename is not atomic no-replace.\n */\nexport async function materializeAgentWorkspaceSnapshot(\n input: MaterializeAgentWorkspaceSnapshotOptions,\n): Promise<void> {\n input.signal?.throwIfAborted()\n const snapshot = workspaceReferences(input.snapshot)\n const limits = workspaceLimits(input.limits)\n if (!input.artifacts.readStream) {\n throw new Error('portable workspace restore requires an authorized readStream')\n }\n if (!isAbsolute(input.destination)) {\n throw new Error('portable workspace destination must be absolute')\n }\n const destination = resolve(input.destination)\n await assertAbsentDestination(destination)\n for (const artifact of [snapshot.manifest, snapshot.archive]) {\n if (artifact.byteLength > limits.maxArchiveBytes) {\n throw new Error('portable workspace artifact exceeds maxArchiveBytes')\n }\n }\n const manifest = await readArtifact(snapshot.manifest, input.artifacts, input.signal)\n const material = agentCandidateWorkspaceManifestMaterialSchema.parse(\n JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(manifest)),\n )\n if (!Buffer.from(canonicalCandidateBytes(material)).equals(manifest)) {\n throw new Error('workspace manifest artifact is not the exact canonical manifest material')\n }\n const evidence = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({ ...snapshot, material })\n const archive = await readArtifact(snapshot.archive, input.artifacts, input.signal)\n input.signal?.throwIfAborted()\n // The artifact resolver may await remote storage. A destination that appeared while waiting\n // belongs to its creator, even when it is empty.\n await assertAbsentDestination(destination)\n input.signal?.throwIfAborted()\n await createAgentCandidateWorkspacePort({ limits }).materialize({\n role: 'task',\n snapshot: evidence,\n archive,\n destination,\n ...(input.signal ? { signal: input.signal } : {}),\n })\n}\n\nfunction workspaceReferences(\n snapshot: Pick<\n AgentCandidateWorkspaceSnapshotEvidence,\n 'kind' | 'digest' | 'manifest' | 'archive'\n >,\n): AgentCandidateWorkspaceSnapshotReferences {\n if (snapshot.kind !== 'agent-candidate-workspace-snapshot') {\n throw new Error('portable workspace snapshot kind is invalid')\n }\n const manifest = agentCandidateArtifactRefSchema.parse(snapshot.manifest)\n const archive = agentCandidateArtifactRefSchema.parse(snapshot.archive)\n for (const artifact of [manifest, archive]) {\n if (!Number.isSafeInteger(artifact.byteLength) || artifact.byteLength < 1) {\n throw new Error('portable workspace artifacts require positive safe byte lengths')\n }\n }\n if (snapshot.digest !== manifest.sha256) {\n throw new Error('workspace digest must equal the canonical manifest hash')\n }\n return deepFreezeCandidate({ kind: snapshot.kind, digest: snapshot.digest, manifest, archive })\n}\n\nasync function readArtifact(\n reference: AgentCandidateArtifactRef,\n artifacts: AgentCandidateArtifactPort,\n signal?: AbortSignal,\n): Promise<Buffer> {\n const chunks: Buffer[] = []\n for await (const chunk of verifiedArtifactChunks(reference, artifacts, signal)) {\n chunks.push(Buffer.from(chunk))\n }\n return Buffer.concat(chunks)\n}\n\nasync function assertAbsentDestination(destination: string): Promise<void> {\n try {\n await lstat(destination)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n throw new Error('portable workspace destination already exists')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwEA,SAAgB,0BACd,OAC6C;CAC7C,MAAM,SAAoC;EACxC,MAAM;EACN,iBAAiB;EACjB,SAAS,wBAAwB,MAAM,OAAO;EA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A6C;CAE/D,MAAM,WAAW,gCAAgC,MAAM,SAAS,QAAQ;CACxE,MAAM,UAAU,gCAAgC,MAAM,SAAS,OAAO;CACtE,KAAK,MAAM,YAAY,CAAC,UAAU,OAAO,GACvC,IAAI,CAAC,OAAO,cAAc,SAAS,UAAU,KAAK,SAAS,aAAa,GACtE,MAAM,IAAI,MAAM,iEAAiE;CAGrF,IAAI,SAAS,WAAW,SAAS,QAC/B,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO,oBAAoB;EAAE,MAAM,SAAS;EAAM,QAAQ,SAAS;EAAQ;EAAU;CAAQ,CAAC;AAChG;AAEA,eAAe,aACb,WACA,WACA,QACiB;CACjB,MAAM,SAAmB,CAAC;CAC1B,WAAW,MAAM,SAAS,uBAAuB,WAAW,WAAW,MAAM,GAC3E,OAAO,KAAK,OAAO,KAAK,KAAK,CAAC;CAEhC,OAAO,OAAO,OAAO,MAAM;AAC7B;AAEA,eAAe,wBAAwB,aAAoC;CACzE,IAAI;EACF,MAAM,MAAM,WAAW;CACzB,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAAU;EACxD,MAAM;CACR;CACA,MAAM,IAAI,MAAM,+CAA+C;AACjE"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { l as sha256 } from "./jsonl-file-
|
|
1
|
+
import { l as sha256 } from "./jsonl-file-BhuxeejY.js";
|
|
2
2
|
import { m as ValidationError } from "./errors-DG8yufqX.js";
|
|
3
3
|
import { a as writeAtomicDurableFile } from "./durable-file-DstVeHcj.js";
|
|
4
4
|
import { join } from "node:path";
|
|
@@ -448,4 +448,4 @@ function createContinuationKeeper(input) {
|
|
|
448
448
|
}
|
|
449
449
|
export { createContinuationKeeper as a, checkVerdictOf as i, admitContinuationPolicy as n, failedItems as o, bestComposite as r, isFiniteNumber as s, CONTINUATIONS_DIR as t };
|
|
450
450
|
|
|
451
|
-
//# sourceMappingURL=continuation-
|
|
451
|
+
//# sourceMappingURL=continuation-CZaeHEzQ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"continuation-DDPfLw2w.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;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GACD,QAAQ,KAAK;IACX;IACA,SAAS,QAAQ;IACjB,YAAY,WAAW,IAAI;IAC3B,SAAS,OAAO,QAAQ;IACxB,UAAU;KAAE;KAAU,OAAO,OAAO;KAAO,KAAK,OAAO;IAAI;IAC3D,QAAQ,iBAAiB,OAAO;IAChC,OAAO;IACP,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,YAAY;IAC1D,UAAU,aAAa,KAAA,IAAY,IAAI;GACzC,CAAC;GACD,IAAI,MAAM,QAAQ,KAAA,GAChB,MAAM,uBAAuB,MAAM,KAAK,cAAc;IACpD;IACA,GAAI,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ;IAC3C,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,WAAW;GAC1D,CAAC;GAEH,OAAO;EACT;EACA,KAAK,cAAc;GACjB,MAAM,QAAQ,iBAAiB,KAAA,IAAY,MAAM,SAAS,IAAI,eAAe;GAC7E,MAAM,QAAQ,MAAM;GACpB,IAAI,UAAU,KAAA,GACZ,OAAO;IACL,OAAO;IACP,QACE,MAAM,WAAW,IACb,8CACA,+BAA+B,MAAM;GAC7C;GAEF,OAAO;IACL,OAAO;IACP,cAAc,QAAQ;IACtB,MAAM,MAAM;IAEZ,SACE,aAAa,SAAS,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-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,I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AgB,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,YAAY;IAC1D,UAAU,aAAa,KAAA,IAAY,IAAI;GACzC,CAAC;GACD,IAAI,MAAM,QAAQ,KAAA,GAChB,MAAM,uBAAuB,MAAM,KAAK,cAAc;IACpD;IACA,GAAI,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ;IAC3C,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,WAAW;GAC1D,CAAC;GAEH,OAAO;EACT;EACA,KAAK,cAAc;GACjB,MAAM,QAAQ,iBAAiB,KAAA,IAAY,MAAM,SAAS,IAAI,eAAe;GAC7E,MAAM,QAAQ,MAAM;GACpB,IAAI,UAAU,KAAA,GACZ,OAAO;IACL,OAAO;IACP,QACE,MAAM,WAAW,IACb,8CACA,+BAA+B,MAAM;GAC7C;GAEF,OAAO;IACL,OAAO;IACP,cAAc,QAAQ;IACtB,MAAM,MAAM;IAEZ,SACE,aAAa,SAAS,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,10 +1,10 @@
|
|
|
1
|
-
import { E as writeWorkerCancellation, F as parseWorkerToolTraceArtifact, I as workerTraceAnalysisStore, K as spawnJournalRecordEvents, O as writeWorkerSteerAcknowledgement, Rt as runtimeGraphMetadataKey, S as workerCancelRequestsFile, St as resolveSpawnResourcePaths, T as workerSteerRequestsDir, W as FileSpawnJournal, _ as readWorkerSteerAcknowledgement, an as FileResultBlobStore, d as claimWorkerSteerDelivery, g as readWorkerCancellation, h as readWorkerCancelRequests, it as meterRuntimeOwnedAccounting, mr as isTerminalNodeStatus, pr as isLiveNodeStatus, v as readWorkerSteerRequests } from "./supervisor-accounting-
|
|
1
|
+
import { E as writeWorkerCancellation, F as parseWorkerToolTraceArtifact, I as workerTraceAnalysisStore, K as spawnJournalRecordEvents, O as writeWorkerSteerAcknowledgement, Rt as runtimeGraphMetadataKey, S as workerCancelRequestsFile, St as resolveSpawnResourcePaths, T as workerSteerRequestsDir, W as FileSpawnJournal, _ as readWorkerSteerAcknowledgement, an as FileResultBlobStore, d as claimWorkerSteerDelivery, g as readWorkerCancellation, h as readWorkerCancelRequests, it as meterRuntimeOwnedAccounting, mr as isTerminalNodeStatus, pr as isLiveNodeStatus, v as readWorkerSteerRequests } from "./supervisor-accounting-us4w7tG6.js";
|
|
2
2
|
import { m as ValidationError } from "./errors-DG8yufqX.js";
|
|
3
|
-
import { N as contentAddress, o as settlementFailureCause, tt as assertValidBudget } from "./failure-cause-
|
|
3
|
+
import { N as contentAddress, o as settlementFailureCause, tt as assertValidBudget } from "./failure-cause-WifbY42M.js";
|
|
4
4
|
import { a as errMessage, f as resolveRedactor, t as detachedFrozen } from "./snapshot-BKI_w3JD.js";
|
|
5
|
-
import { X as INBOX_RECEIPT_KEY, _t as CheckUnavailableError, b as InMemorySpawnJournal, rt as createPeerMailbox, v as withDriverExecutor, x as createExecutorRegistry, y as InMemoryResultBlobStore } from "./supervisor-
|
|
6
|
-
import { i as checkVerdictOf, o as failedItems } from "./continuation-
|
|
7
|
-
import { c as writeRunCancellation, i as readRunCancellation, r as readRunCancelRequest, t as applyRunCancellation, v as FileCoordinationLog } from "./run-cancellation-
|
|
5
|
+
import { X as INBOX_RECEIPT_KEY, _t as CheckUnavailableError, b as InMemorySpawnJournal, rt as createPeerMailbox, v as withDriverExecutor, x as createExecutorRegistry, y as InMemoryResultBlobStore } from "./supervisor-CdrDXnOJ.js";
|
|
6
|
+
import { i as checkVerdictOf, o as failedItems } from "./continuation-CZaeHEzQ.js";
|
|
7
|
+
import { c as writeRunCancellation, i as readRunCancellation, r as readRunCancelRequest, t as applyRunCancellation, v as FileCoordinationLog } from "./run-cancellation-Cy9ie5cQ.js";
|
|
8
8
|
import { a as admitRuntimeSpawn, i as workerSettlement, n as resolveJsonPointer, o as safeJsonText, r as textBytes, t as createMapRouting } from "./coordination-map-routing-XZXTlCmn.js";
|
|
9
9
|
import { ResourceRequestSchema, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest } from "@tangle-network/agent-interface";
|
|
10
10
|
import { argHash, errorStreakDetector, observeAll, repeatedActionDetector } from "@tangle-network/agent-eval";
|
|
@@ -5262,4 +5262,4 @@ function createResumeReplay({ opts, bus, ledger, analysis, projectSettled }) {
|
|
|
5262
5262
|
}
|
|
5263
5263
|
export { downMessageRefusalReasons as a, createSteerAcknowledger as c, coordinationVerbNames as d, createFileRunContext as f, watchTrace as i, budgetOverspendText as l, withRunContext as m, createCoordinationToolsForManager as n, createEventBus as o, createInMemoryRunContext as p, defaultToolDetectors as r, createCancelAcknowledger as s, createCoordinationTools as t, normalizeAnalyzeOnSettle as u };
|
|
5264
5264
|
|
|
5265
|
-
//# sourceMappingURL=coordination-manager-
|
|
5265
|
+
//# sourceMappingURL=coordination-manager-B-Ugh18D.js.map
|