@tangle-network/agent-runtime 0.131.6 → 0.131.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/{activation-D-gsrgSq.js → activation-CDKatOlp.js} +3 -3
  2. package/dist/{activation-D-gsrgSq.js.map → activation-CDKatOlp.js.map} +1 -1
  3. package/dist/agent.d.ts +2 -2
  4. package/dist/agent.js +2 -2
  5. package/dist/analyst-loop.d.ts +1 -1
  6. package/dist/{authoring-DI778qK7.js → authoring-B-Oe8VUf.js} +2 -2
  7. package/dist/{authoring-DI778qK7.js.map → authoring-B-Oe8VUf.js.map} +1 -1
  8. package/dist/candidate-execution/index.js +4 -4
  9. package/dist/{candidate-execution-BNxKr-Bu.js → candidate-execution-DxL_I3xx.js} +4 -4
  10. package/dist/{candidate-execution-BNxKr-Bu.js.map → candidate-execution-DxL_I3xx.js.map} +1 -1
  11. package/dist/conversation.d.ts +1 -1
  12. package/dist/{environment-provider-CxvSd1W6.d.ts → environment-provider-DZihBZx6.d.ts} +3 -3
  13. package/dist/{environment-provider-Dyg8DtLK.js → environment-provider-mDsjfGjY.js} +2 -2
  14. package/dist/{environment-provider-Dyg8DtLK.js.map → environment-provider-mDsjfGjY.js.map} +1 -1
  15. package/dist/environment-provider.d.ts +1 -1
  16. package/dist/environment-provider.js +1 -1
  17. package/dist/{graph-CoN60QtH.js → graph-DOfL9TLn.js} +3 -3
  18. package/dist/{graph-CoN60QtH.js.map → graph-DOfL9TLn.js.map} +1 -1
  19. package/dist/{improvement-cycle-BGF0osPC.js → improvement-cycle-XtFD7dCv.js} +4 -4
  20. package/dist/{improvement-cycle-BGF0osPC.js.map → improvement-cycle-XtFD7dCv.js.map} +1 -1
  21. package/dist/{index-DwGtu9nc.d.ts → index-C-IJR7pR.d.ts} +4 -4
  22. package/dist/{index-CoO7atyo.d.ts → index-D7UJIX2x.d.ts} +3087 -3064
  23. package/dist/{index-qYHpsmG2.d.ts → index-qKm5g7mI.d.ts} +3 -3
  24. package/dist/index.d.ts +9 -9
  25. package/dist/index.js +12 -12
  26. package/dist/index.js.map +1 -1
  27. package/dist/intelligence.d.ts +5 -5
  28. package/dist/intelligence.js +6 -6
  29. package/dist/kernel.d.ts +7 -7
  30. package/dist/kernel.js +9 -9
  31. package/dist/{knowledge-D4zNvxw5.js → knowledge-DPDhKnOz.js} +5 -5
  32. package/dist/{knowledge-D4zNvxw5.js.map → knowledge-DPDhKnOz.js.map} +1 -1
  33. package/dist/knowledge.d.ts +1 -1
  34. package/dist/knowledge.js +1 -1
  35. package/dist/{loop-runner-bin-BwgZ8m_7.d.ts → loop-runner-bin-B6g4vOil.d.ts} +3 -3
  36. package/dist/{loop-runner-bin-CI9Y0sxT.js → loop-runner-bin-DCBho3GJ.js} +3 -3
  37. package/dist/{loop-runner-bin-CI9Y0sxT.js.map → loop-runner-bin-DCBho3GJ.js.map} +1 -1
  38. package/dist/loop-runner-bin.d.ts +1 -1
  39. package/dist/loop-runner-bin.js +1 -1
  40. package/dist/mcp/bin.js +3 -3
  41. package/dist/mcp/index.d.ts +5 -5
  42. package/dist/mcp/index.js +5 -5
  43. package/dist/{openai-tools-CupeHJEv.js → openai-tools-BeVFVJlX.js} +2 -2
  44. package/dist/{openai-tools-CupeHJEv.js.map → openai-tools-BeVFVJlX.js.map} +1 -1
  45. package/dist/{openai-tools-D3oMyVGl.d.ts → openai-tools-CzEiSbPW.d.ts} +2 -2
  46. package/dist/{prepare-DYWjVcPx.js → prepare-BQ82nG06.js} +2 -2
  47. package/dist/{prepare-DYWjVcPx.js.map → prepare-BQ82nG06.js.map} +1 -1
  48. package/dist/primeintellect/index.d.ts +1 -1
  49. package/dist/profiles.d.ts +1 -1
  50. package/dist/{protected-model-port-48ALLGxT.js → protected-model-port-BAOj4gQN.js} +2 -2
  51. package/dist/{protected-model-port-48ALLGxT.js.map → protected-model-port-BAOj4gQN.js.map} +1 -1
  52. package/dist/{redact-9_Gf-8m3.d.ts → redact-CwupS9H2.d.ts} +3 -3
  53. package/dist/{runtime-ZNVnT8h1.js → runtime-BVKEU5jc.js} +131 -28
  54. package/dist/runtime-BVKEU5jc.js.map +1 -0
  55. package/dist/{runtime-D-QfLbSd.d.ts → runtime-DgJZUxql.d.ts} +4 -4
  56. package/dist/{spawn-journal-saHQzqYi.js → spawn-journal-Cd5L-Ie9.js} +20 -9
  57. package/dist/spawn-journal-Cd5L-Ie9.js.map +1 -0
  58. package/dist/{stream-agent-turn-C852AgMT.d.ts → stream-agent-turn-DcDznEnq.d.ts} +3 -3
  59. package/dist/{structural-rollout-n089ZP33.js → structural-rollout-v8o_EO8_.js} +3 -3
  60. package/dist/{structural-rollout-n089ZP33.js.map → structural-rollout-v8o_EO8_.js.map} +1 -1
  61. package/dist/{supervise-msTRhTN7.js → supervise-DzLi985l.js} +24 -6
  62. package/dist/supervise-DzLi985l.js.map +1 -0
  63. package/dist/{supervisor-C16p9KqO.js → supervisor-CMtutocL.js} +92 -81
  64. package/dist/supervisor-CMtutocL.js.map +1 -0
  65. package/dist/testing.d.ts +2 -2
  66. package/dist/testing.js +12 -12
  67. package/dist/{types-ebIY0dMG.d.ts → types-6zHo67jn.d.ts} +13 -1
  68. package/dist/{types-C6Q-J0Dt.d.ts → types-CIg5DBNF.d.ts} +12 -3
  69. package/dist/{util-Bw6srryQ.js → util-Dr--8wAL.js} +32 -3
  70. package/dist/util-Dr--8wAL.js.map +1 -0
  71. package/dist/{workspace-archive-aOfJ47ms.js → workspace-archive-CGcXL3zA.js} +2 -2
  72. package/dist/{workspace-archive-aOfJ47ms.js.map → workspace-archive-CGcXL3zA.js.map} +1 -1
  73. package/package.json +4 -4
  74. package/dist/runtime-ZNVnT8h1.js.map +0 -1
  75. package/dist/spawn-journal-saHQzqYi.js.map +0 -1
  76. package/dist/supervise-msTRhTN7.js.map +0 -1
  77. package/dist/supervisor-C16p9KqO.js.map +0 -1
  78. package/dist/util-Bw6srryQ.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { a as ExecutorConfig } from "../runtime-D-QfLbSd.js";
1
+ import { a as ExecutorConfig } from "../runtime-DgJZUxql.js";
2
2
  import { RunRecord } from "@tangle-network/agent-eval";
3
3
  //#region src/primeintellect/types.d.ts
4
4
  type PrimeIntellectSplit = 'train' | 'eval';
@@ -1,4 +1,4 @@
1
- import { k as Validator, r as Driver, t as AgentRunSpec, w as OutputAdapter } from "./types-ebIY0dMG.js";
1
+ import { k as Validator, r as Driver, t as AgentRunSpec, w as OutputAdapter } from "./types-6zHo67jn.js";
2
2
  import { a as UiFindingSeverity, c as coderTaskToPrompt, i as UiFindingScreenshot, n as UI_LENSES, o as UiLens, r as UiFinding, s as CoderTask, t as UI_FINDING_SEVERITIES } from "./substrate-BcnuSHXm.js";
3
3
  import { AgentProfile } from "@tangle-network/agent-interface";
4
4
  import { SandboxEvent } from "@tangle-network/sandbox";
@@ -1,4 +1,4 @@
1
- import { W as assertExactObjectKeys, l as candidateKnowledgeExecutionPaths, lt as sha256Bytes, m as usdToNanos, nt as canonicalCandidateBytes, p as sealAgentCandidateModelSettlement, rt as canonicalCandidateDigest, st as immutableCandidateValue } from "./prepare-DYWjVcPx.js";
1
+ import { W as assertExactObjectKeys, l as candidateKnowledgeExecutionPaths, lt as sha256Bytes, m as usdToNanos, nt as canonicalCandidateBytes, p as sealAgentCandidateModelSettlement, rt as canonicalCandidateDigest, st as immutableCandidateValue } from "./prepare-BQ82nG06.js";
2
2
  import { posix } from "node:path";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  //#region src/candidate-execution/exact-process-executor.ts
@@ -719,4 +719,4 @@ function record(value, label) {
719
719
  //#endregion
720
720
  export { exactProcessProviderAsCandidateExecutor as n, createProtectedAgentCandidateModelPort as t };
721
721
 
722
- //# sourceMappingURL=protected-model-port-48ALLGxT.js.map
722
+ //# sourceMappingURL=protected-model-port-BAOj4gQN.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"protected-model-port-48ALLGxT.js","names":["isSha256Digest"],"sources":["../src/candidate-execution/exact-process-executor.ts","../src/candidate-execution/protected-model-port.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","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"],"mappings":";;;;AAgCA,MAAM,+BAA+B;AACrC,MAAM,gCAAgC,KAAK;;AA2B3C,SAAgB,wCACd,SAC4B;CAC5B,OAAO,IAAI,mCAAmC,OAAO;AACvD;AAEA,IAAM,qCAAN,MAA+E;CAShD;CAR7B,yBAA0B,IAAI,IAAkC;CAChE;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAgE;EAA/C,KAAA,UAAA;EAC3B,IAAI,CAAC,QAAQ,SAAS,c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AC,CAAC,KAAK,CAAC,CAAC;EACzC,IAAI,WAAW,KAAA,GAAW;EAC1B,YAAY,OAAO,MAAM;CAC3B;AACF;AAEA,SAAS,eAAe,OAAuC;CAC7D,OAAO,OAAO,UAAU,YAAY,wBAAwB,KAAK,KAAK;AACxE;AAEA,SAAS,YACP,OACA,MACA,OACyB;CACzB,MAAM,SAAS,OAAO,OAAO,KAAK;CAClC,sBAAsB,QAAQ,MAAM,KAAK;CACzC,OAAO;AACT;AAEA,SAAS,OAAO,OAAgB,OAAwC;CACtE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MAAM,GAAG,MAAM,mBAAmB;CAE9C,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,IAAI,cAAc,OAAO,aAAa,cAAc,MAClD,MAAM,IAAI,MAAM,GAAG,MAAM,wBAAwB;CAEnD,OAAO;AACT"}
1
+ {"version":3,"file":"protected-model-port-BAOj4gQN.js","names":["isSha256Digest"],"sources":["../src/candidate-execution/exact-process-executor.ts","../src/candidate-execution/protected-model-port.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","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"],"mappings":";;;;AAgCA,MAAM,+BAA+B;AACrC,MAAM,gCAAgC,KAAK;;AA2B3C,SAAgB,wCACd,SAC4B;CAC5B,OAAO,IAAI,mCAAmC,OAAO;AACvD;AAEA,IAAM,qCAAN,MAA+E;CAShD;CAR7B,yBAA0B,IAAI,IAAkC;CAChE;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAgE;EAA/C,KAAA,UAAA;EAC3B,IAAI,CAAC,QAAQ,SAAS,cACpB,MAAM,IAAI,MACR,+BAA+B,QAAQ,SAAS,KAAK,qCACvD;EAEF,KAAK,eAAe,QAAQ,SAAS;EACrC,KAAK,YAAY,eAAe,QAAQ,SAAS;EACjD,KAAK,qBAAqB,gBACxB,QAAQ,sBAAsB,8BAC9B,iCACF;EACA,KAAK,sBAAsB,gBACzB,QAAQ,uBAAuB,+BAC/B,kCACF;EACA,KAAK,kBAAkB,QAAQ,kBAC3B,wBAAwB,QAAQ,eAAe,IAC/C,KAAA;CACN;CAEA,MAAM,QACJ,SACA,SACA;EACA,uBAAuB,OAAO;EAC9B,MAAM,UAAU,QAAQ,UAAU,KAAK;EACvC,IAAI,QAAQ,SAAS,UAAU,MAAM,IAAI,MAAM,gDAAgD;EAC/F,MAAM,UAAU,QAAQ,cAAc,MAAM,SAAS,MAAM,OAAO;EAClE,MAAM,SACJ,QAAQ,SAAS,aACZ,EAAE,MAAM,UAAU,IAClB;GAAE,MAAM;GAAU,cAAc,CAAC,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ExecutorConfig } from "./runtime-D-QfLbSd.js";
2
- import { i as CollectedAgentTurn, r as AgentTurnUsage } from "./stream-agent-turn-C852AgMT.js";
1
+ import { a as ExecutorConfig } from "./runtime-DgJZUxql.js";
2
+ import { i as CollectedAgentTurn, r as AgentTurnUsage } from "./stream-agent-turn-DcDznEnq.js";
3
3
  import { CostLedgerHandle, MaximumCharge, ProposalFinding } from "@tangle-network/agent-eval";
4
4
  import { CampaignScenarioIdentity, CompareOptimizationMethodsOptions, OptimizationMethod, OptimizationMethodComparison, WorktreeAdapter } from "@tangle-network/agent-eval/campaign";
5
5
  import { AgentProfile as AgentProfile$1, HarnessType as HarnessType$1, ReasoningEffort, Sha256Digest } from "@tangle-network/agent-interface";
@@ -448,4 +448,4 @@ declare function defaultRedactor(value: unknown): unknown;
448
448
  declare function resolveRedactor(redact: Redactor | false | undefined): Redactor;
449
449
  //#endregion
450
450
  export { ImprovementCandidate as A, Verifier as B, ImproveProfileComponents as C, ImproveScenarioPartitions as D, ImproveRuntimeCodeGeneratorOptions as E, AgenticGeneratorExecutorForWorktree as F, CandidateGenerator as G, agenticGenerator as H, AgenticGeneratorOptions as I, AgenticGeneratorShotDisposition as L, ImprovementProfileCandidate as M, DeepReadonly as N, ImproveSkillsOptions as O, ReadonlyAgentProfile as P, AgenticGeneratorShotExecution as R, ImproveProfileAgent as S, ImproveResult as T, commandVerifier as U, VerifyResult as V, defaultBuildPrompt as W, ImproveMethodOptions as _, ImproveCandidateValidationInput as a, ImproveOptimizationRunOptions as b, ImproveCodeOptions as c, ImproveCost as d, ImproveCustomCodeGeneratorOptions as f, ImproveMethodLineage as g, ImproveMethodFactory as h, improve as i, ImprovementCodeCandidate as j, ImproveSurface as k, ImproveCodeResult as l, ImproveMethodContext as m, defaultRedactor as n, ImproveCandidateValidator as o, ImproveLineage as p, resolveRedactor as r, ImproveCodeBaseOptions as s, Redactor as t, ImproveCodeRunOptions as u, ImproveMethodResult as v, ImproveProfileSurface as w, ImproveOptions as x, ImproveMethodSource as y, AgenticGeneratorShotReceipt as z };
451
- //# sourceMappingURL=redact-9_Gf-8m3.d.ts.map
451
+ //# sourceMappingURL=redact-CwupS9H2.d.ts.map
@@ -1,18 +1,18 @@
1
1
  import { n as AnalystError, s as PlannerError, u as ValidationError } from "./errors-DEAvWQPy.js";
2
2
  import "./stream-agent-turn-DE8_alvm.js";
3
- import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore, v as isTraceAnalysisStore, x as contentAddress } from "./spawn-journal-saHQzqYi.js";
4
- import { a as randomSuffix, c as stringifySafe, f as zeroTokenUsage, r as isAbortError, s as sleep, t as addTokenUsage } from "./util-Bw6srryQ.js";
3
+ import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore, v as isTraceAnalysisStore, x as contentAddress } from "./spawn-journal-Cd5L-Ie9.js";
4
+ import { a as isAbortError, i as hasCompleteCacheBreakdown, l as sleep, m as zeroTokenUsage, n as cloneTokenUsage, s as randomSuffix, t as addTokenUsage, u as stringifySafe } from "./util-Dr--8wAL.js";
5
5
  import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction--F3v1oo8.js";
6
6
  import { a as notifySandboxEventObserver } from "./sandbox-events-CRDwc5WN.js";
7
7
  import { c as profileProviderModel, i as concreteModelId, s as profileModelExecutionSettings, t as assertExecutableAgentProfile } from "./model-policy-mWSoToiQ.js";
8
8
  import { v as executableAgentProfileSnapshot, y as executableAgentSpecSnapshot } from "./materialization-DBXuH34A.js";
9
- import { $ as createSandboxLineage, I as createWorktreeCliExecutor, N as createExecutor, P as createExecutorRegistry, Q as runAgentRounds, U as createPushTraceSource, Z as defaultSelectWinner, et as probeSandboxCapabilities, l as withDriverExecutor, m as settledToIteration, n as createSupervisor, nt as routerBrain, rt as runBrainLoop, w as rollingDispatch } from "./supervisor-C16p9KqO.js";
10
- import "./environment-provider-Dyg8DtLK.js";
9
+ import { $ as createSandboxLineage, I as createWorktreeCliExecutor, N as createExecutor, P as createExecutorRegistry, Q as runAgentRounds, U as createPushTraceSource, Z as defaultSelectWinner, et as probeSandboxCapabilities, l as withDriverExecutor, m as settledToIteration, n as createSupervisor, nt as routerBrain, rt as runBrainLoop, w as rollingDispatch } from "./supervisor-CMtutocL.js";
10
+ import "./environment-provider-mDsjfGjY.js";
11
11
  import { i as notifyRuntimeHookEvent } from "./runtime-hooks-C7iJOWm3.js";
12
- import { C as observe, O as strategyAuthorMethod, T as profileChatClient, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-n089ZP33.js";
13
- import { It as gateOnDeliverable, Lt as mapExecutorResult, n as supervise } from "./supervise-msTRhTN7.js";
14
- import "./authoring-DI778qK7.js";
15
- import "./graph-CoN60QtH.js";
12
+ import { C as observe, O as strategyAuthorMethod, T as profileChatClient, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-v8o_EO8_.js";
13
+ import { It as gateOnDeliverable, Lt as mapExecutorResult, n as supervise } from "./supervise-DzLi985l.js";
14
+ import "./authoring-B-Oe8VUf.js";
15
+ import "./graph-DOfL9TLn.js";
16
16
  import { CODING_HARNESSES, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
17
17
  import { heldoutSignificance, runProfileMatrix } from "@tangle-network/agent-eval/campaign";
18
18
  import { agentProfileSchema, canonicalAgentProfileDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
@@ -1036,14 +1036,122 @@ async function runLoopWithCampaignContext(opts, loopOptions, ctx, cost) {
1036
1036
  return (opts.toArtifact ?? ((r) => r.winner?.output))(result);
1037
1037
  }
1038
1038
  function loopCostReceipt(result, model) {
1039
+ return costReceiptFromUsage(result.tokenUsage, model, {
1040
+ usageUnknown: result.tokenUsage.tokensKnown === false,
1041
+ actualCostUsd: result.costUsdKnown !== false ? result.costUsd : void 0,
1042
+ costUnknown: result.costUsdKnown === false,
1043
+ estimatedCostUsd: result.estimatedCostUsd
1044
+ });
1045
+ }
1046
+ /** Map Runtime usage into Eval's canonical paid-call receipt without inventing cache classes. */
1047
+ function costReceiptFromUsage(usage, model, cost) {
1048
+ const cacheComplete = hasCompleteCacheBreakdown(usage) && (usage.freshInput !== void 0 || usage.cacheRead !== void 0 || usage.cacheWrite !== void 0);
1049
+ const cacheRead = cacheComplete ? usage.cacheRead ?? 0 : void 0;
1050
+ const cacheWrite = cacheComplete ? usage.cacheWrite ?? 0 : void 0;
1051
+ const classified = (cacheRead ?? 0) + (cacheWrite ?? 0);
1039
1052
  return {
1040
1053
  model,
1041
- inputTokens: result.tokenUsage.input,
1042
- outputTokens: result.tokenUsage.output,
1043
- ...result.tokenUsage.tokensKnown === false ? { usageUnknown: true } : {},
1044
- ...result.costUsdKnown !== false ? { actualCostUsd: result.costUsd } : {},
1045
- ...result.costUsdKnown === false ? { costUnknown: true } : {},
1046
- ...result.estimatedCostUsd !== void 0 ? { estimatedCostUsd: result.estimatedCostUsd } : {}
1054
+ inputTokens: cacheComplete ? usage.input - classified : usage.input,
1055
+ outputTokens: usage.output,
1056
+ ...cacheComplete ? {
1057
+ cachedTokens: cacheRead,
1058
+ cacheWriteTokens: cacheWrite
1059
+ } : {},
1060
+ ...usage.tokensKnown === false || cost.usageUnknown ? { usageUnknown: true } : {},
1061
+ ...cost.actualCostUsd !== void 0 ? { actualCostUsd: cost.actualCostUsd } : {},
1062
+ ...cost.costUnknown ? { costUnknown: true } : {},
1063
+ ...cost.estimatedCostUsd !== void 0 ? { estimatedCostUsd: cost.estimatedCostUsd } : {}
1064
+ };
1065
+ }
1066
+ /**
1067
+ * Eval has one pre-admitted paid call for this dispatch. A tree can only settle that one call when
1068
+ * Runtime can prove every visible leaf used the same model. Child identities come from Runtime's
1069
+ * materialization receipts. A router root is validated against its exact profile model before
1070
+ * Runtime accepts each response. A nested tree is not flattened in this result view, so it remains
1071
+ * unknown rather than being relabelled from its parent. A caller-supplied override would be false.
1072
+ */
1073
+ function supervisedTreeModel(result, rootProfile) {
1074
+ const models = /* @__PURE__ */ new Set();
1075
+ const rootModel = rootProfile.harness === void 0 || rootProfile.harness === "cli-base" ? rootProfile.model?.default : void 0;
1076
+ if (rootModel === void 0) return { kind: "unknown" };
1077
+ models.add(rootModel);
1078
+ let unknown = false;
1079
+ for (const node of result.tree.nodes) {
1080
+ if (node.ownedTreeRoot !== void 0) {
1081
+ unknown = true;
1082
+ continue;
1083
+ }
1084
+ const materialization = node.materialization;
1085
+ if (materialization?.status !== "known" || materialization.model.status !== "known") {
1086
+ unknown = true;
1087
+ continue;
1088
+ }
1089
+ models.add(materialization.model.id);
1090
+ }
1091
+ if (unknown || models.size === 0) return { kind: "unknown" };
1092
+ if (models.size !== 1) return {
1093
+ kind: "mixed",
1094
+ models: [...models].sort()
1095
+ };
1096
+ return {
1097
+ kind: "known",
1098
+ model: [...models][0]
1099
+ };
1100
+ }
1101
+ /** The Eval receipt surface has no pre-admitted per-model recursive-tree receipt bundle yet. */
1102
+ var SupervisedTreeModelIdentityError = class extends Error {
1103
+ constructor(identity) {
1104
+ const detail = identity.kind === "mixed" ? `multiple models (${identity.models.join(", ")})` : "an unknown materialized model";
1105
+ super(`superviseDispatch: cannot settle one Eval paid-call receipt for a tree with ${detail}`);
1106
+ this.name = "SupervisedTreeModelIdentityError";
1107
+ }
1108
+ };
1109
+ function unknownSupervisedTreeReceipt() {
1110
+ return {
1111
+ model: "unknown",
1112
+ inputTokens: 0,
1113
+ outputTokens: 0,
1114
+ usageUnknown: true,
1115
+ costUnknown: true
1116
+ };
1117
+ }
1118
+ /** Run one recursive supervised tree inside Eval's pre-execution paid-call lifecycle. */
1119
+ function superviseDispatch(opts) {
1120
+ return async (profile, scenario, ctx) => {
1121
+ const superviseOptions = opts.toSuperviseOptions(scenario, profile);
1122
+ const task = opts.toTask(scenario, profile);
1123
+ const maximumCharge = typeof opts.maximumCharge === "function" ? opts.maximumCharge(scenario, profile) : opts.maximumCharge;
1124
+ const paid = await ctx.cost.runPaidCall({
1125
+ channel: "agent",
1126
+ actor: opts.costSource ?? "supervise",
1127
+ model: "unknown",
1128
+ signal: ctx.signal,
1129
+ ...maximumCharge ? { maximumCharge } : {},
1130
+ execute: async (executionSignal) => {
1131
+ const result = await supervise(profile, task, {
1132
+ ...superviseOptions,
1133
+ signal: executionSignal
1134
+ });
1135
+ const identity = supervisedTreeModel(result, profile);
1136
+ if (identity.kind !== "known") throw new SupervisedTreeModelIdentityError(identity);
1137
+ return result;
1138
+ },
1139
+ receipt: (result) => {
1140
+ const identity = supervisedTreeModel(result, profile);
1141
+ if (identity.kind !== "known") throw new SupervisedTreeModelIdentityError(identity);
1142
+ return costReceiptFromUsage(result.spentTotal.tokens, identity.model, {
1143
+ usageUnknown: result.spentTotal.tokensKnown === false,
1144
+ actualCostUsd: result.spentTotal.usdKnown !== false ? result.spentTotal.usd : void 0,
1145
+ costUnknown: result.spentTotal.usdKnown === false
1146
+ });
1147
+ },
1148
+ receiptFromError: (error) => error instanceof SupervisedTreeModelIdentityError ? unknownSupervisedTreeReceipt() : void 0
1149
+ });
1150
+ if (!paid.succeeded) throw paid.error;
1151
+ return (opts.toArtifact ?? ((result) => {
1152
+ if (result.kind !== "winner") throw new Error(`superviseDispatch: supervised tree ended without a winner (${result.reason})`);
1153
+ return result.out;
1154
+ }))(paid.value);
1047
1155
  };
1048
1156
  }
1049
1157
  function modelFromLoopOptions(options) {
@@ -2936,7 +3044,7 @@ async function trajectoryReport(journal, blobs, root, options = {}) {
2936
3044
  continue;
2937
3045
  }
2938
3046
  node.status = ev.status === "done" ? "done" : "failed";
2939
- node.ownSpend = ev.spent;
3047
+ node.ownSpend = cloneSpend(ev.spent);
2940
3048
  node.verdict = ev.verdict;
2941
3049
  node.outRef = ev.outRef;
2942
3050
  }
@@ -3072,13 +3180,13 @@ function zeroSpend() {
3072
3180
  function addNodeSpend(a, b) {
3073
3181
  return {
3074
3182
  iterations: a.iterations + b.iterations,
3075
- tokens: {
3076
- input: a.tokens.input + b.tokens.input,
3077
- output: a.tokens.output + b.tokens.output
3078
- },
3183
+ tokens: (() => {
3184
+ const tokens = cloneTokenUsage(a.tokens);
3185
+ addTokenUsage(tokens, b.tokens);
3186
+ return tokens;
3187
+ })(),
3079
3188
  ...a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {},
3080
3189
  usd: a.usd + b.usd,
3081
- ...a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {},
3082
3190
  ...a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {},
3083
3191
  ms: a.ms + b.ms
3084
3192
  };
@@ -3086,13 +3194,9 @@ function addNodeSpend(a, b) {
3086
3194
  function cloneSpend(spend) {
3087
3195
  return {
3088
3196
  iterations: spend.iterations,
3089
- tokens: {
3090
- input: spend.tokens.input,
3091
- output: spend.tokens.output
3092
- },
3197
+ tokens: cloneTokenUsage(spend.tokens),
3093
3198
  ...spend.tokensKnown === false ? { tokensKnown: false } : {},
3094
3199
  usd: spend.usd,
3095
- ...spend.tokensKnown === false ? { tokensKnown: false } : {},
3096
3200
  ...spend.usdKnown === false ? { usdKnown: false } : {},
3097
3201
  ms: spend.ms
3098
3202
  };
@@ -3103,7 +3207,6 @@ function addSpend(acc, delta) {
3103
3207
  addTokenUsage(acc.tokens, delta.tokens);
3104
3208
  if (delta.tokensKnown === false) acc.tokensKnown = false;
3105
3209
  acc.usd += delta.usd;
3106
- if (delta.tokensKnown === false) acc.tokensKnown = false;
3107
3210
  if (delta.usdKnown === false) acc.usdKnown = false;
3108
3211
  acc.ms += delta.ms;
3109
3212
  }
@@ -5625,6 +5728,6 @@ function tail(s) {
5625
5728
  return s.slice(-400);
5626
5729
  }
5627
5730
  //#endregion
5628
- export { pipeline as $, assertStrategyContract as A, createMcpEnvironment as At, trajectoryReport as B, chatTransportExecutor as C, renderLeaderboardSvg as Ct, pickChampion as D, McpSpawnFault as Dt, discriminatingMeans as E, defaultAuditorInstruction as Et, openSandboxRun as F, resolveSecretEnv as Ft, registerShape as G, runPersonified as H, printBenchmarkReport as I, secretEnvOfMcpServer as It, renderCorpusToInstructions as J, FileCorpus as K, runBenchmark as L, strategyAuthorContract as M, envKeyProvider as Mt, strategyAuthorSystemPrompt as N, mcpSecretEnvMetadataKey as Nt, runStrategyEvolution as O, connectStdioMcp as Ot, SandboxRunAbortError as P, resolveMcpServerLaunch as Pt, panel as Q, promotionGate as R, runCoderChecks as S, renderLeaderboardMarkdown as St, createChatSessionStore as T, auditIntent as Tt, builtinShapes as U, definePersona as V, createShapeRegistry as W, flatWidenGate as X, fanout as Y, loopUntil as Z, settledWorkerOut as _, sentinelCompletion as _t, localShell as a, createScopeAnalyst as at, analyzeTrace as b, pairwiseSignificance as bt, createVerifierEnvironment as c, harvestCorpus as ct, worktreeFanout as d, localSandboxClient as dt, selectValidWinner as et, EVIDENCE_MAX_CHARS as f, inlineSandboxClient as ft, composeWorkerEvidence as g, deterministicCompletion as gt, closingWorkerNote as h, completionAuthorizes as ht, jjWorkspace as i, buildSteerContext as it, authorStrategy as j, sanitizeMcpToolSchema as jt, selectChampion as k, materializeLocalMcp as kt, failuresAnalyst as l, defineLeaderboard as lt, VERIFY_TAIL_CHARS as m, loopDispatch as mt, makeFinding$1 as n, widen as nt, runInWorkspace as o, registryScopeAnalyst as ot, NOTE_MAX_CHARS as p, loopCampaignDispatch as pt, InMemoryCorpus as q, gitWorkspace as r, assertTraceDerivedFindings as rt, createWaterfallCollector as s, inProcessSandboxClient as st, computeFindingId$1 as t, verify as tt, superviseSurface as u, resolveSandboxClient as ut, copyUntrackedIntoClone as v, stopSentinel as vt, chatWorkerSeam as w, renderPairwiseMarkdown as wt, patchDelivered as x, renderLeaderboardHtml as xt, withUntrackedArtifacts as y, leaderboard as yt, equalKOnCost as z };
5731
+ export { pipeline as $, assertStrategyContract as A, materializeLocalMcp as At, trajectoryReport as B, chatTransportExecutor as C, renderLeaderboardMarkdown as Ct, pickChampion as D, defaultAuditorInstruction as Dt, discriminatingMeans as E, auditIntent as Et, openSandboxRun as F, resolveMcpServerLaunch as Ft, registerShape as G, runPersonified as H, printBenchmarkReport as I, resolveSecretEnv as It, renderCorpusToInstructions as J, FileCorpus as K, runBenchmark as L, secretEnvOfMcpServer as Lt, strategyAuthorContract as M, sanitizeMcpToolSchema as Mt, strategyAuthorSystemPrompt as N, envKeyProvider as Nt, runStrategyEvolution as O, McpSpawnFault as Ot, SandboxRunAbortError as P, mcpSecretEnvMetadataKey as Pt, panel as Q, promotionGate as R, runCoderChecks as S, renderLeaderboardHtml as St, createChatSessionStore as T, renderPairwiseMarkdown as Tt, builtinShapes as U, definePersona as V, createShapeRegistry as W, flatWidenGate as X, fanout as Y, loopUntil as Z, settledWorkerOut as _, deterministicCompletion as _t, localShell as a, createScopeAnalyst as at, analyzeTrace as b, leaderboard as bt, createVerifierEnvironment as c, harvestCorpus as ct, worktreeFanout as d, localSandboxClient as dt, selectValidWinner as et, EVIDENCE_MAX_CHARS as f, inlineSandboxClient as ft, composeWorkerEvidence as g, completionAuthorizes as gt, closingWorkerNote as h, superviseDispatch as ht, jjWorkspace as i, buildSteerContext as it, authorStrategy as j, createMcpEnvironment as jt, selectChampion as k, connectStdioMcp as kt, failuresAnalyst as l, defineLeaderboard as lt, VERIFY_TAIL_CHARS as m, loopDispatch as mt, makeFinding$1 as n, widen as nt, runInWorkspace as o, registryScopeAnalyst as ot, NOTE_MAX_CHARS as p, loopCampaignDispatch as pt, InMemoryCorpus as q, gitWorkspace as r, assertTraceDerivedFindings as rt, createWaterfallCollector as s, inProcessSandboxClient as st, computeFindingId$1 as t, verify as tt, superviseSurface as u, resolveSandboxClient as ut, copyUntrackedIntoClone as v, sentinelCompletion as vt, chatWorkerSeam as w, renderLeaderboardSvg as wt, patchDelivered as x, pairwiseSignificance as xt, withUntrackedArtifacts as y, stopSentinel as yt, equalKOnCost as z };
5629
5732
 
5630
- //# sourceMappingURL=runtime-ZNVnT8h1.js.map
5733
+ //# sourceMappingURL=runtime-BVKEU5jc.js.map