@tangle-network/agent-runtime 0.107.4 → 0.108.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -4
- package/dist/{activation-Ck5ksFWg.js → activation-DRpnplEm.js} +3 -3
- package/dist/{activation-Ck5ksFWg.js.map → activation-DRpnplEm.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-BUpR0mSD.js → candidate-execution-nYMa-bc-.js} +4 -4
- package/dist/{candidate-execution-BUpR0mSD.js.map → candidate-execution-nYMa-bc-.js.map} +1 -1
- package/dist/durable.d.ts +134 -0
- package/dist/durable.js +124 -0
- package/dist/durable.js.map +1 -0
- package/dist/{environment-provider-IUGU3epE.d.ts → environment-provider-D0NXc4Qz.d.ts} +73 -4
- package/dist/environment-provider.d.ts +1 -1
- package/dist/{improvement-cycle-Ulvvbg5p.js → improvement-cycle-CRnDDdX0.js} +49 -155
- package/dist/improvement-cycle-CRnDDdX0.js.map +1 -0
- package/dist/{index-CeawCSEg.d.ts → index-BZbJWqoZ.d.ts} +175 -27
- package/dist/{index-D6MwUzvB.d.ts → index-DQp3BPeC.d.ts} +11 -159
- package/dist/{index-jmFVBIHo.d.ts → index-cdkwHruJ.d.ts} +3 -3
- package/dist/index.d.ts +6 -6
- package/dist/index.js +14 -121
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +15 -7
- package/dist/intelligence.js +4 -4
- package/dist/{knowledge-Dizh_AtL.js → knowledge-rdrpPIXs.js} +5 -5
- package/dist/{knowledge-Dizh_AtL.js.map → knowledge-rdrpPIXs.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-BbYG9CeA.d.ts → loop-runner-bin-9-JlGqN7.d.ts} +3 -3
- package/dist/{loop-runner-bin-CvdKZkE4.js → loop-runner-bin-B1V-XS5A.js} +3 -3
- package/dist/{loop-runner-bin-CvdKZkE4.js.map → loop-runner-bin-B1V-XS5A.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/loops.d.ts +3 -3
- package/dist/loops.js +5 -5
- package/dist/mcp/bin.js +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +4 -4
- package/dist/{openai-tools-CKLy1C7M.js → openai-tools-BjQq2TTL.js} +2 -2
- package/dist/{openai-tools-CKLy1C7M.js.map → openai-tools-BjQq2TTL.js.map} +1 -1
- package/dist/{prepare-_WTTffkz.js → prepare-Pr19X93k.js} +141 -6
- package/dist/prepare-Pr19X93k.js.map +1 -0
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/{protected-model-port-ZUwVuftA.js → protected-model-port-uthtDNqu.js} +2 -2
- package/dist/{protected-model-port-ZUwVuftA.js.map → protected-model-port-uthtDNqu.js.map} +1 -1
- package/dist/{redact-C5xOm8cu.d.ts → redact-BkasKlyd.d.ts} +17 -27
- package/dist/{runtime-5zM5XxLr.js → runtime-CDekUROm.js} +20 -13
- package/dist/runtime-CDekUROm.js.map +1 -0
- package/dist/{structural-rollout-IXUEplky.js → structural-rollout-BC81Otmc.js} +10 -9
- package/dist/structural-rollout-BC81Otmc.js.map +1 -0
- package/dist/{supervise-BiRutHS9.js → supervise-JfKPwIlO.js} +270 -69
- package/dist/supervise-JfKPwIlO.js.map +1 -0
- package/dist/{supervisor-DTKhF-RV.js → supervisor-B2LzaWRb.js} +221 -16
- package/dist/supervisor-B2LzaWRb.js.map +1 -0
- package/dist/testing.js +3544 -657
- package/dist/testing.js.map +1 -1
- package/dist/{workspace-archive-CIG1VNCj.js → workspace-archive-C9w_rxt6.js} +2 -2
- package/dist/{workspace-archive-CIG1VNCj.js.map → workspace-archive-C9w_rxt6.js.map} +1 -1
- package/package.json +11 -6
- package/dist/improvement-cycle-Ulvvbg5p.js.map +0 -1
- package/dist/prepare-_WTTffkz.js.map +0 -1
- package/dist/runtime-5zM5XxLr.js.map +0 -1
- package/dist/structural-rollout-IXUEplky.js.map +0 -1
- package/dist/supervise-BiRutHS9.js.map +0 -1
- package/dist/supervisor-DTKhF-RV.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as AgentExecutionBackend, r as AgentBackendInput } from "../types-C9j4qg6l.js";
|
|
2
|
-
import {
|
|
2
|
+
import { xt as createOpenAICompatibleBackend } from "../index-DQp3BPeC.js";
|
|
3
3
|
import { RunRecord } from "@tangle-network/agent-eval";
|
|
4
4
|
//#region src/primeintellect/types.d.ts
|
|
5
5
|
type PrimeIntellectSplit = 'train' | 'eval';
|
|
@@ -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-
|
|
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-Pr19X93k.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-
|
|
722
|
+
//# sourceMappingURL=protected-model-port-uthtDNqu.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protected-model-port-ZUwVuftA.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,KA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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-uthtDNqu.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,GAAG,QAAQ,OAAO;EAAE;EAC5D,MAAM,K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as LocalHarness, r as CodexTokenUsage, t as CodexExecutionEvidence } from "./local-harness-Dh8PJ0ot.js";
|
|
2
|
-
import {
|
|
3
|
-
import { CampaignScenarioIdentity, CompareOptimizationMethodsOptions,
|
|
2
|
+
import { CostLedgerHandle, MaximumCharge, ProposalFinding } from "@tangle-network/agent-eval";
|
|
3
|
+
import { CampaignScenarioIdentity, CompareOptimizationMethodsOptions, OptimizationMethod, OptimizationMethodComparison, WorktreeAdapter } from "@tangle-network/agent-eval/campaign";
|
|
4
4
|
import { AgentProfile as AgentProfile$1, ReasoningEffort, Sha256Digest } from "@tangle-network/agent-interface";
|
|
5
5
|
import { MutableSurface, Scenario as Scenario$1, SelfImproveBudget, SelfImproveOptions, SelfImproveResult } from "@tangle-network/agent-eval/contract";
|
|
6
6
|
//#region src/improvement/improvement-driver.d.ts
|
|
7
|
-
/** The byte-producing
|
|
7
|
+
/** The byte-producing path that differs between the cheap
|
|
8
8
|
* reflective path and the full agentic path. A generator makes (uncommitted)
|
|
9
9
|
* changes inside `worktreePath`; the driver commits them via the worktree
|
|
10
10
|
* adapter's `finalize`. */
|
|
11
11
|
interface CandidateGenerator {
|
|
12
12
|
kind: string;
|
|
13
|
-
/** Whether this generator can produce a candidate from an
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* raw traces ARE the signal, so it must still run the full `populationSize`
|
|
18
|
-
* when the distiller yielded nothing (this is the meta-harness contract — the
|
|
19
|
-
* agent diagnoses from the raw traces itself). A patch-applier
|
|
13
|
+
/** Whether this generator can produce a candidate from an empty findings set
|
|
14
|
+
* because it draws its change signal from the repo and raw traces on disk.
|
|
15
|
+
* An agentic coder (`agenticGenerator`) sets this so it still runs the full
|
|
16
|
+
* `populationSize` when the distiller yielded nothing. A patch-applier
|
|
20
17
|
* (`reflectiveGenerator`) leaves it unset — with no findings there is no
|
|
21
18
|
* patch to draft, so the driver short-circuits rather than spin up worktrees
|
|
22
19
|
* for a guaranteed no-op. Default `false`. */
|
|
@@ -24,12 +21,8 @@ interface CandidateGenerator {
|
|
|
24
21
|
generate(args: {
|
|
25
22
|
/** The candidate worktree — a clean checkout of the current incumbent. */
|
|
26
23
|
worktreePath: string;
|
|
27
|
-
/**
|
|
28
|
-
|
|
29
|
-
/** Findings resolved from the report or the loop context. */
|
|
30
|
-
findings: AnalystFinding[];
|
|
31
|
-
/** Handle to all captured data, to ground the change. */
|
|
32
|
-
dataset?: LabeledScenarioStore;
|
|
24
|
+
/** Search or production findings explicitly admitted for proposal use. */
|
|
25
|
+
findings: ReadonlyArray<ProposalFinding>;
|
|
33
26
|
/** DEPTH: max iterations the generator may take (agentic uses this; the
|
|
34
27
|
* reflective generator ignores it). */
|
|
35
28
|
maxShots: number;
|
|
@@ -169,11 +162,9 @@ interface AgenticGeneratorOptions {
|
|
|
169
162
|
maximumCharge?: MaximumCharge;
|
|
170
163
|
/** Per-shot wall-clock timeout (ms). Default = `runLocalHarness` default (5m). */
|
|
171
164
|
timeoutMs?: number;
|
|
172
|
-
/** Build the harness task prompt from
|
|
173
|
-
* domain phrasing; the default turns findings into a concrete coder task. */
|
|
165
|
+
/** Build the harness task prompt from proposal findings. */
|
|
174
166
|
buildPrompt?: (args: {
|
|
175
|
-
|
|
176
|
-
findings: AnalystFinding[];
|
|
167
|
+
findings: ReadonlyArray<ProposalFinding>;
|
|
177
168
|
}) => string;
|
|
178
169
|
/** Verify the worktree after each dirtying shot. When set, a candidate that
|
|
179
170
|
* fails verification is NOT returned — the failure feeds the next shot
|
|
@@ -188,11 +179,10 @@ interface AgenticGeneratorOptions {
|
|
|
188
179
|
}
|
|
189
180
|
/** Full-agentic `CandidateGenerator` (the `shots=N, sandbox=on` setting): run a real coding harness inside the candidate worktree so the agent makes the change in place. */
|
|
190
181
|
declare function agenticGenerator(opts?: AgenticGeneratorOptions): CandidateGenerator;
|
|
191
|
-
/** Turn
|
|
182
|
+
/** Turn proposal findings into a concrete coder task —
|
|
192
183
|
* the senior scientific-method framing shared with the tool/MCP build prompts. */
|
|
193
184
|
declare function defaultBuildPrompt(args: {
|
|
194
|
-
|
|
195
|
-
findings: AnalystFinding[];
|
|
185
|
+
findings: ReadonlyArray<ProposalFinding>;
|
|
196
186
|
}): string;
|
|
197
187
|
/** A `Verifier` that runs a command in the worktree: exit 0 ⇒ ok, any other
|
|
198
188
|
* exit ⇒ failed with stdout+stderr as feedback. The common case — verify by
|
|
@@ -227,7 +217,7 @@ interface ImproveMethodContext {
|
|
|
227
217
|
/** Structured value represented by `baselineSurface`, before serialization. */
|
|
228
218
|
readonly baselineValue: unknown;
|
|
229
219
|
/** Findings produced before this search, if any. */
|
|
230
|
-
readonly findings:
|
|
220
|
+
readonly findings: ReadonlyArray<ProposalFinding>;
|
|
231
221
|
}
|
|
232
222
|
/** Build a complete method after trace findings are available. */
|
|
233
223
|
type ImproveMethodFactory<TScenario extends Scenario$1, TArtifact> = (context: ImproveMethodContext) => OptimizationMethod<TScenario, TArtifact>;
|
|
@@ -260,7 +250,7 @@ type ImproveMethodOptions<TScenario extends Scenario$1, TArtifact> = Omit<Compar
|
|
|
260
250
|
/** Reject a materialized profile before it reaches the agent callback. */
|
|
261
251
|
validateCandidate?: ImproveCandidateValidator;
|
|
262
252
|
/** Trace or analyst findings available to a method factory. */
|
|
263
|
-
findings?:
|
|
253
|
+
findings?: ReadonlyArray<ProposalFinding>;
|
|
264
254
|
/** Select the exact inline skill document for `surface: 'skills'`. */
|
|
265
255
|
skills?: ImproveSkillsOptions;
|
|
266
256
|
/**
|
|
@@ -279,7 +269,7 @@ type ImproveCodeRunOptions<TScenario extends Scenario$1, TArtifact> = Omit<SelfI
|
|
|
279
269
|
/** Local code-search budget. Method-only selection controls do not apply. */
|
|
280
270
|
budget?: Omit<SelfImproveBudget, 'selectionFraction'>;
|
|
281
271
|
/** Findings supplied to Runtime's code candidate driver. */
|
|
282
|
-
findings?:
|
|
272
|
+
findings?: ReadonlyArray<ProposalFinding>;
|
|
283
273
|
/** Gate mode. `'holdout'` (default) runs the held-out promotion gate;
|
|
284
274
|
* `'none'` is a baseline-only run (`budget.generations = 0`). */
|
|
285
275
|
gate?: 'holdout' | 'none';
|
|
@@ -469,4 +459,4 @@ declare function defaultRedactor(value: unknown): unknown;
|
|
|
469
459
|
declare function resolveRedactor(redact: Redactor | false | undefined): Redactor;
|
|
470
460
|
//#endregion
|
|
471
461
|
export { DeepReadonly as A, commandVerifier as B, ImproveResult as C, ImprovementCandidate as D, ImproveSurface as E, AgenticGeneratorShotExecution as F, CandidateGenerator as H, AgenticGeneratorShotReceipt as I, Verifier as L, AGENTIC_PROFILE_RESOURCE_ROOT as M, AgenticGeneratorOptions as N, ImprovementCodeCandidate as O, AgenticGeneratorShotDisposition as P, VerifyResult as R, ImproveProfileSurface as S, ImproveSkillsOptions as T, defaultBuildPrompt as V, ImproveMethodSource as _, ImproveCandidateValidationInput as a, ImproveProfileAgent as b, ImproveCodeResult as c, ImproveLineage as d, ImproveMethodContext as f, ImproveMethodResult as g, ImproveMethodOptions as h, improve as i, ReadonlyAgentProfile as j, ImprovementProfileCandidate as k, ImproveCodeRunOptions as l, ImproveMethodLineage as m, defaultRedactor as n, ImproveCandidateValidator as o, ImproveMethodFactory as p, resolveRedactor as r, ImproveCodeOptions as s, Redactor as t, ImproveCost as u, ImproveOptimizationRunOptions as v, ImproveScenarioPartitions as w, ImproveProfileComponents as x, ImproveOptions as y, agenticGenerator as z };
|
|
472
|
-
//# sourceMappingURL=redact-
|
|
462
|
+
//# sourceMappingURL=redact-BkasKlyd.d.ts.map
|
|
@@ -3,11 +3,11 @@ import { i as normalizeBackendStreamEvent, o as newRuntimeSession, s as nowIso }
|
|
|
3
3
|
import { a as randomSuffix, c as stringifySafe, f as zeroTokenUsage, r as isAbortError, s as sleep, t as addTokenUsage } from "./util-MVgdwuIS.js";
|
|
4
4
|
import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore } from "./spawn-journal-CwPvKUTa.js";
|
|
5
5
|
import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction--F3v1oo8.js";
|
|
6
|
-
import {
|
|
7
|
-
import { C as observe, O as strategyAuthorMethod, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-
|
|
6
|
+
import { D as routerChatWithUsage, T as routerBrain, d as settledToIteration, k as runBrainLoop, l as withDriverExecutor, t as createSupervisor, w as notifyRuntimeHookEvent } from "./supervisor-B2LzaWRb.js";
|
|
7
|
+
import { C as observe, O as strategyAuthorMethod, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-BC81Otmc.js";
|
|
8
8
|
import { a as notifySandboxEventObserver, i as mapSandboxToolEvent, r as mapSandboxEvent, t as createSandboxToolPartState } from "./sandbox-events-DeI5xX8P.js";
|
|
9
|
-
import { Bt as runAgentRounds, Dt as createExecutorRegistry, Et as createExecutor, Ht as createSandboxLineage,
|
|
10
|
-
import { CODING_HARNESSES, InMemoryTraceStore, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, expandProfileAxes, harnessAxisOf, makeFinding as makeFinding$1, pairedBootstrap,
|
|
9
|
+
import { Bt as runAgentRounds, Dt as createExecutorRegistry, Et as createExecutor, Ht as createSandboxLineage, Ot as createWorktreeCliExecutor, Ut as probeSandboxCapabilities, bt as rollingDispatch, qt as gateOnDeliverable, t as supervise, zt as defaultSelectWinner } from "./supervise-JfKPwIlO.js";
|
|
10
|
+
import { CODING_HARNESSES, InMemoryTraceStore, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, expandProfileAxes, harnessAxisOf, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, scoreKnowledgeReadiness, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
11
11
|
import { heldoutSignificance, runProfileMatrix } from "@tangle-network/agent-eval/campaign";
|
|
12
12
|
import { canonicalCandidateDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
13
13
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
@@ -724,7 +724,7 @@ function pairwiseSignificance(records, opts = {}) {
|
|
|
724
724
|
seed: 7,
|
|
725
725
|
statistic: "median"
|
|
726
726
|
});
|
|
727
|
-
const
|
|
727
|
+
const test = wilcoxonSignedRank(aScores, bScores, { seed: 7 });
|
|
728
728
|
raw.push({
|
|
729
729
|
a: labelOf(ka),
|
|
730
730
|
b: labelOf(kb),
|
|
@@ -732,12 +732,16 @@ function pairwiseSignificance(records, opts = {}) {
|
|
|
732
732
|
delta: boot.median,
|
|
733
733
|
ciLow: boot.low,
|
|
734
734
|
ciHigh: boot.high,
|
|
735
|
-
|
|
735
|
+
nonZeroPairs: test.nNonZero,
|
|
736
|
+
testMethod: test.method,
|
|
737
|
+
pFloor: test.pFloor,
|
|
738
|
+
p: test.p
|
|
736
739
|
});
|
|
737
740
|
}
|
|
738
|
-
const { significant } = benjaminiHochberg(raw.map((
|
|
741
|
+
const { qValues, significant } = benjaminiHochberg(raw.map((result) => result.p), opts.fdr ?? .05);
|
|
739
742
|
return raw.map((r, i) => ({
|
|
740
743
|
...r,
|
|
744
|
+
q: qValues[i] ?? 1,
|
|
741
745
|
significant: (significant[i] ?? false) && r.pairs >= minPairs
|
|
742
746
|
}));
|
|
743
747
|
}
|
|
@@ -780,15 +784,18 @@ function renderLeaderboardMarkdown(report) {
|
|
|
780
784
|
function renderPairwiseMarkdown(verdicts, title = "Pairwise significance (paired, BH-corrected)") {
|
|
781
785
|
const lines = [`## ${title}`, ""];
|
|
782
786
|
if (verdicts.length === 0) return lines.concat("_no comparable pairs_").join("\n");
|
|
783
|
-
lines.push("| A vs B | Δ(b−a) median | 95% CI | pairs | p | verdict |");
|
|
784
|
-
lines.push("
|
|
787
|
+
lines.push("| A vs B | Δ(b−a) median | 95% CI | pairs | changed | test | p | p floor | q | verdict |");
|
|
788
|
+
lines.push("|---|--:|--:|--:|--:|---|--:|--:|--:|---|");
|
|
785
789
|
for (const v of verdicts) {
|
|
786
|
-
const verdict = v.significant ? `**${v.delta >= 0 ? v.b : v.a} wins**` : "ns";
|
|
787
|
-
lines.push(`| ${v.a} vs ${v.b} | ${v.delta >= 0 ? "+" : ""}${pct(v.delta)} | [${pct(v.ciLow)}, ${pct(v.ciHigh)}] | ${v.pairs} | ${v.p.
|
|
790
|
+
const verdict = v.nonZeroPairs === 0 ? "tie" : v.significant ? `**${v.delta >= 0 ? v.b : v.a} wins**` : "ns";
|
|
791
|
+
lines.push(`| ${v.a} vs ${v.b} | ${v.delta >= 0 ? "+" : ""}${pct(v.delta)} | [${pct(v.ciLow)}, ${pct(v.ciHigh)}] | ${v.pairs} | ${v.nonZeroPairs} | ${v.testMethod} | ${formatProbability(v.p)} | ${formatProbability(v.pFloor)} | ${formatProbability(v.q)} | ${verdict} |`);
|
|
788
792
|
}
|
|
789
|
-
lines.push("", "> `
|
|
793
|
+
lines.push("", "> `changed` excludes exact ties. `p` is the raw two-sided signed-rank probability; `q` is Benjamini-Hochberg adjusted. `ns` means q did not clear the target or the pair count was below the configured minimum.");
|
|
790
794
|
return lines.join("\n");
|
|
791
795
|
}
|
|
796
|
+
function formatProbability(value) {
|
|
797
|
+
return value > 0 && value < .001 ? value.toExponential(2) : value.toFixed(3);
|
|
798
|
+
}
|
|
792
799
|
function esc(s) {
|
|
793
800
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
794
801
|
}
|
|
@@ -5405,4 +5412,4 @@ function tail(s) {
|
|
|
5405
5412
|
//#endregion
|
|
5406
5413
|
export { defineLeaderboard as $, trajectoryReport as A, flatWidenGate as B, strategyAuthorContract as C, sanitizeMcpToolSchema as Ct, runBenchmark as D, secretEnvOfMcpServer as Dt, printBenchmarkReport as E, resolveSecretEnv as Et, registerShape as F, verify as G, panel as H, FileCorpus as I, buildSteerContext as J, widen as K, InMemoryCorpus as L, runPersonified as M, builtinShapes as N, promotionGate as O, createShapeRegistry as P, harvestCorpus as Q, renderCorpusToInstructions as R, authorStrategy as S, createMcpEnvironment as St, openSandboxRun as T, mcpSecretEnvMetadataKey as Tt, pipeline as U, loopUntil as V, selectValidWinner as W, registryScopeAnalyst as X, createScopeAnalyst as Y, inProcessSandboxClient as Z, discriminatingMeans as _, auditIntent as _t, localShell as a, loopCampaignDispatch as at, selectChampion as b, connectStdioMcp as bt, createVerifierEnvironment as c, deterministicCompletion as ct, worktreeFanout as d, leaderboard as dt, dumbDriver as et, analyzeTrace as f, pairwiseSignificance as ft, streamAgentTurn as g, renderPairwiseMarkdown as gt, collectAgentTurn as h, renderLeaderboardSvg as ht, jjWorkspace as i, inlineSandboxClient as it, definePersona as j, equalKOnCost as k, failuresAnalyst as l, sentinelCompletion as lt, runCoderChecks as m, renderLeaderboardMarkdown as mt, makeFinding$1 as n, resolveSandboxClient as nt, runInWorkspace as o, loopDispatch as ot, patchDelivered as p, renderLeaderboardHtml as pt, assertTraceDerivedFindings as q, gitWorkspace as r, localSandboxClient as rt, createWaterfallCollector as s, completionAuthorizes as st, computeFindingId$1 as t, naiveDriver as tt, superviseSurface as u, stopSentinel as ut, pickChampion as v, defaultAuditorInstruction as vt, SandboxRunAbortError as w, envKeyProvider as wt, assertStrategyContract as x, materializeLocalMcp as xt, runStrategyEvolution as y, McpSpawnFault as yt, fanout as z };
|
|
5407
5414
|
|
|
5408
|
-
//# sourceMappingURL=runtime-
|
|
5415
|
+
//# sourceMappingURL=runtime-CDekUROm.js.map
|