@tangle-network/agent-runtime 0.102.2 → 0.103.1
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/README.md +73 -10
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +5 -5
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/candidate-execution/index.d.ts +5 -41
- package/dist/candidate-execution/index.js +8 -6
- package/dist/{chunk-QCXD7NHM.js → chunk-3LJF5XSE.js} +79 -334
- package/dist/chunk-3LJF5XSE.js.map +1 -0
- package/dist/{chunk-3DW5DEKQ.js → chunk-5AITUUHO.js} +3 -3
- package/dist/{chunk-SQ3ZJH3Y.js → chunk-6WZZXQV5.js} +467 -23
- package/dist/chunk-6WZZXQV5.js.map +1 -0
- package/dist/{chunk-SCOHHMKU.js → chunk-AAN2MB2X.js} +3 -3
- package/dist/{chunk-KSM6GFHP.js → chunk-B7K7V22Y.js} +2 -2
- package/dist/{chunk-ZUCUAFVF.js → chunk-EAQ5YRRY.js} +1382 -62
- package/dist/chunk-EAQ5YRRY.js.map +1 -0
- package/dist/chunk-ISPWRSEC.js +408 -0
- package/dist/chunk-ISPWRSEC.js.map +1 -0
- package/dist/{chunk-7FJJUC73.js → chunk-LFM4JBRW.js} +29 -6
- package/dist/{chunk-7FJJUC73.js.map → chunk-LFM4JBRW.js.map} +1 -1
- package/dist/{chunk-ROILMKDL.js → chunk-QYCKIV6C.js} +3 -3
- package/dist/{chunk-LJLG734E.js → chunk-SBTWKPVR.js} +10 -11
- package/dist/{chunk-LJLG734E.js.map → chunk-SBTWKPVR.js.map} +1 -1
- package/dist/{chunk-CK76OZPM.js → chunk-SNSMRT6H.js} +56 -386
- package/dist/chunk-SNSMRT6H.js.map +1 -0
- package/dist/{chunk-EKUMRQNR.js → chunk-TUSOOIDV.js} +2 -2
- package/dist/{chunk-J6V6DWWS.js → chunk-ZOYN3JR5.js} +5 -5
- package/dist/{chunk-377GOJHJ.js → chunk-ZXICDSAK.js} +333 -4
- package/dist/chunk-ZXICDSAK.js.map +1 -0
- package/dist/{completion-gate-C6dhVN-N.d.ts → completion-gate-DLINnrkM.d.ts} +1 -1
- package/dist/{coordination-D9l_YmwW.d.ts → coordination-DTehA977.d.ts} +250 -8
- package/dist/environment-provider.d.ts +2 -2
- package/dist/index.d.ts +12 -12
- package/dist/index.js +17 -15
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +26 -8
- package/dist/intelligence.js +24 -7
- package/dist/intelligence.js.map +1 -1
- package/dist/knowledge.d.ts +6 -6
- package/dist/knowledge.js +9 -9
- package/dist/{loop-runner-bin-PnWslIw4.d.ts → loop-runner-bin-DhIXsLAd.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +5 -5
- package/dist/loop-runner-bin.js +6 -6
- package/dist/loops.d.ts +305 -148
- package/dist/loops.js +82 -14
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +6 -6
- package/dist/mcp/index.js +6 -6
- package/dist/profiles.d.ts +1 -1
- package/dist/{profile-DbfaMTdk.d.ts → protected-model-port-DzkUY3HQ.d.ts} +41 -3
- package/dist/{structural-rollout-D7xik9XR.d.ts → structural-rollout-BFPIy3iw.d.ts} +3 -3
- package/dist/supervise-Cp8bNcJi.d.ts +379 -0
- package/dist/testing.js +10 -10
- package/dist/testing.js.map +1 -1
- package/dist/{types-CWqfCO8s.d.ts → types-Cbp72qyu.d.ts} +1 -1
- package/dist/{types-CLat4bT9.d.ts → types-DK11_O4L.d.ts} +1 -1
- package/dist/types-lZTE_LBd.d.ts +957 -0
- package/dist/{worktree-fanout-DsIR4d6w.d.ts → worktree-fanout-DiiJWjJO.d.ts} +17 -5
- package/package.json +5 -4
- package/skills/build-with-agent-runtime/SKILL.md +7 -5
- package/skills/generate-eval/SKILL.md +45 -52
- package/skills/loop-writer/SKILL.md +79 -147
- package/skills/supervise/SKILL.md +33 -14
- package/dist/chunk-377GOJHJ.js.map +0 -1
- package/dist/chunk-CK76OZPM.js.map +0 -1
- package/dist/chunk-IMSNJSXH.js +0 -73
- package/dist/chunk-IMSNJSXH.js.map +0 -1
- package/dist/chunk-QCXD7NHM.js.map +0 -1
- package/dist/chunk-SQ3ZJH3Y.js.map +0 -1
- package/dist/chunk-ZUCUAFVF.js.map +0 -1
- package/dist/supervise-BQdNAXtK.d.ts +0 -131
- package/dist/types-D870JlH0.d.ts +0 -500
- /package/dist/{chunk-3DW5DEKQ.js.map → chunk-5AITUUHO.js.map} +0 -0
- /package/dist/{chunk-SCOHHMKU.js.map → chunk-AAN2MB2X.js.map} +0 -0
- /package/dist/{chunk-KSM6GFHP.js.map → chunk-B7K7V22Y.js.map} +0 -0
- /package/dist/{chunk-ROILMKDL.js.map → chunk-QYCKIV6C.js.map} +0 -0
- /package/dist/{chunk-EKUMRQNR.js.map → chunk-TUSOOIDV.js.map} +0 -0
- /package/dist/{chunk-J6V6DWWS.js.map → chunk-ZOYN3JR5.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/candidate-execution/exact-process-executor.ts"],"sourcesContent":["import { posix } from 'node:path'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { TraceStore } from '@tangle-network/agent-eval'\nimport type { AgentCandidateTermination, Sha256Digest } from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n AgentExactProcess,\n AgentExactProcessEnvironment,\n AgentExactProcessLaunch,\n AgentExactProcessResources,\n AgentExactProcessStatus,\n} from '@tangle-network/agent-interface/environment-provider'\n\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n immutableCandidateValue,\n sha256Bytes,\n} from './digest'\nimport {\n CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV,\n CANDIDATE_KNOWLEDGE_ROOT_ENV,\n candidateKnowledgeExecutionPaths,\n} from './knowledge'\nimport type {\n AgentCandidateExecutorPort,\n AgentCandidateExecutorRequest,\n AgentCandidateExecutorStopRequest,\n} from './types'\n\nconst DEFAULT_PROVISION_TIMEOUT_MS = 120_000\nconst DEFAULT_RECOVERY_RETENTION_MS = 15 * 60_000\n\ninterface ExactProcessRunState {\n environment: AgentExactProcessEnvironment\n output?: Uint8Array\n termination?: AgentCandidateTermination\n runtimeTermination?: AgentCandidateTermination\n trace?: {\n runId: string\n scenarioId: string\n startedAt: number\n deadlineAtMs: number\n timeoutMs: number\n tags: Record<string, string>\n written: boolean\n }\n}\n\nexport interface ExactProcessCandidateExecutorOptions {\n provider: AgentEnvironmentProvider\n resources: AgentExactProcessResources\n provisionTimeoutMs?: number\n recoveryRetentionMs?: number\n providerOptions?: Record<string, unknown>\n}\n\n/** Adapt one neutral exact-process provider to Runtime's trusted candidate boundary. */\nexport function exactProcessProviderAsCandidateExecutor(\n options: ExactProcessCandidateExecutorOptions,\n): AgentCandidateExecutorPort {\n return new ExactProcessAgentCandidateExecutor(options)\n}\n\nclass ExactProcessAgentCandidateExecutor implements AgentCandidateExecutorPort {\n private readonly states = new Map<string, ExactProcessRunState>()\n private readonly exactProcess\n private readonly resources: AgentExactProcessResources\n private readonly provisionTimeoutMs: number\n private readonly recoveryRetentionMs: number\n private readonly providerOptions?: Record<string, unknown>\n private capabilitiesPromise?: Promise<AgentEnvironmentCapabilities>\n\n constructor(private readonly options: ExactProcessCandidateExecutorOptions) {\n if (!options.provider.exactProcess) {\n throw new Error(\n `agent environment provider \"${options.provider.name}\" does not implement exact processes`,\n )\n }\n this.exactProcess = options.provider.exactProcess\n this.resources = exactResources(options.resources)\n this.provisionTimeoutMs = positiveInteger(\n options.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS,\n 'exact process provision timeout',\n )\n this.recoveryRetentionMs = positiveInteger(\n options.recoveryRetentionMs ?? DEFAULT_RECOVERY_RETENTION_MS,\n 'exact process recovery retention',\n )\n this.providerOptions = options.providerOptions\n ? immutableCandidateValue(options.providerOptions)\n : undefined\n }\n\n async execute(\n request: AgentCandidateExecutorRequest,\n context: Parameters<AgentCandidateExecutorPort['execute']>[1],\n ) {\n assertSupportedRequest(request)\n const outcome = request.benchmark.task.outcome\n if (outcome.kind !== 'output') throw new Error('exact process executor requires an output task')\n const network = request.executionPlan.value.material.model.access.network\n const egress =\n network.mode === 'disabled'\n ? ({ mode: 'blocked' } as const)\n : ({ mode: 'strict', allowDomains: [...network.domains] } as const)\n await this.assertCapability(egress.mode)\n context.signal.throwIfAborted()\n\n const key = executionKey(request.executionId, request.executionPlan.value.digest)\n if (this.states.has(key)) throw new Error('candidate execution environment is already active')\n const image = exactImage(\n request.executionPlan.value.material.container.image,\n request.executionPlan.value.material.container.manifestDigest,\n )\n const maxLifetimeMs = environmentLifetimeMs(\n request.hardLimits.timeoutMs,\n this.recoveryRetentionMs,\n )\n const createMaterial = immutableCandidateValue({\n kind: 'agent-candidate-exact-process-create',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n image,\n egress,\n maxLifetimeMs,\n provisionTimeoutMs: this.provisionTimeoutMs,\n resources: this.resources,\n output: { mediaType: outcome.mediaType, maxBytes: outcome.maxBytes },\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n const createInputDigest = canonicalCandidateDigest(createMaterial)\n const metadata = immutableCandidateValue({\n kind: 'agent-candidate-execution',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n createInputDigest,\n outputMediaType: outcome.mediaType,\n outputMaxBytes: outcome.maxBytes,\n })\n const environment = await this.exactProcess.create({\n image,\n egress,\n maxLifetimeMs,\n provisionTimeoutMs: this.provisionTimeoutMs,\n resources: this.resources,\n metadata,\n idempotencyKey: executionIdempotencyKey(\n request.executionId,\n request.executionPlan.value.digest,\n ),\n signal: context.signal,\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n try {\n assertExecutionEnvironment(environment, metadata, this.options.provider.name)\n } catch (error) {\n try {\n await environment.destroy()\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n 'exact process validation and cleanup both failed',\n )\n }\n throw error\n }\n const state: ExactProcessRunState = { environment }\n this.states.set(key, state)\n\n const existing = await environment.process.list()\n if (existing.length !== 0) {\n throw new Error('fresh candidate environment already contains a process')\n }\n await materializeRequest(environment, request, context.signal)\n const launch = exactLaunch(request)\n const startedAt = Date.now()\n state.trace = {\n runId: request.trace.runId,\n scenarioId: request.benchmark.task.scenario.id,\n startedAt,\n deadlineAtMs: context.deadlineAtMs,\n timeoutMs: request.hardLimits.timeoutMs,\n tags: {\n ...request.trace.tags,\n environmentId: environment.id,\n environmentProvider: environment.provider,\n },\n written: false,\n }\n const process = await environment.process.spawn(launch, { signal: context.signal })\n const outputPromise = collectOutput(process, outcome.maxBytes)\n void outputPromise.catch(() => undefined)\n let cancellation: Promise<void> | undefined\n let processExited = false\n const cancel = () => {\n if (!processExited) cancellation ??= stopProcess(process)\n }\n context.signal.addEventListener('abort', cancel, { once: true })\n if (context.signal.aborted) cancel()\n try {\n const termination = await process.wait()\n processExited = true\n context.signal.removeEventListener('abort', cancel)\n if (cancellation) await cancellation\n const status = await process.status()\n assertTerminalStatus(status, termination)\n state.output = await awaitOutput(outputPromise, context.signal, context.deadlineAtMs)\n state.termination = termination\n await appendExactProcessTrace(state, context.traceStore, status)\n return { executionId: request.executionId, termination }\n } finally {\n context.signal.removeEventListener('abort', cancel)\n }\n }\n\n async stop(\n request: AgentCandidateExecutorStopRequest,\n context: Parameters<AgentCandidateExecutorPort['stop']>[1],\n ): Promise<{ readonly stopped: true }> {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, true)\n if (!environment) return { stopped: true }\n let statuses = await environment.process.list()\n if (statuses.length > 1) {\n throw new Error('candidate exact process environment contains more than one process')\n }\n const status = statuses[0]\n if (status?.running) {\n const process = await environment.process.get(status.pid)\n if (!process) throw new Error('candidate environment lost its running process handle')\n await stopProcess(process)\n }\n context.signal.throwIfAborted()\n statuses = await environment.process.list()\n if (statuses.some((entry) => entry.running)) {\n throw new Error('candidate exact process termination is not proven')\n }\n const finalStatus = statuses[0]\n if (finalStatus) assertTerminalStatus(finalStatus)\n const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest))\n if (state) {\n state.termination = finalStatus?.termination ?? state.termination\n if (context.reason === 'timeout' && state.trace) {\n state.runtimeTermination = {\n kind: 'timeout',\n timeoutMs: state.trace.timeoutMs,\n }\n }\n await appendExactProcessTrace(state, context.traceStore, finalStatus)\n }\n return { stopped: true }\n }\n\n async capture(\n request: AgentCandidateExecutorStopRequest,\n context: Parameters<AgentCandidateExecutorPort['capture']>[1],\n ) {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, false)\n const statuses = await environment.process.list()\n const status = statuses[0]\n if (statuses.length !== 1 || !status || status.running) {\n throw new Error('candidate environment must contain one stopped process before capture')\n }\n assertTerminalStatus(status)\n const process = await environment.process.get(status.pid)\n if (!process) throw new Error('candidate environment lost its captured process handle')\n const currentStatus = await process.status()\n assertTerminalStatus(currentStatus, status.termination)\n const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest))\n const output =\n state?.output ??\n (await awaitOutput(\n collectOutput(process, outputSpec(environment).maxBytes),\n context.signal,\n Date.now() + this.provisionTimeoutMs,\n ))\n context.signal.throwIfAborted()\n const evidence = canonicalCandidateBytes({\n kind: 'agent-candidate-exact-process-capture',\n provider: environment.provider,\n environmentId: environment.id,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlanDigest,\n createInputDigest: environment.metadata?.createInputDigest,\n process: {\n pid: status.pid,\n exitCode: status.exitCode,\n ...(status.exitSignal ? { exitSignal: status.exitSignal } : {}),\n termination: status.termination,\n },\n ...(state?.runtimeTermination ? { runtimeTermination: state.runtimeTermination } : {}),\n output: { sha256: sha256Bytes(output), byteLength: output.byteLength },\n })\n return {\n taskOutcome: { kind: 'output' as const, bytes: output },\n evidence,\n }\n }\n\n async dispose(\n request: AgentCandidateExecutorStopRequest,\n context: { signal: AbortSignal },\n ): Promise<{ readonly disposed: true }> {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, true)\n if (!environment) return { disposed: true }\n let destroyError: unknown\n try {\n await environment.destroy()\n } catch (error) {\n destroyError = error\n }\n const remaining = await this.exactProcess.get(environment.id)\n if (remaining) {\n throw new Error('exact process environment disposal is not proven', { cause: destroyError })\n }\n context.signal.throwIfAborted()\n this.states.delete(executionKey(request.executionId, request.executionPlanDigest))\n return { disposed: true }\n }\n\n private async assertCapability(mode?: 'blocked' | 'strict'): Promise<void> {\n const pending =\n this.capabilitiesPromise ?? Promise.resolve(this.options.provider.capabilities())\n this.capabilitiesPromise = pending\n let capabilities: AgentEnvironmentCapabilities\n try {\n capabilities = await pending\n } catch (error) {\n if (this.capabilitiesPromise === pending) this.capabilitiesPromise = undefined\n throw error\n }\n const exact = capabilities.exactProcess\n if (!exact) {\n throw new Error(\n `agent environment provider \"${this.options.provider.name}\" does not declare exact process support`,\n )\n }\n if (mode && !exact.egress.includes(mode)) {\n throw new Error(\n `agent environment provider \"${this.options.provider.name}\" does not declare ${mode} exact egress`,\n )\n }\n }\n\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: false,\n ): Promise<AgentExactProcessEnvironment>\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: true,\n ): Promise<AgentExactProcessEnvironment | undefined>\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: boolean,\n ): Promise<AgentExactProcessEnvironment | undefined> {\n const key = executionKey(request.executionId, request.executionPlanDigest)\n const active = this.states.get(key)?.environment\n if (active) return active\n const metadata = {\n kind: 'agent-candidate-execution',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlanDigest,\n }\n const listed = await this.exactProcess.list({\n metadata,\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n const matches = listed.filter(\n (environment) =>\n environment.provider === this.options.provider.name &&\n Object.entries(metadata).every(([name, value]) =>\n isDeepStrictEqual(environment.metadata?.[name], value),\n ),\n )\n if (matches.length > 1) {\n throw new Error('multiple exact process environments match one candidate execution')\n }\n const environment = matches[0]\n if (!environment) {\n if (missingIsDeleted) return undefined\n throw new Error('candidate exact process evidence is unavailable')\n }\n if (!isSha256Digest(environment.metadata?.createInputDigest)) {\n throw new Error('candidate exact process create-input digest is unavailable')\n }\n this.states.set(key, { environment })\n return environment\n }\n}\n\nasync function appendExactProcessTrace(\n state: ExactProcessRunState,\n traceStore: TraceStore,\n status?: AgentExactProcessStatus,\n): Promise<void> {\n const trace = state.trace\n if (!trace || trace.written) return\n const endedAt = Math.max(trace.startedAt, Math.min(Date.now(), trace.deadlineAtMs))\n const termination = state.runtimeTermination ?? state.termination ?? status?.termination\n await traceStore.appendRun({\n runId: trace.runId,\n scenarioId: trace.scenarioId,\n startedAt: trace.startedAt,\n endedAt,\n status: termination?.kind === 'exit' && termination.exitCode === 0 ? 'completed' : 'failed',\n tags: trace.tags,\n })\n trace.written = true\n}\n\nfunction assertSupportedRequest(request: AgentCandidateExecutorRequest): void {\n if (request.benchmark.task.outcome.kind !== 'output') {\n throw new Error(\n 'exact process candidate executor does not support workspace outcomes; use Pier',\n )\n }\n if (request.executionPlan.value.material.codeKind !== 'disabled' || request.inputs.candidate) {\n throw new Error('exact process candidate executor does not support code workspaces; use Pier')\n }\n if (request.memory.mode !== 'disabled') {\n throw new Error('exact process candidate executor does not support isolated memory')\n }\n const mediaType = request.benchmark.task.outcome.mediaType.toLowerCase()\n if (\n !(\n mediaType.startsWith('text/') ||\n mediaType === 'application/json' ||\n mediaType.endsWith('+json')\n )\n ) {\n throw new Error('exact process candidate executor supports only UTF-8 text and JSON outputs')\n }\n if (!posix.isAbsolute(request.launch.executable) && !request.launch.env.PATH?.trim()) {\n throw new Error('exact process candidate executable must be absolute or declare a signed PATH')\n }\n}\n\nasync function materializeRequest(\n environment: AgentExactProcessEnvironment,\n request: AgentCandidateExecutorRequest,\n signal: AbortSignal,\n): Promise<void> {\n const knowledgePaths = assertKnowledgeExecutionBinding(request)\n for (const file of request.inputs.task.files) {\n await environment.writeFile(beneath(request.roots.taskRoot, file.path), file.bytes, {\n mode: file.mode,\n signal,\n })\n }\n const profileRoot =\n request.executionPlan.value.material.profile.targetWorkspace === 'task'\n ? request.roots.taskRoot\n : request.roots.candidateRoot\n if (!profileRoot) throw new Error('candidate profile targets a missing workspace')\n for (const file of request.profileActivation.files) {\n await environment.writeFile(\n beneath(profileRoot, file.path),\n Buffer.from(file.content, 'utf8'),\n { mode: file.mode, signal },\n )\n }\n if (request.knowledge && knowledgePaths) {\n for (const file of request.knowledge.files) {\n await environment.writeFile(beneath(knowledgePaths.root, file.path), file.bytes, {\n mode: file.mode,\n signal,\n })\n }\n if (request.knowledge.retrievalConfig && knowledgePaths.retrievalConfig) {\n await environment.writeFile(\n knowledgePaths.retrievalConfig,\n request.knowledge.retrievalConfig,\n { mode: 0o644, signal },\n )\n }\n }\n if (request.instruction.delivery.kind === 'utf8-file') {\n await environment.writeFile(request.instruction.delivery.path, request.instruction.bytes, {\n mode: 0o644,\n signal,\n })\n }\n}\n\nfunction assertKnowledgeExecutionBinding(\n request: AgentCandidateExecutorRequest,\n): ReturnType<typeof candidateKnowledgeExecutionPaths> | undefined {\n const knowledge = request.knowledge\n if (!knowledge) {\n if (\n request.launch.env[CANDIDATE_KNOWLEDGE_ROOT_ENV] !== undefined ||\n request.launch.env[CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV] !== undefined\n ) {\n throw new Error('candidate launch declares knowledge paths without verified knowledge')\n }\n return undefined\n }\n const paths = candidateKnowledgeExecutionPaths(\n request.roots.taskRoot,\n knowledge.retrievalConfig !== undefined,\n )\n if (\n request.launch.env[CANDIDATE_KNOWLEDGE_ROOT_ENV] !== paths.root ||\n request.launch.env[CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV] !== paths.retrievalConfig\n ) {\n throw new Error('candidate knowledge paths do not match the signed launch environment')\n }\n const reserved = [paths.root, paths.retrievalConfig].filter(\n (value): value is string => value !== undefined,\n )\n const profileRoot =\n request.executionPlan.value.material.profile.targetWorkspace === 'task'\n ? request.roots.taskRoot\n : request.roots.candidateRoot\n const otherFiles = [\n ...request.inputs.task.files.map((file) => beneath(request.roots.taskRoot, file.path)),\n ...(profileRoot\n ? request.profileActivation.files.map((file) => beneath(profileRoot, file.path))\n : []),\n ...(request.instruction.delivery.kind === 'utf8-file'\n ? [request.instruction.delivery.path]\n : []),\n ]\n if (\n otherFiles.some((path) =>\n reserved.some(\n (reservedPath) =>\n path === reservedPath ||\n path.startsWith(`${reservedPath}/`) ||\n reservedPath.startsWith(`${path}/`),\n ),\n )\n ) {\n throw new Error('candidate knowledge paths overlap other execution inputs')\n }\n return paths\n}\n\nfunction exactLaunch(request: AgentCandidateExecutorRequest): AgentExactProcessLaunch {\n const instruction = new TextDecoder('utf-8', { fatal: true }).decode(request.instruction.bytes)\n const base = {\n executable: request.launch.executable,\n args: request.launch.args,\n cwd: request.launch.cwd,\n env: request.launch.env,\n timeoutMs: 0,\n }\n switch (request.instruction.delivery.kind) {\n case 'argv-append':\n return { ...base, args: [...base.args, instruction] }\n case 'stdin-utf8':\n return { ...base, stdin: instruction }\n case 'utf8-file':\n return base\n }\n}\n\nasync function collectOutput(process: AgentExactProcess, maxBytes: number): Promise<Uint8Array> {\n const chunks: Buffer[] = []\n let byteLength = 0\n for await (const chunk of process.stdout()) {\n const bytes = Buffer.from(chunk, 'utf8')\n byteLength += bytes.byteLength\n if (byteLength > maxBytes) {\n let stopError: unknown\n try {\n await stopProcess(process)\n } catch (error) {\n stopError = error\n }\n throw new Error(`candidate output exceeds its ${maxBytes}-byte maximum`, {\n cause: stopError,\n })\n }\n chunks.push(bytes)\n }\n return Uint8Array.from(Buffer.concat(chunks, byteLength))\n}\n\nasync function awaitOutput(\n output: Promise<Uint8Array>,\n signal: AbortSignal,\n deadlineAtMs: number,\n): Promise<Uint8Array> {\n signal.throwIfAborted()\n const remainingMs = deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw new Error('candidate output deadline expired')\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n try {\n return await Promise.race([\n output,\n new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(signal.reason ?? new Error('candidate output cancelled'))\n signal.addEventListener('abort', onAbort, { once: true })\n timer = setTimeout(\n () => reject(new Error('candidate output deadline expired')),\n remainingMs,\n )\n }),\n ])\n } finally {\n if (onAbort) signal.removeEventListener('abort', onAbort)\n if (timer) clearTimeout(timer)\n }\n}\n\nasync function stopProcess(process: AgentExactProcess): Promise<void> {\n const before = await process.status()\n if (!before.running) return\n try {\n await process.kill()\n } catch (error) {\n if ((await process.status()).running) throw error\n }\n const termination = await process.wait()\n assertTerminalStatus(await process.status(), termination)\n}\n\nfunction assertTerminalStatus(\n status: AgentExactProcessStatus,\n expected?: AgentCandidateTermination,\n): asserts status is AgentExactProcessStatus & { termination: AgentCandidateTermination } {\n if (status.running || !status.termination) {\n throw new Error('exact process returned no terminal reason after exit')\n }\n if (expected && !isDeepStrictEqual(status.termination, expected)) {\n throw new Error('exact process wait and status returned different terminal reasons')\n }\n}\n\nfunction assertExecutionEnvironment(\n environment: AgentExactProcessEnvironment,\n metadata: Record<string, unknown>,\n providerName: string,\n): void {\n if (!environment.id || environment.provider !== providerName) {\n throw new Error('exact process provider returned the wrong environment identity')\n }\n if (\n !Object.entries(metadata).every(([name, value]) =>\n isDeepStrictEqual(environment.metadata?.[name], value),\n )\n ) {\n throw new Error('exact process provider did not persist candidate execution metadata')\n }\n}\n\nfunction outputSpec(environment: AgentExactProcessEnvironment): { maxBytes: number } {\n const maxBytes = environment.metadata?.outputMaxBytes\n if (!Number.isSafeInteger(maxBytes) || Number(maxBytes) < 1) {\n throw new Error('candidate exact process output bound is unavailable')\n }\n return { maxBytes: Number(maxBytes) }\n}\n\nfunction executionKey(executionId: string, executionPlanDigest: Sha256Digest): string {\n return `${executionId}\\0${executionPlanDigest}`\n}\n\nfunction executionIdempotencyKey(executionId: string, executionPlanDigest: Sha256Digest): string {\n return `candidate-${canonicalCandidateDigest({\n kind: 'agent-candidate-execution-identity',\n executionId,\n executionPlanDigest,\n }).slice('sha256:'.length)}`\n}\n\nfunction exactImage(image: string, manifestDigest: Sha256Digest): string {\n if (isSha256Digest(image)) {\n if (image !== manifestDigest) {\n throw new Error('candidate container image conflicts with its resolved manifest')\n }\n return image\n }\n const marker = image.lastIndexOf('@')\n if (marker < 0) return `${image}@${manifestDigest}`\n if (image.slice(marker + 1) !== manifestDigest) {\n throw new Error('candidate container image conflicts with its resolved manifest')\n }\n return image\n}\n\nfunction environmentLifetimeMs(timeoutMs: number, retentionMs: number): number {\n const total = positiveInteger(timeoutMs, 'candidate execution timeout') + retentionMs\n if (!Number.isSafeInteger(total)) throw new Error('candidate environment lifetime is too large')\n return Math.ceil(total / 1_000) * 1_000\n}\n\nfunction exactResources(resources: AgentExactProcessResources): AgentExactProcessResources {\n if (!Number.isFinite(resources.cpu) || resources.cpu <= 0) {\n throw new Error('exact process CPU must be positive and finite')\n }\n return Object.freeze({\n cpu: resources.cpu,\n memoryMb: positiveInteger(resources.memoryMb, 'exact process memory'),\n diskMb: positiveInteger(resources.diskMb, 'exact process disk'),\n })\n}\n\nfunction positiveInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1)\n throw new Error(`${label} must be a positive integer`)\n return value\n}\n\nfunction beneath(root: string, relativePath: string): string {\n if (posix.isAbsolute(relativePath)) throw new Error('candidate input path must be relative')\n const path = posix.normalize(relativePath)\n if (path === '..' || path.startsWith('../')) {\n throw new Error('candidate input path escapes its execution root')\n }\n return posix.join(root, path)\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value)\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,yBAAyB;AA+BlC,IAAM,+BAA+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AAK,QAAQ;AAC1C,UAAM,IAAI,MAAM,GAAG,KAAK,6BAA6B;AACvD,SAAO;AACT;AAEA,SAAS,QAAQ,MAAc,cAA8B;AAC3D,MAAI,MAAM,WAAW,YAAY,EAAG,OAAM,IAAI,MAAM,uCAAuC;AAC3F,QAAM,OAAO,MAAM,UAAU,YAAY;AACzC,MAAI,SAAS,QAAQ,KAAK,WAAW,KAAK,GAAG;AAC3C,UAAM,IAAI,MAAM,iDAAiD;AAAA,EACnE;AACA,SAAO,MAAM,KAAK,MAAM,IAAI;AAC9B;AAEA,SAAS,eAAe,OAAuC;AAC7D,SAAO,OAAO,UAAU,YAAY,wBAAwB,KAAK,KAAK;AACxE;","names":["environment"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/candidate-execution/builder.ts","../src/candidate-execution/claim-file-store.ts","../src/candidate-execution/dispose.ts","../src/candidate-execution/protected-model-port.ts","../src/candidate-execution/recover.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 state = await this.transitionState(stored.claim)\n const terminalPath = this.terminalPath(claim)\n const terminal = await readTerminalIfPresent(terminalPath)\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\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 {\n AgentCandidateModelAccessNetwork,\n AgentCandidateResolvedModel,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from './digest'\nimport { assertExactObjectKeys } from './exact-object'\nimport { sealAgentCandidateModelSettlement, usdToNanos } from './model-settlement'\nimport type {\n AgentCandidateModelLimits,\n AgentCandidateModelPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\nexport type AgentCandidateModelGrantReserveInput = Parameters<\n AgentCandidateModelPort['reserveGrant']\n>[0]\nexport type AgentCandidateModelGrantActivateInput = Parameters<\n AgentCandidateModelPort['activateGrant']\n>[0]\nexport type AgentCandidateModelGrantSettleInput = Parameters<\n AgentCandidateModelPort['settleGrant']\n>[0]\n\n/** Secret-free response from the service's reservation endpoint. */\nexport type AgentCandidateModelGrantReservation = AgentCandidateProtectedModelReservation\n\n/**\n * Narrow transport contract for a service that owns scoped model credentials\n * and the authoritative per-call usage ledger.\n *\n * An HTTP client can bind these methods to control-plane endpoints. Keeping\n * transport out of the runtime prevents parent credentials, endpoint paths,\n * and retry policy from becoming part of the portable candidate contract.\n */\nexport interface AgentCandidateModelGrantClient {\n reserve(input: AgentCandidateModelGrantReserveInput): Promise<AgentCandidateModelGrantReservation>\n activate(\n input: AgentCandidateModelGrantActivateInput,\n ): Promise<AgentCandidateProtectedModelActivation>\n settle(\n input: AgentCandidateModelGrantSettleInput,\n ): Promise<AgentCandidateProtectedModelSettlement>\n}\n\nexport interface CreateProtectedAgentCandidateModelPortOptions {\n client: AgentCandidateModelGrantClient\n /** Catalog/snapshot resolution stays separate from credential issuance. */\n resolveModel: AgentCandidateModelPort['resolve']\n /** The only public DNS name candidate processes may reach for inference. */\n gatewayDomain: string\n /** Exact environment names the activation endpoint must return, no more or fewer. */\n activationEnvNames: readonly string[]\n}\n\ninterface RememberedReservation {\n requestDigest: Sha256Digest\n responseDigest: Sha256Digest\n executionId: string\n preparationId: string\n grantDigest: Sha256Digest\n expiresAtMs: number\n resolved: AgentCandidateResolvedModel\n limits: AgentCandidateModelLimits\n maxCostUsdNanos: number\n activation: 'reserved' | 'activating' | 'activated'\n settlementDigest?: Sha256Digest\n settlementReason?: AgentCandidateModelGrantSettleInput['reason']\n}\n\ninterface RememberedSettlement {\n settlementDigest: Sha256Digest\n settlementReason: AgentCandidateModelGrantSettleInput['reason']\n expiresAtMs: number\n}\n\nconst MAX_RECENT_SETTLEMENTS = 4_096\nconst RECOVERED_SETTLEMENT_RETENTION_MS = 15 * 60 * 1_000\n\n/**\n * Bind a protected model-grant service to the immutable candidate runtime.\n *\n * The service remains the authority for expiry, admission, revocation, and\n * metering. This adapter independently checks every response before allowing\n * it to cross into candidate execution or durable receipt finalization.\n */\nexport function createProtectedAgentCandidateModelPort(\n options: CreateProtectedAgentCandidateModelPortOptions,\n): AgentCandidateModelPort {\n const gatewayDomain = assertGatewayDomain(options.gatewayDomain)\n const activationEnvNames = exactEnvironmentNames(options.activationEnvNames)\n const reservations = new Map<string, RememberedReservation>()\n const recentSettlements = new Map<string, RememberedSettlement>()\n\n return {\n resolve: async (input) => {\n const request = immutableCandidateValue(input)\n const resolved = validateResolvedModel(await options.resolveModel(request), request)\n return immutableCandidateValue(resolved)\n },\n\n reserveGrant: async (input) => {\n pruneExpiredState(reservations, recentSettlements, Date.now())\n const request = immutableCandidateValue(input)\n validateReserveInput(request)\n const requestDigest = canonicalCandidateDigest(request)\n const key = reservationKey(request.executionId, request.preparationId)\n if (recentSettlements.has(key)) {\n throw new Error('protected model reservation is already settled')\n }\n const previous = reservations.get(key)\n if (previous && previous.requestDigest !== requestDigest) {\n throw new Error('protected model reservation retry changed immutable input')\n }\n\n const reservation = validateReservation(\n await options.client.reserve(request),\n request,\n gatewayDomain,\n )\n const responseDigest = canonicalCandidateDigest(reservation)\n if (recentSettlements.has(key)) {\n throw new Error('protected model reservation completed after the grant was settled')\n }\n const recorded = previous ?? reservations.get(key)\n if (recorded && recorded.requestDigest !== requestDigest) {\n throw new Error('protected model reservation retry changed immutable input')\n }\n if (recorded && recorded.responseDigest !== responseDigest) {\n throw new Error('protected model reservation retry returned different evidence')\n }\n if (!recorded) {\n reservations.set(key, {\n requestDigest,\n responseDigest,\n executionId: request.executionId,\n preparationId: request.preparationId,\n grantDigest: reservation.digest,\n expiresAtMs: request.expiresAtMs,\n resolved: immutableCandidateValue(request.resolved),\n limits: immutableCandidateValue(request.limits),\n maxCostUsdNanos: usdToNanos(request.limits.maxCostUsd, 'reserved maxCostUsd'),\n activation: 'reserved',\n })\n }\n return reservation\n },\n\n activateGrant: async (input) => {\n pruneExpiredState(reservations, recentSettlements, Date.now())\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n if (recentSettlements.has(key)) throw new Error('protected model grant is already settled')\n const state = reservations.get(key)\n if (!state) throw new Error('protected model grant was not reserved by this port')\n assertGrantIdentity(state, request)\n if (state.settlementDigest) throw new Error('protected model grant is already settled')\n if (state.activation !== 'reserved') {\n throw new Error('protected model grant activation is single-use')\n }\n if (!Number.isSafeInteger(request.deadlineAtMs) || request.deadlineAtMs <= 0) {\n throw new Error('protected model activation deadline must be a positive safe integer')\n }\n if (request.deadlineAtMs <= Date.now()) {\n throw new Error('protected model activation deadline must be in the future')\n }\n if (request.deadlineAtMs > state.expiresAtMs) {\n throw new Error('protected model activation deadline exceeds the reserved expiry')\n }\n state.activation = 'activating'\n try {\n const activation = validateActivation(\n await options.client.activate(request),\n state.limits.maxModelCalls === 0 ? [] : activationEnvNames,\n )\n if (recentSettlements.has(key) || reservations.get(key) !== state) {\n throw new Error('protected model grant settled while activation was in flight')\n }\n state.activation = 'activated'\n return activation\n } catch (error) {\n state.activation = 'reserved'\n throw error\n }\n },\n\n settleGrant: async (input) => {\n const now = Date.now()\n pruneExpiredState(reservations, recentSettlements, now)\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n const state = reservations.get(key)\n if (state) assertGrantIdentity(state, request)\n const remembered = state ?? recentSettlements.get(key)\n if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {\n throw new Error('protected model settlement retry changed the termination reason')\n }\n\n const sealed = sealAgentCandidateModelSettlement(await options.client.settle(request), {\n preparationId: request.preparationId,\n grantDigest: request.grantDigest,\n model: request.resolved.model,\n })\n if (state) assertWithinReservedLimits(sealed.usage, state)\n\n const settlementDigest = canonicalCandidateDigest(sealed.value)\n if (remembered?.settlementDigest && remembered.settlementDigest !== settlementDigest) {\n throw new Error('protected model settlement retry returned a different final ledger')\n }\n if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {\n throw new Error('protected model settlement retry changed the termination reason')\n }\n const expiresAtMs = state?.expiresAtMs ?? now + RECOVERED_SETTLEMENT_RETENTION_MS\n if (state) {\n state.settlementDigest = settlementDigest\n state.settlementReason = request.reason\n }\n reservations.delete(key)\n rememberSettlement(recentSettlements, key, {\n settlementDigest,\n settlementReason: request.reason,\n expiresAtMs,\n })\n return sealed.value\n },\n }\n}\n\nfunction validateReserveInput(input: AgentCandidateModelGrantReserveInput): void {\n if (!Number.isSafeInteger(input.expiresAtMs) || input.expiresAtMs <= 0) {\n throw new Error('protected model reservation expiry must be a positive safe integer')\n }\n if (input.expiresAtMs <= Date.now()) {\n throw new Error('protected model reservation expiry must be in the future')\n }\n for (const [name, value] of [\n ['maxModelCalls', input.limits.maxModelCalls],\n ['maxInputTokens', input.limits.maxInputTokens],\n ['maxOutputTokens', input.limits.maxOutputTokens],\n ] as const) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`protected model reservation ${name} must be a nonnegative safe integer`)\n }\n }\n usdToNanos(input.limits.maxCostUsd, 'reserved maxCostUsd')\n}\n\nfunction validateReservation(\n value: unknown,\n expected: AgentCandidateModelGrantReserveInput,\n gatewayDomain: string,\n): AgentCandidateModelGrantReservation {\n const source = exactRecord(\n value,\n ['preparationId', 'digest', 'expiresAtMs', 'enforcedLimits', 'network'],\n 'protected model reservation response',\n )\n if (source.preparationId !== expected.preparationId) {\n throw new Error('protected model reservation response changed preparation identity')\n }\n if (!isSha256Digest(source.digest)) {\n throw new Error('protected model reservation response has an invalid digest')\n }\n if (source.expiresAtMs !== expected.expiresAtMs) {\n throw new Error('protected model reservation response changed expiry')\n }\n exactRecord(\n source.enforcedLimits,\n ['maxModelCalls', 'maxInputTokens', 'maxOutputTokens', 'maxCostUsd'],\n 'protected model reservation enforced limits',\n )\n if (\n canonicalCandidateDigest(source.enforcedLimits) !== canonicalCandidateDigest(expected.limits)\n ) {\n throw new Error('protected model reservation response changed enforced limits')\n }\n\n const network = validateReservationNetwork(\n source.network,\n expected.limits.maxModelCalls,\n gatewayDomain,\n )\n return immutableCandidateValue({\n preparationId: source.preparationId,\n digest: source.digest,\n expiresAtMs: source.expiresAtMs,\n enforcedLimits: source.enforcedLimits,\n network,\n }) as AgentCandidateModelGrantReservation\n}\n\nfunction validateReservationNetwork(\n value: unknown,\n maxModelCalls: number,\n gatewayDomain: string,\n): AgentCandidateModelAccessNetwork {\n if (maxModelCalls === 0) {\n const source = exactRecord(value, ['mode'], 'protected model reservation network')\n if (source.mode !== 'disabled') {\n throw new Error('zero-call protected model reservation must disable gateway access')\n }\n return { mode: 'disabled' }\n }\n\n const source = exactRecord(value, ['mode', 'domains'], 'protected model reservation network')\n if (source.mode !== 'gateway-only') {\n throw new Error('protected model reservation must allow only its model gateway')\n }\n if (\n !Array.isArray(source.domains) ||\n source.domains.length !== 1 ||\n source.domains[0] !== gatewayDomain\n ) {\n throw new Error('protected model reservation returned an unexpected gateway domain')\n }\n return { mode: 'gateway-only', domains: [gatewayDomain] }\n}\n\nfunction validateActivation(\n value: unknown,\n expectedNames: readonly string[],\n): AgentCandidateProtectedModelActivation {\n const source = exactRecord(value, ['env'], 'protected model activation response')\n const env = record(source.env, 'protected model activation environment')\n const actualNames = Object.keys(env).sort()\n if (\n actualNames.length !== expectedNames.length ||\n actualNames.some((name, index) => name !== expectedNames[index])\n ) {\n throw new Error('protected model activation returned unexpected environment names')\n }\n const detached: Record<string, string> = Object.create(null) as Record<string, string>\n for (const name of expectedNames) {\n const value = env[name]\n if (typeof value !== 'string' || value.length < 8 || value.length > 65_536) {\n throw new Error(`protected model activation ${name} must be a non-empty protected value`)\n }\n detached[name] = value\n }\n return Object.freeze({ env: Object.freeze(detached) })\n}\n\nfunction validateResolvedModel(\n value: unknown,\n expected: Parameters<AgentCandidateModelPort['resolve']>[0],\n): AgentCandidateResolvedModel {\n const source = exactRecord(\n value,\n ['requested', 'provider', 'model', 'snapshot', 'reasoningEffort'],\n 'resolved candidate model',\n )\n if (source.requested !== expected.requested) {\n throw new Error('model resolver changed the evaluator-owned request')\n }\n if (source.reasoningEffort !== expected.reasoningEffort) {\n throw new Error('model resolver changed the evaluator-owned reasoning effort')\n }\n for (const name of ['requested', 'provider', 'model', 'snapshot'] as const) {\n if (typeof source[name] !== 'string' || source[name].length === 0) {\n throw new Error(`resolved candidate model ${name} must be non-empty`)\n }\n }\n return source as unknown as AgentCandidateResolvedModel\n}\n\nfunction assertGrantIdentity(\n expected: RememberedReservation,\n actual: AgentCandidateModelGrantActivateInput | AgentCandidateModelGrantSettleInput,\n): void {\n if (\n actual.executionId !== expected.executionId ||\n actual.preparationId !== expected.preparationId ||\n actual.grantDigest !== expected.grantDigest ||\n canonicalCandidateDigest(actual.resolved) !== canonicalCandidateDigest(expected.resolved)\n ) {\n throw new Error('protected model grant input does not match its immutable reservation')\n }\n}\n\nfunction assertWithinReservedLimits(\n usage: {\n modelCalls: number\n inputTokens: number\n outputTokens: number\n costUsdNanos: number\n },\n reservation: RememberedReservation,\n): void {\n for (const [name, actual, limit] of [\n ['model calls', usage.modelCalls, reservation.limits.maxModelCalls],\n ['input tokens', usage.inputTokens, reservation.limits.maxInputTokens],\n ['output tokens', usage.outputTokens, reservation.limits.maxOutputTokens],\n ['cost USD nanos', usage.costUsdNanos, reservation.maxCostUsdNanos],\n ] as const) {\n if (actual > limit) {\n throw new Error(`protected model settlement ${name} ${actual} exceeds reserved ${limit}`)\n }\n }\n}\n\nfunction exactEnvironmentNames(values: readonly string[]): readonly string[] {\n if (values.length === 0) {\n throw new Error('protected model activation environment names must not be empty')\n }\n const names = [...values].sort()\n if (new Set(names).size !== names.length) {\n throw new Error('protected model activation environment names must be unique')\n }\n for (const name of names) {\n if (\n !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ||\n ['__proto__', 'constructor', 'prototype'].includes(name)\n ) {\n throw new Error(`protected model activation environment name is invalid: ${name}`)\n }\n }\n return Object.freeze(names)\n}\n\nfunction assertGatewayDomain(value: string): string {\n if (\n value.length > 253 ||\n value !== value.toLowerCase() ||\n value.endsWith('.') ||\n value.includes(':') ||\n value === 'localhost' ||\n value.endsWith('.localhost') ||\n value === 'metadata.google' ||\n value === 'metadata.google.internal'\n ) {\n throw new Error('protected model gateway must be an exact lowercase public DNS name')\n }\n const labels = value.split('.')\n if (\n labels.length < 2 ||\n !labels.every(\n (label) =>\n label.length >= 1 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label),\n ) ||\n !/[a-z]/.test(labels.at(-1) ?? '')\n ) {\n throw new Error('protected model gateway must be an exact lowercase public DNS name')\n }\n return value\n}\n\nfunction reservationKey(executionId: string, preparationId: string): string {\n return canonicalCandidateDigest({ executionId, preparationId })\n}\n\nfunction pruneExpiredState(\n reservations: Map<string, RememberedReservation>,\n settlements: Map<string, RememberedSettlement>,\n now: number,\n): void {\n for (const [key, value] of reservations) {\n if (value.expiresAtMs <= now) reservations.delete(key)\n }\n for (const [key, value] of settlements) {\n if (value.expiresAtMs <= now) settlements.delete(key)\n }\n}\n\nfunction rememberSettlement(\n settlements: Map<string, RememberedSettlement>,\n key: string,\n value: RememberedSettlement,\n): void {\n settlements.delete(key)\n settlements.set(key, value)\n while (settlements.size > MAX_RECENT_SETTLEMENTS) {\n const oldest = settlements.keys().next().value\n if (oldest === undefined) return\n settlements.delete(oldest)\n }\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value)\n}\n\nfunction exactRecord(\n value: unknown,\n keys: readonly string[],\n label: string,\n): Record<string, unknown> {\n const source = record(value, label)\n assertExactObjectKeys(source, keys, label)\n return source\n}\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must be a plain object`)\n }\n return value as Record<string, unknown>\n}\n","import type { TraceStore } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateExecutionPlanMaterial,\n AgentCandidateMaterializationReceipt,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateExecutionPlanMaterialSchema,\n agentCandidateMaterializationReceiptSchema,\n} from '@tangle-network/agent-interface'\n\nimport { readVerifiedArtifact } from './artifacts'\nimport type {\n AgentCandidateExecutionAttemptRef,\n AgentCandidateExecutionClaim,\n AgentCandidateExecutionClaimStore,\n AgentCandidateExecutionFinishResult,\n} from './claim'\nimport {\n candidateCleanupDeadline,\n candidateCleanupTimeout,\n withinCandidateCleanupDeadline,\n} from './cleanup'\nimport { canonicalCandidateBytes } from './digest'\nimport { sealAgentCandidateExecutorStopAcknowledgement } from './executor-capture'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport { persistCandidateModelSettlementEvidence } from './outcome-evidence'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport { RecoveryAgentCandidateTraceStore } from './protected-trace-store'\nimport type {\n AgentCandidateExecutionPorts,\n AgentCandidateExecutorPort,\n AgentCandidateOutputArtifactPort,\n} from './types'\n\nexport interface RecoverExpiredAgentCandidateOptions {\n attempt: AgentCandidateExecutionAttemptRef\n claimStore: AgentCandidateExecutionClaimStore\n executor: AgentCandidateExecutorPort\n traceStore: TraceStore\n ports: Pick<AgentCandidateExecutionPorts, 'models' | 'memory'>\n outputArtifacts: AgentCandidateOutputArtifactPort\n cleanupTimeoutMs?: number\n /** Evaluator clock; must be the same clock used by the claim store. */\n now?: () => number\n}\n\n/** Close an expired crashed attempt from persisted non-secret handles, then record failure. */\nexport async function recoverExpiredAgentCandidateExecution(\n options: RecoverExpiredAgentCandidateOptions,\n): Promise<AgentCandidateExecutionFinishResult> {\n const record = await options.claimStore.getAttempt(options.attempt)\n if (!record) throw new Error('candidate execution recovery attempt is missing')\n if (record.terminal) {\n return Object.freeze({ finished: false, terminal: record.terminal, exactReplay: true })\n }\n const cleanupTimeoutMs = candidateCleanupTimeout(\n options.cleanupTimeoutMs ?? record.claim.cleanup.cleanupTimeoutMs,\n )\n if (cleanupTimeoutMs > record.claim.cleanup.cleanupTimeoutMs) {\n throw new Error('recovery cleanup timeout exceeds the frozen preparation bound')\n }\n\n const now = options.now ?? Date.now\n if (now() < record.claim.leaseExpiresAtMs) {\n throw new Error('candidate execution lease has not expired')\n }\n\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const recoveryTraceStore = new RecoveryAgentCandidateTraceStore(options.traceStore)\n const preparation = withinCandidateCleanupDeadline(\n () => readRecoveryPreparation(record.claim, options.outputArtifacts),\n cleanupDeadlineAtMs,\n 'expired candidate preparation evidence read',\n )\n const processClosure = withinCandidateCleanupDeadline(\n async (cleanupSignal) => {\n const stopped = await options.executor.stop(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n {\n traceStore: recoveryTraceStore,\n reason: 'failed',\n signal: cleanupSignal,\n deadlineAtMs: cleanupDeadlineAtMs,\n },\n )\n sealAgentCandidateExecutorStopAcknowledgement(stopped)\n if (options.executor.dispose) {\n const disposed = await options.executor.dispose(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n { signal: cleanupSignal },\n )\n if (disposed.disposed !== true || Object.keys(disposed).some((key) => key !== 'disposed')) {\n throw new Error('expired candidate executor did not acknowledge resource disposal')\n }\n }\n return { stopped: true as const }\n },\n cleanupDeadlineAtMs,\n 'expired candidate process termination',\n )\n\n const modelClosure = withinCandidateCleanupDeadline(\n async () =>\n sealAgentCandidateModelSettlement(\n await options.ports.models.settleGrant({\n executionId: record.claim.executionId,\n preparationId: record.claim.cleanup.preparationId,\n grantDigest: record.claim.cleanup.modelGrantDigest,\n resolved: record.claim.cleanup.resolvedModel,\n reason: 'failed',\n }),\n {\n preparationId: record.claim.cleanup.preparationId,\n grantDigest: record.claim.cleanup.modelGrantDigest,\n model: record.claim.cleanup.resolvedModel.model,\n },\n ),\n cleanupDeadlineAtMs,\n 'expired candidate model settlement',\n )\n\n const memoryClosure = record.claim.cleanup.memory\n ? withinCandidateCleanupDeadline(\n async () => {\n const memory = record.claim.cleanup.memory\n if (!memory) throw new Error('expired candidate memory handle is missing')\n const closed = await options.ports.memory.close({\n executionId: record.claim.executionId,\n preparationId: record.claim.cleanup.preparationId,\n accessDigest: memory.accessDigest,\n effectiveNamespace: memory.effectiveNamespace,\n reason: 'failed',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('expired candidate memory did not acknowledge closure')\n }\n return { closed: true as const }\n },\n cleanupDeadlineAtMs,\n 'expired candidate memory closure',\n )\n : undefined\n\n const closureOutcomes = Promise.allSettled([\n modelClosure,\n memoryClosure ?? Promise.resolve(undefined),\n ] as const)\n const [preparationOutcome, processOutcome] = await Promise.allSettled([\n preparation,\n processClosure,\n ] as const)\n const failures: unknown[] = [preparationOutcome, processOutcome]\n .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n .map((outcome) => outcome.reason)\n const [modelOutcome, memoryOutcome] = await closureOutcomes\n for (const outcome of [modelOutcome, memoryOutcome]) {\n if (outcome.status === 'rejected') failures.push(outcome.reason)\n }\n if (failures.length > 0) {\n throw new AggregateError(failures, 'expired candidate cleanup could not be proven')\n }\n\n if (modelOutcome.status !== 'fulfilled') {\n throw new Error('expired candidate model settlement was not recovered')\n }\n const model = modelOutcome.value\n const modelSettlement = await withinCandidateCleanupDeadline(\n () =>\n persistCandidateModelSettlementEvidence(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n resolvedModel: record.claim.cleanup.resolvedModel,\n },\n model,\n options.outputArtifacts,\n ),\n cleanupDeadlineAtMs,\n 'expired candidate model-settlement persistence',\n )\n const failureClass =\n record.phase === 'claimed' && model.usage.modelCalls === 0\n ? 'pre-model-infrastructure'\n : 'unknown'\n const failureEvidence = await withinCandidateCleanupDeadline(\n () =>\n persistCandidateOutputArtifact(options.outputArtifacts, {\n executionId: record.claim.executionId,\n purpose: 'failure-evidence',\n bytes: canonicalCandidateBytes({\n kind: 'agent-candidate-recovery-failure',\n executionId: record.claim.executionId,\n attempt: record.claim.attempt,\n bundleDigest: record.claim.bundleDigest,\n executionPlanDigest: record.claim.executionPlanDigest,\n materializationReceiptDigest:\n record.claim.preparationEvidence.materializationReceipt.sha256,\n failureClass,\n processStopped: true,\n modelSettlementDigest: modelSettlement.digest,\n memoryClosed: record.claim.cleanup.memory !== undefined,\n }),\n }),\n cleanupDeadlineAtMs,\n 'expired candidate failure-evidence persistence',\n )\n const memory = record.claim.cleanup.memory\n return await options.claimStore.recoverExpired(options.attempt, {\n failureClass,\n usage: model.usage,\n modelSettlement: modelSettlement.artifact,\n failureEvidence,\n process: {\n stopped: true,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n model: {\n closed: true,\n preparationId: record.claim.cleanup.preparationId,\n grantDigest: record.claim.cleanup.modelGrantDigest,\n },\n ...(memory\n ? {\n memory: {\n closed: true,\n preparationId: record.claim.cleanup.preparationId,\n accessDigest: memory.accessDigest,\n effectiveNamespace: memory.effectiveNamespace,\n },\n }\n : {}),\n })\n}\n\nasync function readRecoveryPreparation(\n claim: AgentCandidateExecutionClaim,\n artifacts: AgentCandidateOutputArtifactPort,\n): Promise<{\n plan: AgentCandidateExecutionPlanMaterial\n receipt: AgentCandidateMaterializationReceipt\n}> {\n const [planBytes, receiptBytes] = await Promise.all([\n readVerifiedArtifact(claim.preparationEvidence.executionPlan, artifacts),\n readVerifiedArtifact(claim.preparationEvidence.materializationReceipt, artifacts),\n ])\n const plan = agentCandidateExecutionPlanMaterialSchema.parse(\n parseCanonicalBytes(planBytes, 'plan'),\n )\n if (claim.preparationEvidence.executionPlan.sha256 !== claim.executionPlanDigest) {\n throw new Error('recovery execution plan artifact does not match the claimed digest')\n }\n const receiptMaterial = parseCanonicalBytes(receiptBytes, 'materialization receipt')\n const receipt = agentCandidateMaterializationReceiptSchema.parse({\n ...receiptMaterial,\n digest: claim.preparationEvidence.materializationReceipt.sha256,\n })\n if (\n receipt.bundleDigest !== claim.bundleDigest ||\n receipt.executionPlan.digest !== claim.executionPlanDigest ||\n plan.runCell.bundleDigest !== claim.bundleDigest ||\n plan.executionId !== claim.executionId\n ) {\n throw new Error('recovery preparation evidence does not match the durable claim')\n }\n return { plan, receipt }\n}\n\nfunction parseCanonicalBytes(bytes: Uint8Array, label: string): Record<string, unknown> {\n let parsed: unknown\n try {\n parsed = JSON.parse(Buffer.from(bytes).toString('utf8'))\n } catch (error) {\n throw new Error(`candidate recovery ${label} is not JSON`, { cause: error })\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`candidate recovery ${label} must be an object`)\n }\n if (!Buffer.from(canonicalCandidateBytes(parsed)).equals(Buffer.from(bytes))) {\n throw new Error(`candidate recovery ${label} bytes are not canonical`)\n }\n return parsed as Record<string, unknown>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,yBAAyB;AAuE3B,SAAS,0BACd,OAC6C;AAC7C,QAAM,SAAoC;AAAA,IACxC,MAAM;AAAA,IACN,iBAAiB;AAAA,IACjB,SAAS,wBAAwB,MAAM,O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MAAM,CAAC;AAAA,EACzD,SAAS,OAAO;AACd,UAAM,IAAI,MAAM,sBAAsB,KAAK,gBAAgB,EAAE,OAAO,MAAM,CAAC;AAAA,EAC7E;AACA,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GAAG;AAClE,UAAM,IAAI,MAAM,sBAAsB,KAAK,oBAAoB;AAAA,EACjE;AACA,MAAI,CAAC,OAAO,KAAK,wBAAwB,MAAM,CAAC,EAAE,OAAO,OAAO,KAAK,KAAK,CAAC,GAAG;AAC5E,UAAM,IAAI,MAAM,sBAAsB,KAAK,0BAA0B;AAAA,EACvE;AACA,SAAO;AACT;","names":["record","winner","source","value","record","memory"]}
|
package/dist/chunk-IMSNJSXH.js
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
// src/durable/spawn-journal.ts
|
|
2
|
-
import { createHash } from "crypto";
|
|
3
|
-
function contentAddress(artifact) {
|
|
4
|
-
const hex = createHash("sha256").update(stableStringify(artifact), "utf-8").digest("hex");
|
|
5
|
-
return `sha256:${hex}`;
|
|
6
|
-
}
|
|
7
|
-
function stableStringify(value) {
|
|
8
|
-
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
9
|
-
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
10
|
-
const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
11
|
-
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
|
|
12
|
-
}
|
|
13
|
-
var InMemoryResultBlobStore = class {
|
|
14
|
-
blobs = /* @__PURE__ */ new Map();
|
|
15
|
-
async put(outRef, artifact) {
|
|
16
|
-
assertContentAddress(outRef, artifact);
|
|
17
|
-
this.blobs.set(outRef, artifact);
|
|
18
|
-
}
|
|
19
|
-
async get(outRef) {
|
|
20
|
-
return this.blobs.has(outRef) ? this.blobs.get(outRef) : void 0;
|
|
21
|
-
}
|
|
22
|
-
};
|
|
23
|
-
function assertContentAddress(outRef, artifact) {
|
|
24
|
-
const expected = contentAddress(artifact);
|
|
25
|
-
if (outRef !== expected) {
|
|
26
|
-
throw new Error(
|
|
27
|
-
`blob outRef '${outRef}' does not match the artifact content hash '${expected}'; a content-addressed store refuses a mismatched ref (breaks the replay invariant)`
|
|
28
|
-
);
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
var InMemorySpawnJournal = class {
|
|
32
|
-
trees = /* @__PURE__ */ new Map();
|
|
33
|
-
async loadTree(root) {
|
|
34
|
-
const tree = this.trees.get(root);
|
|
35
|
-
if (!tree) return void 0;
|
|
36
|
-
return tree.events.map((ev) => ({ ...ev }));
|
|
37
|
-
}
|
|
38
|
-
async beginTree(root, at) {
|
|
39
|
-
const existing = this.trees.get(root);
|
|
40
|
-
if (existing) {
|
|
41
|
-
if (existing.begunAt !== at) {
|
|
42
|
-
throw new Error(
|
|
43
|
-
`spawn tree '${root}' already begun at ${existing.begunAt}; refusing to overwrite with ${at}`
|
|
44
|
-
);
|
|
45
|
-
}
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
this.trees.set(root, { begunAt: at, events: [] });
|
|
49
|
-
}
|
|
50
|
-
async appendEvent(root, ev) {
|
|
51
|
-
const tree = this.trees.get(root);
|
|
52
|
-
if (!tree) {
|
|
53
|
-
throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`);
|
|
54
|
-
}
|
|
55
|
-
assertSeqUnique(root, tree.events, ev);
|
|
56
|
-
tree.events.push({ ...ev });
|
|
57
|
-
}
|
|
58
|
-
};
|
|
59
|
-
function assertSeqUnique(root, events, ev) {
|
|
60
|
-
if (ev.kind === "spawned" || ev.kind === "metered") return;
|
|
61
|
-
if (events.some((e) => e.kind !== "spawned" && e.kind !== "metered" && e.seq === ev.seq)) {
|
|
62
|
-
throw new Error(
|
|
63
|
-
`spawn journal corrupted: duplicate cursor seq ${ev.seq} in tree '${root}'; the cursor order replay relies on is not unique`
|
|
64
|
-
);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export {
|
|
69
|
-
contentAddress,
|
|
70
|
-
InMemoryResultBlobStore,
|
|
71
|
-
InMemorySpawnJournal
|
|
72
|
-
};
|
|
73
|
-
//# sourceMappingURL=chunk-IMSNJSXH.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/durable/spawn-journal.ts"],"sourcesContent":["/**\n *\n * Event-sourced spawn journal for the recursive execution atom (build steps 3 + 7).\n *\n * The supervision tree is journaled as an append-only event log: every `spawned`,\n * `settled`, and `cancelled` is recorded AFTER it is observed-committed (never\n * speculative), mirroring `ConversationJournal`'s begin/append/load shape. The log\n * holds only the THIN decision record — ids, parentage, budget, the spend a decision\n * consumed, and a content-addressed `outRef`. The payloads the driver branched on\n * (the `out` artifacts) live in a separate `ResultBlobStore`, keyed by `outRef`, so\n * the journal stays small (decisions) and replay rehydrates the exact `Settled` from\n * the blob store (evidence). This is the decision/payload split the replay argument\n * rests on (B1/B2).\n *\n * Replay determinism (B2): `seq` is the monotonic cursor order `scope.next()` yielded\n * each settlement — NOT wall-clock. `replaySpawnTree` sorts strictly by `seq` before\n * touching the blob store, so the order in which rehydration `get`s resolve can never\n * reorder the replayed `Settled[]`; the result is identical regardless of blob latency.\n *\n * @experimental\n */\n\nimport { createHash } from 'node:crypto'\nimport type {\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ResultBlobStore,\n Runtime,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\n TreeView,\n} from '../runtime/supervise/types'\nimport { zeroTokenUsage } from '../runtime/util'\n\n// ── Content addressing ──────────────────────────────────────────────────────\n\n/**\n * Mint the content-addressed `outRef` for a result artifact: `sha256:<hex>` over a\n * stable JSON encoding. Producers call this to derive the `outRef` they journal and\n * `put`; the FS/in-mem stores re-derive it on `put` to verify the supplied ref\n * matches (fail loud on a mismatch — a forged ref breaks the replay invariant).\n *\n * Stable encoding: object keys are sorted recursively so two structurally-equal\n * artifacts hash identically regardless of key insertion order.\n */\nexport function contentAddress(artifact: unknown): string {\n const hex = createHash('sha256').update(stableStringify(artifact), 'utf-8').digest('hex')\n return `sha256:${hex}`\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n\n// ── Result blob store ─────────────────────────────────────────────────────────\n\n/**\n * In-memory `ResultBlobStore`. Content-addressed: `put` verifies the supplied\n * `outRef` matches the artifact's hash so a stale/forged ref fails loud rather than\n * silently rehydrating the wrong payload. Idempotent on an identical re-put.\n */\nexport class InMemoryResultBlobStore implements ResultBlobStore {\n private readonly blobs = new Map<string, unknown>()\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n this.blobs.set(outRef, artifact)\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n return this.blobs.has(outRef) ? this.blobs.get(outRef) : undefined\n }\n}\n\n/**\n * FS `ResultBlobStore`. One JSON file per artifact under `dir`, named by a\n * filesystem-safe encoding of the `outRef` (`sha256:<hex>` → `sha256-<hex>.json`).\n * `put` fsyncs so a crash between writes never loses an acknowledged blob.\n */\nexport class FileResultBlobStore implements ResultBlobStore {\n constructor(private readonly dir: string) {}\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n assertContentAddress(outRef, artifact)\n const fs = await import('node:fs/promises')\n await fs.mkdir(this.dir, { recursive: true })\n const fh = await fs.open(this.blobPath(outRef), 'w')\n try {\n await fh.write(JSON.stringify(artifact))\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.blobPath(outRef), 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n return JSON.parse(text)\n }\n\n private blobPath(outRef: string): string {\n return `${this.dir}/${outRef.replace(/:/g, '-')}.json`\n }\n}\n\nfunction assertContentAddress(outRef: string, artifact: unknown): void {\n const expected = contentAddress(artifact)\n if (outRef !== expected) {\n throw new Error(\n `blob outRef '${outRef}' does not match the artifact content hash '${expected}'; ` +\n 'a content-addressed store refuses a mismatched ref (breaks the replay invariant)',\n )\n }\n}\n\n// ── Spawn journal ──────────────────────────────────────────────────────────────\n\n/**\n * In-memory `SpawnJournal`. Appends are observed-committed only; the impl enforces\n * the corruption guards a durable replay rests on:\n * - an event before `beginTree` is a corrupted tree (fail loud),\n * - a duplicate `seq` within a tree is a corrupted cursor (fail loud) — two\n * settlements cannot share the cursor position replay orders by.\n */\nexport class InMemorySpawnJournal implements SpawnJournal {\n private readonly trees = new Map<NodeId, { begunAt: string; events: SpawnEvent[] }>()\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const tree = this.trees.get(root)\n if (!tree) return undefined\n return tree.events.map((ev) => ({ ...ev }))\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = this.trees.get(root)\n if (existing) {\n if (existing.begunAt !== at) {\n throw new Error(\n `spawn tree '${root}' already begun at ${existing.begunAt}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n this.trees.set(root, { begunAt: at, events: [] })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const tree = this.trees.get(root)\n if (!tree) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, tree.events, ev)\n tree.events.push({ ...ev })\n }\n}\n\n/**\n * JSONL on disk. One line per record: the first record is `begin`, subsequent records\n * are `event` envelopes wrapping a `SpawnEvent`. `loadTree` replays the whole file,\n * filtering by `root`, and applies the same begin-precedes-events + unique-seq\n * corruption guards as the in-memory impl. Each append fsyncs so a crash between\n * writes never loses an acknowledged event.\n */\nexport class FileSpawnJournal implements SpawnJournal {\n constructor(private readonly path: string) {}\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n let begun = false\n const events: SpawnEvent[] = []\n for (const line of lines) {\n const record = JSON.parse(line) as SpawnJournalRecord\n if (record.root !== root) continue\n if (record.kind === 'begin') {\n begun = true\n } else {\n if (!begun) {\n throw new Error(\n `spawn journal corrupted: event for tree '${root}' precedes its begin record`,\n )\n }\n assertSeqUnique(root, events, record.event)\n events.push(record.event)\n }\n }\n return begun ? events : undefined\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n const existing = await this.loadTreeBegin(root)\n if (existing) {\n if (existing !== at) {\n throw new Error(\n `spawn tree '${root}' already begun in ${this.path} at ${existing}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n await this.appendRecord({ kind: 'begin', root, at })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const events = await this.loadTree(root)\n if (events === undefined) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n assertSeqUnique(root, events, ev)\n await this.appendRecord({ kind: 'event', root, event: ev })\n }\n\n private async loadTreeBegin(root: NodeId): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n let text: string\n try {\n text = await fs.readFile(this.path, 'utf8')\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const lines = text.split('\\n').filter((line) => line.length > 0)\n for (const line of lines) {\n const record = JSON.parse(line) as SpawnJournalRecord\n if (record.root === root && record.kind === 'begin') return record.at\n }\n return undefined\n }\n\n private async appendRecord(record: SpawnJournalRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const fh = await fs.open(this.path, 'a')\n try {\n await fh.write(`${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\ntype SpawnJournalRecord =\n | { kind: 'begin'; root: NodeId; at: string }\n | { kind: 'event'; root: NodeId; event: SpawnEvent }\n\n/**\n * Two `seq` namespaces share the journal: a `spawned` event's `seq` is the spawn ordinal\n * (the order children were created), and a `settled`/`cancelled` event's `seq` is the\n * monotonic CURSOR order `scope.next()` yielded that settlement (B2). The uniqueness\n * replay rests on is the cursor namespace — two settlements cannot share the position\n * replay orders by — so the guard checks only settled/cancelled events. A `spawned`\n * ordinal legitimately equals a later `settled` cursor seq and is not a collision.\n */\nfunction assertSeqUnique(root: NodeId, events: SpawnEvent[], ev: SpawnEvent): void {\n // `spawned` (ordinal namespace) and `metered` (informational spend, no settlement order) live\n // outside the cursor-uniqueness namespace replay relies on.\n if (ev.kind === 'spawned' || ev.kind === 'metered') return\n if (events.some((e) => e.kind !== 'spawned' && e.kind !== 'metered' && e.seq === ev.seq)) {\n throw new Error(\n `spawn journal corrupted: duplicate cursor seq ${ev.seq} in tree '${root}'; ` +\n 'the cursor order replay relies on is not unique',\n )\n }\n}\n\n// ── Replay executor (build step 7) ───────────────────────────────────────────────\n\n/**\n * Re-feed a journaled spawn tree in strict `seq` order, rehydrating each settled\n * child's `out` from the blob store by `outRef`, and return the `Settled[]` exactly\n * as `scope.next()` originally delivered them.\n *\n * Determinism (B2): the events are sorted by `seq` BEFORE any blob `get`, so the\n * replay order is the recorded cursor order regardless of how fast each rehydration\n * resolves. `at` (wall-clock) is never a replay input. Fail loud on a tree that was\n * never begun, a settled-done event missing its `outRef`, or a blob the store can't\n * rehydrate — a silent gap would let `act` branch on the wrong evidence.\n */\nexport async function replaySpawnTree(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n): Promise<Settled<unknown>[]> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`replaySpawnTree: no journaled tree for root '${root}'`)\n }\n const ordered = [...events].sort((a, b) => a.seq - b.seq)\n const labels = new Map<NodeId, string>()\n for (const ev of ordered) {\n if (ev.kind === 'spawned') labels.set(ev.id, ev.label)\n }\n const settled: Settled<unknown>[] = []\n for (const ev of ordered) {\n if (ev.kind === 'spawned') continue\n if (ev.kind === 'metered') continue // a spend record, not a settlement — irrelevant to replay\n if (ev.kind === 'cancelled') {\n settled.push({\n kind: 'down',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'cancelled'),\n reason: ev.reason,\n infra: false,\n restartCount: 0,\n seq: ev.seq,\n })\n continue\n }\n if (ev.status === 'down') {\n settled.push({\n kind: 'down',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'failed'),\n reason: ev.verdict?.notes ?? 'child down',\n infra: ev.infra === true,\n restartCount: 0,\n seq: ev.seq,\n })\n continue\n }\n if (ev.outRef === undefined) {\n throw new Error(\n `replaySpawnTree: settled-done event for '${ev.id}' (seq ${ev.seq}) has no outRef; ` +\n 'cannot rehydrate the result the driver branched on',\n )\n }\n const out = await blobs.get(ev.outRef)\n if (out === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no artifact for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n settled.push({\n kind: 'done',\n handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, 'done'),\n out,\n outRef: ev.outRef,\n verdict: ev.verdict,\n spent: ev.spent,\n seq: ev.seq,\n })\n }\n return settled\n}\n\nfunction replayHandle(id: NodeId, label: string, status: NodeStatus) {\n return {\n id,\n label,\n status,\n abort() {\n throw new Error(`cannot abort node '${id}': replayed handles are terminal, not live`)\n },\n }\n}\n\n/**\n * Materialize a recorded `TreeView` from a journaled event list for inspection. Folds\n * `spawned`/`settled`/`cancelled` into a per-node snapshot in `seq` order, then adds each\n * `metered` event's driver-inference spend onto its node in a separate additive pass so the view\n * matches the recorded cursor. It does not recover live executors or driver state after restart.\n */\nexport function materializeTreeView(events: SpawnEvent[]): TreeView {\n const nodes = new Map<NodeId, MutableSnapshot>()\n let root: NodeId | undefined\n // `spawned` (ordinal namespace) and `settled`/`cancelled` (cursor namespace) carry\n // overlapping `seq` values, so create every node before any update — process spawns in\n // ordinal order, then settlements/cancellations in cursor order. A settle/cancel for an\n // un-spawned node is a corrupted log (fail loud via requireNode).\n const spawns = events\n .filter((ev): ev is Extract<SpawnEvent, { kind: 'spawned' }> => ev.kind === 'spawned')\n .sort((a, b) => a.seq - b.seq)\n const settlements = events\n .filter((ev) => ev.kind !== 'spawned' && ev.kind !== 'metered')\n .sort((a, b) => a.seq - b.seq)\n for (const ev of spawns) {\n if (ev.parent === undefined && root === undefined) root = ev.id\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'pending',\n runtime: ev.runtime,\n budget: ev.budget,\n spent: zeroSpend(),\n })\n }\n for (const ev of settlements) {\n if (ev.kind === 'settled') {\n const node = requireNode(nodes, ev.id)\n node.status = ev.status === 'done' ? 'done' : 'failed'\n node.spent = ev.spent\n node.outRef = ev.outRef\n } else {\n const node = requireNode(nodes, ev.id)\n node.status = 'cancelled'\n }\n }\n // Driver inference: a separate pass so it accumulates ONTO the settled child-work base (no\n // dependence on metered-vs-settled seq order) without touching node status.\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n const node = requireNode(nodes, ev.id)\n node.spent = addJournalSpend(node.spent, ev.spend)\n }\n const snapshots = [...nodes.values()].map(freezeSnapshot)\n return {\n root: root ?? snapshots[0]?.id ?? '',\n nodes: snapshots,\n inFlight: snapshots.filter((n) => n.status === 'running' || n.status === 'acquiring').length,\n }\n}\n\ninterface MutableSnapshot {\n id: NodeId\n parent?: NodeId\n label: string\n status: NodeStatus\n runtime: Runtime\n budget: NodeSnapshot['budget']\n spent: Spend\n outRef?: string\n}\n\nfunction zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/** Add a `metered` spend record onto a node's accumulated spend (per channel). */\nfunction addJournalSpend(a: Spend, b: Spend): Spend {\n return {\n iterations: a.iterations + b.iterations,\n tokens: { input: a.tokens.input + b.tokens.input, output: a.tokens.output + b.tokens.output },\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ms: a.ms + b.ms,\n }\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableSnapshot>, id: NodeId): MutableSnapshot {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`)\n }\n return node\n}\n\nfunction freezeSnapshot(node: MutableSnapshot): NodeSnapshot {\n return {\n id: node.id,\n parent: node.parent,\n label: node.label,\n status: node.status,\n runtime: node.runtime,\n budget: node.budget,\n spent: node.spent,\n outRef: node.outRef,\n }\n}\n\nfunction isNoEntError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";AAsBA,SAAS,kBAAkB;AA0BpB,SAAS,eAAe,UAA2B;AACxD,QAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,gBAAgB,QAAQ,GAAG,OAAO,EAAE,OAAO,KAAK;AACxF,SAAO,UAAU,GAAG;AACtB;AAEA,SAAS,gBAAgB,OAAwB;AAC/C,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO,KAAK,UAAU,KAAK,KAAK;AACjF,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,IAAI,MAAM,IAAI,eAAe,EAAE,KAAK,GAAG,CAAC;AACzE,QAAM,UAAU,OAAO,QAAQ,KAAgC,EAC5D,OAAO,CAAC,CAAC,EAAE,CAAC,MAAM,MAAM,MAAS,EACjC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAO,IAAI,IAAI,KAAK,IAAI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