@tangle-network/agent-runtime 0.133.5 → 0.133.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-CeZdt1R3.js → activation-BeFr74qj.js} +3 -3
- package/dist/{activation-CeZdt1R3.js.map → activation-BeFr74qj.js.map} +1 -1
- package/dist/agent.js +2 -2
- package/dist/{authoring-Cbz3BYqD.js → authoring-CxnWFZVk.js} +2 -2
- package/dist/{authoring-Cbz3BYqD.js.map → authoring-CxnWFZVk.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +4 -4
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-gDXl7pGk.js → candidate-execution-_u2HIWeX.js} +30 -5
- package/dist/candidate-execution-_u2HIWeX.js.map +1 -0
- package/dist/{graph-BcwxFLW_.js → graph-C_rMgoWQ.js} +2 -2
- package/dist/{graph-BcwxFLW_.js.map → graph-C_rMgoWQ.js.map} +1 -1
- package/dist/{improvement-cycle-CXY8XmhV.js → improvement-cycle-BBH8oYiA.js} +4 -4
- package/dist/{improvement-cycle-CXY8XmhV.js.map → improvement-cycle-BBH8oYiA.js.map} +1 -1
- package/dist/{index-C7tsPEzj.d.ts → index-DLjXduyp.d.ts} +2 -2
- package/dist/{index-C8WhH5Yt.d.ts → index-DQxQgKDs.d.ts} +3 -3
- package/dist/index.d.ts +5 -5
- package/dist/index.js +11 -11
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +5 -5
- package/dist/kernel.js +6 -6
- package/dist/{knowledge-vEyPvtRm.js → knowledge-DubRihOP.js} +5 -5
- package/dist/{knowledge-vEyPvtRm.js.map → knowledge-DubRihOP.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-BrF0g950.js → loop-runner-bin-CMKMWSH6.js} +3 -3
- package/dist/{loop-runner-bin-BrF0g950.js.map → loop-runner-bin-CMKMWSH6.js.map} +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.js +4 -4
- package/dist/{openai-tools-BEeoh5i0.js → openai-tools-DrQwA-X_.js} +2 -2
- package/dist/{openai-tools-BEeoh5i0.js.map → openai-tools-DrQwA-X_.js.map} +1 -1
- package/dist/{prepare-DWH0J5z2.js → prepare-DUbH3GD5.js} +10 -4
- package/dist/prepare-DUbH3GD5.js.map +1 -0
- package/dist/{protected-model-port-CoJOiINX.d.ts → protected-model-port-DEsTWOFs.d.ts} +2 -2
- package/dist/{protected-model-port-djV8FMXc.js → protected-model-port-DP7MS63a.js} +46 -16
- package/dist/protected-model-port-DP7MS63a.js.map +1 -0
- package/dist/{runtime-BX5c47Qm.js → runtime-VwxvxGN7.js} +6 -6
- package/dist/{runtime-BX5c47Qm.js.map → runtime-VwxvxGN7.js.map} +1 -1
- package/dist/{structural-rollout-CHq3qJau.js → structural-rollout-eAj7HG0m.js} +2 -2
- package/dist/{structural-rollout-CHq3qJau.js.map → structural-rollout-eAj7HG0m.js.map} +1 -1
- package/dist/{supervise-D-e9RIuG.js → supervise-009CRDW1.js} +2 -2
- package/dist/{supervise-D-e9RIuG.js.map → supervise-009CRDW1.js.map} +1 -1
- package/dist/{supervisor-GBIOnjUo.js → supervisor-DNX8CXui.js} +15 -2
- package/dist/{supervisor-GBIOnjUo.js.map → supervisor-DNX8CXui.js.map} +1 -1
- package/dist/testing.js +12 -12
- package/dist/{types-BaIpb0XT.d.ts → types-CxU37Uzr.d.ts} +14 -5
- package/dist/{workspace-archive-DdrlLnIj.js → workspace-archive-WEbaLREb.js} +2 -2
- package/dist/{workspace-archive-DdrlLnIj.js.map → workspace-archive-WEbaLREb.js.map} +1 -1
- package/package.json +1 -1
- package/dist/candidate-execution-gDXl7pGk.js.map +0 -1
- package/dist/prepare-DWH0J5z2.js.map +0 -1
- package/dist/protected-model-port-djV8FMXc.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as AgentCandidateProtectedModelSettlement, D as AgentCandidateRunFinalization, F as PreparedAgentCandidateExecution, O as AgentCandidateTaskExecution, S as AgentCandidateProtectedModelReservation, V as VerifiedAgentCandidate, a as AgentCandidateExecutionPorts, c as AgentCandidateExecutorPort, r as AgentCandidateBenchmarkGraderPort, v as AgentCandidateModelPort, x as AgentCandidateProtectedModelActivation, y as AgentCandidateOutputArtifactPort } from "./types-CxU37Uzr.js";
|
|
2
2
|
import { TraceStore } from "@tangle-network/agent-eval";
|
|
3
3
|
import { AgentCandidateArtifactRef, AgentCandidateAttemptPolicy, AgentCandidateFixedSpend, AgentCandidateProfile, AgentCandidateProfileActivation, AgentCandidateProfilePlanEvidence, AgentCandidateResolvedModel, AgentProfile as AgentProfile$1, AgentProfileDiff, HarnessType as HarnessType$1, Sha256Digest } from "@tangle-network/agent-interface";
|
|
4
4
|
import "@tangle-network/agent-profile-materialize";
|
|
@@ -288,4 +288,4 @@ interface CreateProtectedAgentCandidateModelPortOptions {
|
|
|
288
288
|
declare function createProtectedAgentCandidateModelPort(options: CreateProtectedAgentCandidateModelPortOptions): AgentCandidateModelPort;
|
|
289
289
|
//#endregion
|
|
290
290
|
export { AgentCandidateExecutionPhase as A, AgentCandidatePreparationEvidence as B, AgentCandidateExecutionClaim as C, AgentCandidateExecutionFailureClass as D, AgentCandidateExecutionCleanupHandles as E, AgentCandidateExecutionTerminalResult as F, AgentCandidateRetryRejection as I, InMemoryAgentCandidateExecutionClaimStore as L, AgentCandidateExecutionRecoveryEvidence as M, AgentCandidateExecutionStageResult as N, AgentCandidateExecutionFinishResult as O, AgentCandidateExecutionTerminalRecord as P, InMemoryAgentCandidateExecutionClaimStoreOptions as R, AgentCandidateExecutionAttemptRef as S, AgentCandidateExecutionClaimStore as T, PrepareAgentCandidateExecutionOptions as _, AgentCandidateModelGrantSettleInput as a, executePreparedAgentCandidate as b, agentCandidateProfileAsAgentProfile as c, freezeGenericAgentCandidateProfile as d, omitUndefinedObjectFields as f, parseExactCandidateProfile as g, parseExactAgentProfileDiff as h, AgentCandidateModelGrantReserveInput as i, AgentCandidateExecutionPhaseResult as j, AgentCandidateExecutionLease as k, applyExactAgentProfileDiff as l, parseExactAgentProfile as m, AgentCandidateModelGrantClient as n, CreateProtectedAgentCandidateModelPortOptions as o, parseAgentCandidateProfileActivation as p, AgentCandidateModelGrantReservation as r, createProtectedAgentCandidateModelPort as s, AgentCandidateModelGrantActivateInput as t, assertCandidateProfileBinding as u, prepareAgentCandidateExecution as v, AgentCandidateExecutionClaimResult as w, AgentCandidateExecutionAttemptRecord as x, ExecutePreparedAgentCandidateOptions as y, candidateExecutionClaim as z };
|
|
291
|
-
//# sourceMappingURL=protected-model-port-
|
|
291
|
+
//# sourceMappingURL=protected-model-port-DEsTWOFs.d.ts.map
|
|
@@ -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-DUbH3GD5.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
|
|
@@ -467,6 +467,7 @@ function createProtectedAgentCandidateModelPort(options) {
|
|
|
467
467
|
const gatewayDomain = assertGatewayDomain(options.gatewayDomain);
|
|
468
468
|
const activationEnvNames = exactEnvironmentNames(options.activationEnvNames);
|
|
469
469
|
const reservations = /* @__PURE__ */ new Map();
|
|
470
|
+
const expiredReservations = /* @__PURE__ */ new Map();
|
|
470
471
|
const recentSettlements = /* @__PURE__ */ new Map();
|
|
471
472
|
return {
|
|
472
473
|
resolve: async (input) => {
|
|
@@ -474,12 +475,13 @@ function createProtectedAgentCandidateModelPort(options) {
|
|
|
474
475
|
return immutableCandidateValue(validateResolvedModel(await options.resolveModel(request), request));
|
|
475
476
|
},
|
|
476
477
|
reserveGrant: async (input) => {
|
|
477
|
-
pruneExpiredState(reservations, recentSettlements, Date.now());
|
|
478
|
+
pruneExpiredState(reservations, expiredReservations, recentSettlements, Date.now());
|
|
478
479
|
const request = immutableCandidateValue(input);
|
|
479
480
|
validateReserveInput(request);
|
|
480
481
|
const requestDigest = canonicalCandidateDigest(request);
|
|
481
482
|
const key = reservationKey(request.executionId, request.preparationId);
|
|
482
483
|
if (recentSettlements.has(key)) throw new Error("protected model reservation is already settled");
|
|
484
|
+
if (expiredReservations.get(key)) throw new Error("protected model reservation has expired");
|
|
483
485
|
const previous = reservations.get(key);
|
|
484
486
|
if (previous && previous.requestDigest !== requestDigest) throw new Error("protected model reservation retry changed immutable input");
|
|
485
487
|
const reservation = validateReservation(await options.client.reserve(request), request, gatewayDomain);
|
|
@@ -503,11 +505,12 @@ function createProtectedAgentCandidateModelPort(options) {
|
|
|
503
505
|
return reservation;
|
|
504
506
|
},
|
|
505
507
|
activateGrant: async (input) => {
|
|
506
|
-
pruneExpiredState(reservations, recentSettlements, Date.now());
|
|
508
|
+
pruneExpiredState(reservations, expiredReservations, recentSettlements, Date.now());
|
|
507
509
|
const request = immutableCandidateValue(input);
|
|
508
510
|
const key = reservationKey(request.executionId, request.preparationId);
|
|
509
511
|
if (recentSettlements.has(key)) throw new Error("protected model grant is already settled");
|
|
510
512
|
const state = reservations.get(key);
|
|
513
|
+
if (!state && expiredReservations.has(key)) throw new Error("protected model grant reservation has expired");
|
|
511
514
|
if (!state) throw new Error("protected model grant was not reserved by this port");
|
|
512
515
|
assertGrantIdentity(state, request);
|
|
513
516
|
if (state.settlementDigest) throw new Error("protected model grant is already settled");
|
|
@@ -528,10 +531,10 @@ function createProtectedAgentCandidateModelPort(options) {
|
|
|
528
531
|
},
|
|
529
532
|
settleGrant: async (input) => {
|
|
530
533
|
const now = Date.now();
|
|
531
|
-
pruneExpiredState(reservations, recentSettlements, now);
|
|
534
|
+
pruneExpiredState(reservations, expiredReservations, recentSettlements, now);
|
|
532
535
|
const request = immutableCandidateValue(input);
|
|
533
536
|
const key = reservationKey(request.executionId, request.preparationId);
|
|
534
|
-
const state = reservations.get(key);
|
|
537
|
+
const state = reservations.get(key) ?? expiredReservations.get(key)?.state;
|
|
535
538
|
if (state) assertGrantIdentity(state, request);
|
|
536
539
|
const remembered = state ?? recentSettlements.get(key);
|
|
537
540
|
if (remembered?.settlementReason && remembered.settlementReason !== request.reason) throw new Error("protected model settlement retry changed the termination reason");
|
|
@@ -550,6 +553,7 @@ function createProtectedAgentCandidateModelPort(options) {
|
|
|
550
553
|
state.settlementReason = request.reason;
|
|
551
554
|
}
|
|
552
555
|
reservations.delete(key);
|
|
556
|
+
expiredReservations.delete(key);
|
|
553
557
|
rememberSettlement(recentSettlements, key, {
|
|
554
558
|
settlementDigest,
|
|
555
559
|
settlementReason: request.reason,
|
|
@@ -565,8 +569,12 @@ function validateReserveInput(input) {
|
|
|
565
569
|
for (const [name, value] of [
|
|
566
570
|
["maxModelCalls", input.limits.maxModelCalls],
|
|
567
571
|
["maxInputTokens", input.limits.maxInputTokens],
|
|
568
|
-
["maxOutputTokens", input.limits.maxOutputTokens]
|
|
569
|
-
|
|
572
|
+
["maxOutputTokens", input.limits.maxOutputTokens],
|
|
573
|
+
["maxTotalTokens", input.limits.maxTotalTokens]
|
|
574
|
+
]) {
|
|
575
|
+
if (value === void 0) continue;
|
|
576
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`protected model reservation ${name} must be a nonnegative safe integer`);
|
|
577
|
+
}
|
|
570
578
|
usdToNanos(input.limits.maxCostUsd, "reserved maxCostUsd");
|
|
571
579
|
}
|
|
572
580
|
function validateReservation(value, expected, gatewayDomain) {
|
|
@@ -580,12 +588,7 @@ function validateReservation(value, expected, gatewayDomain) {
|
|
|
580
588
|
if (source.preparationId !== expected.preparationId) throw new Error("protected model reservation response changed preparation identity");
|
|
581
589
|
if (!isSha256Digest(source.digest)) throw new Error("protected model reservation response has an invalid digest");
|
|
582
590
|
if (source.expiresAtMs !== expected.expiresAtMs) throw new Error("protected model reservation response changed expiry");
|
|
583
|
-
exactRecord(source.enforcedLimits,
|
|
584
|
-
"maxModelCalls",
|
|
585
|
-
"maxInputTokens",
|
|
586
|
-
"maxOutputTokens",
|
|
587
|
-
"maxCostUsd"
|
|
588
|
-
], "protected model reservation enforced limits");
|
|
591
|
+
exactRecord(source.enforcedLimits, modelLimitKeys(expected.limits), "protected model reservation enforced limits");
|
|
589
592
|
if (canonicalCandidateDigest(source.enforcedLimits) !== canonicalCandidateDigest(expected.limits)) throw new Error("protected model reservation response changed enforced limits");
|
|
590
593
|
const network = validateReservationNetwork(source.network, expected.limits.maxModelCalls, gatewayDomain);
|
|
591
594
|
return immutableCandidateValue({
|
|
@@ -665,6 +668,26 @@ function assertWithinReservedLimits(usage, reservation) {
|
|
|
665
668
|
reservation.maxCostUsdNanos
|
|
666
669
|
]
|
|
667
670
|
]) if (actual > limit) throw new Error(`protected model settlement ${name} ${actual} exceeds reserved ${limit}`);
|
|
671
|
+
const maxTotalTokens = reservation.limits.maxTotalTokens;
|
|
672
|
+
if (maxTotalTokens !== void 0) {
|
|
673
|
+
const totalTokens = usage.inputTokens + usage.outputTokens;
|
|
674
|
+
if (!Number.isSafeInteger(totalTokens)) throw new Error("protected model settlement total token usage is incomplete");
|
|
675
|
+
if (totalTokens > maxTotalTokens) throw new Error(`protected model settlement total tokens ${totalTokens} exceeds reserved ${maxTotalTokens}`);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
function modelLimitKeys(limits) {
|
|
679
|
+
return limits.maxTotalTokens === void 0 ? [
|
|
680
|
+
"maxModelCalls",
|
|
681
|
+
"maxInputTokens",
|
|
682
|
+
"maxOutputTokens",
|
|
683
|
+
"maxCostUsd"
|
|
684
|
+
] : [
|
|
685
|
+
"maxModelCalls",
|
|
686
|
+
"maxInputTokens",
|
|
687
|
+
"maxOutputTokens",
|
|
688
|
+
"maxTotalTokens",
|
|
689
|
+
"maxCostUsd"
|
|
690
|
+
];
|
|
668
691
|
}
|
|
669
692
|
function exactEnvironmentNames(values) {
|
|
670
693
|
if (values.length === 0) throw new Error("protected model activation environment names must not be empty");
|
|
@@ -689,8 +712,15 @@ function reservationKey(executionId, preparationId) {
|
|
|
689
712
|
preparationId
|
|
690
713
|
});
|
|
691
714
|
}
|
|
692
|
-
function pruneExpiredState(reservations, settlements, now) {
|
|
693
|
-
for (const [key, value] of reservations) if (value.expiresAtMs <= now)
|
|
715
|
+
function pruneExpiredState(reservations, expiredReservations, settlements, now) {
|
|
716
|
+
for (const [key, value] of reservations) if (value.expiresAtMs <= now) {
|
|
717
|
+
reservations.delete(key);
|
|
718
|
+
expiredReservations.set(key, {
|
|
719
|
+
state: value,
|
|
720
|
+
retainedUntilMs: now + RECOVERED_SETTLEMENT_RETENTION_MS
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
for (const [key, value] of expiredReservations) if (value.retainedUntilMs <= now) expiredReservations.delete(key);
|
|
694
724
|
for (const [key, value] of settlements) if (value.expiresAtMs <= now) settlements.delete(key);
|
|
695
725
|
}
|
|
696
726
|
function rememberSettlement(settlements, key, value) {
|
|
@@ -719,4 +749,4 @@ function record(value, label) {
|
|
|
719
749
|
//#endregion
|
|
720
750
|
export { exactProcessProviderAsCandidateExecutor as n, createProtectedAgentCandidateModelPort as t };
|
|
721
751
|
|
|
722
|
-
//# sourceMappingURL=protected-model-port-
|
|
752
|
+
//# sourceMappingURL=protected-model-port-DP7MS63a.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"protected-model-port-DP7MS63a.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 expiredReservations = new Map<\n string,\n { state: RememberedReservation; retainedUntilMs: number }\n >()\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, expiredReservations, 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 expired = expiredReservations.get(key)\n if (expired) throw new Error('protected model reservation has expired')\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, expiredReservations, 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 && expiredReservations.has(key)) {\n throw new Error('protected model grant reservation has expired')\n }\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, expiredReservations, recentSettlements, now)\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n const state = reservations.get(key) ?? expiredReservations.get(key)?.state\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 expiredReservations.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 ['maxTotalTokens', input.limits.maxTotalTokens],\n ] as const) {\n if (value === undefined) continue\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 modelLimitKeys(expected.limits),\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 const maxTotalTokens = reservation.limits.maxTotalTokens\n if (maxTotalTokens !== undefined) {\n const totalTokens = usage.inputTokens + usage.outputTokens\n if (!Number.isSafeInteger(totalTokens)) {\n throw new Error('protected model settlement total token usage is incomplete')\n }\n if (totalTokens > maxTotalTokens) {\n throw new Error(\n `protected model settlement total tokens ${totalTokens} exceeds reserved ${maxTotalTokens}`,\n )\n }\n }\n}\n\nfunction modelLimitKeys(limits: AgentCandidateModelLimits): readonly string[] {\n return limits.maxTotalTokens === undefined\n ? ['maxModelCalls', 'maxInputTokens', 'maxOutputTokens', 'maxCostUsd']\n : ['maxModelCalls', 'maxInputTokens', 'maxOutputTokens', 'maxTotalTokens', 'maxCostUsd']\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 expiredReservations: Map<string, { state: RememberedReservation; retainedUntilMs: number }>,\n settlements: Map<string, RememberedSettlement>,\n now: number,\n): void {\n for (const [key, value] of reservations) {\n if (value.expiresAtMs <= now) {\n reservations.delete(key)\n expiredReservations.set(key, {\n state: value,\n retainedUntilMs: now + RECOVERED_SETTLEMENT_RETENTION_MS,\n })\n }\n }\n for (const [key, value] of expiredReservations) {\n if (value.retainedUntilMs <= now) expiredReservations.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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,CAAC,KAAK,UAAU,cACzB,IAAI,MAAM,eAAe,KAAK;EAC5B,aAAa,OAAO,GAAG;EACvB,oBAAoB,IAAI,KAAK;GAC3B,OAAO;GACP,iBAAiB,MAAM;EACzB,CAAC;CACH;CAEF,KAAK,MAAM,CAAC,KAAK,UAAU,qBACzB,IAAI,MAAM,mBAAmB,KAAK,oBAAoB,OAAO,GAAG;CAElE,KAAK,MAAM,CAAC,KAAK,UAAU,aACzB,IAAI,MAAM,eAAe,KAAK,YAAY,OAAO,GAAG;AAExD;AAEA,SAAS,mBACP,aACA,KACA,OACM;CACN,YAAY,OAAO,GAAG;CACtB,YAAY,IAAI,KAAK,KAAK;CAC1B,OAAO,YAAY,OAAO,wBAAwB;EAChD,MAAM,SAAS,YAAY,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;EACzC,IAAI,WAAW,KAAA,GAAW;EAC1B,YAAY,OAAO,MAAM;CAC3B;AACF;AAEA,SAAS,eAAe,OAAuC;CAC7D,OAAO,OAAO,UAAU,YAAY,wBAAwB,KAAK,KAAK;AACxE;AAEA,SAAS,YACP,OACA,MACA,OACyB;CACzB,MAAM,SAAS,OAAO,OAAO,KAAK;CAClC,sBAAsB,QAAQ,MAAM,KAAK;CACzC,OAAO;AACT;AAEA,SAAS,OAAO,OAAgB,OAAwC;CACtE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MAAM,GAAG,MAAM,mBAAmB;CAE9C,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,IAAI,cAAc,OAAO,aAAa,cAAc,MAClD,MAAM,IAAI,MAAM,GAAG,MAAM,wBAAwB;CAEnD,OAAO;AACT"}
|
|
@@ -6,13 +6,13 @@ import { i as redactProtectedValue, r as redactProtectedReason } from "./protect
|
|
|
6
6
|
import { a as notifySandboxEventObserver, c as parseCanonicalTransportEvent, s as extractTransportEventIdentity } from "./sandbox-events-vIwmuPdl.js";
|
|
7
7
|
import { c as profileProviderModel, i as concreteModelId, s as profileModelExecutionSettings, t as assertExecutableAgentProfile } from "./model-policy-Bv1DU2fw.js";
|
|
8
8
|
import { T as executableAgentSpecSnapshot, w as executableAgentProfileSnapshot } from "./materialization-D2bdTfkK.js";
|
|
9
|
-
import { $ as defaultSelectWinner, F as createExecutorRegistry, G as createPushTraceSource, L as createWorktreeCliExecutor, P as createExecutor, T as rollingDispatch, at as runBrainLoop, et as runAgentRounds, h as settledToIteration, it as routerBrain, l as withDriverExecutor, n as createSupervisor, nt as probeSandboxCapabilities, ot as canonicalObservedModel, tt as createSandboxLineage } from "./supervisor-
|
|
9
|
+
import { $ as defaultSelectWinner, F as createExecutorRegistry, G as createPushTraceSource, L as createWorktreeCliExecutor, P as createExecutor, T as rollingDispatch, at as runBrainLoop, et as runAgentRounds, h as settledToIteration, it as routerBrain, l as withDriverExecutor, n as createSupervisor, nt as probeSandboxCapabilities, ot as canonicalObservedModel, tt as createSandboxLineage } from "./supervisor-DNX8CXui.js";
|
|
10
10
|
import "./environment-provider-DTJA4ZiM.js";
|
|
11
11
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-C7iJOWm3.js";
|
|
12
|
-
import { C as observe, O as strategyAuthorMethod, T as profileChatClient, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-
|
|
13
|
-
import { It as gateOnDeliverable, Lt as mapExecutorResult, n as supervise } from "./supervise-
|
|
14
|
-
import "./authoring-
|
|
15
|
-
import "./graph-
|
|
12
|
+
import { C as observe, O as strategyAuthorMethod, T as profileChatClient, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-eAj7HG0m.js";
|
|
13
|
+
import { It as gateOnDeliverable, Lt as mapExecutorResult, n as supervise } from "./supervise-009CRDW1.js";
|
|
14
|
+
import "./authoring-CxnWFZVk.js";
|
|
15
|
+
import "./graph-C_rMgoWQ.js";
|
|
16
16
|
import { CODING_HARNESSES, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
17
17
|
import { heldoutSignificance, runProfileMatrix } from "@tangle-network/agent-eval/campaign";
|
|
18
18
|
import { AgentEnvironmentCapabilitiesSchema, AgentExactRunControlRefSchema, AgentNativeContextContinuationResultSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, AgentTurnResultSchema, InteractionAcknowledgementSchema, InteractionResponseCommandSchema, NativeContextBoundaryProofSchema, NativeContextContinuationRequestSchema, RuntimeEventEnvelopeSchema, agentNativeContextContinuationResultMatchesRequest, agentProfileSchema, agentRunCancellationAcknowledgementMatchesRequest, agentRunCancellationRequestDigest, canonicalAgentProfileDigest, canonicalCandidateDigest, nativeContextContinuationTurnDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
@@ -6592,4 +6592,4 @@ function tail(s) {
|
|
|
6592
6592
|
//#endregion
|
|
6593
6593
|
export { InMemoryCorpus as $, pickChampion as A, renderLeaderboardSvg as At, runBenchmark as B, mcpSecretEnvMetadataKey as Bt, analyzeTrace as C, deterministicCompletion as Ct, chatWorkerSeam as D, pairwiseSignificance as Dt, chatTransportExecutor as E, leaderboard as Et, strategyAuthorContract as F, connectStdioMcp as Ft, equalKOnCost as G, recoverRetainedRun as H, resolveSecretEnv as Ht, strategyAuthorSystemPrompt as I, materializeLocalMcp as It, runPersonified as J, trajectoryReport as K, SandboxRunAbortError as L, createMcpEnvironment as Lt, selectChampion as M, auditIntent as Mt, assertStrategyContract as N, defaultAuditorInstruction as Nt, createChatSessionStore as O, renderLeaderboardHtml as Ot, authorStrategy as P, McpSpawnFault as Pt, FileCorpus as Q, openSandboxRun as R, sanitizeMcpToolSchema as Rt, withUntrackedArtifacts as S, completionAuthorizes as St, runCoderChecks as T, stopSentinel as Tt, startRetainedRun as U, secretEnvOfMcpServer as Ut, reconnectRetainedRun as V, resolveMcpServerLaunch as Vt, promotionGate as W, createShapeRegistry as X, builtinShapes as Y, registerShape as Z, VERIFY_TAIL_CHARS as _, localSandboxClient as _t, localShell as a, pipeline as at, settledWorkerOut as b, loopDispatch as bt, createVerifierEnvironment as c, widen as ct, harvestSurfaceDiffs as d, createScopeAnalyst as dt, renderCorpusToInstructions as et, failuresAnalyst as f, registryScopeAnalyst as ft, NOTE_MAX_CHARS as g, resolveSandboxClient as gt, EVIDENCE_MAX_CHARS as h, defineLeaderboard as ht, jjWorkspace as i, panel as it, runStrategyEvolution as j, renderPairwiseMarkdown as jt, discriminatingMeans as k, renderLeaderboardMarkdown as kt, boxSurfaceReader as l, assertTraceDerivedFindings as lt, worktreeFanout as m, harvestCorpus as mt, makeFinding$1 as n, flatWidenGate as nt, runInWorkspace as o, selectValidWinner as ot, superviseSurface as p, inProcessSandboxClient as pt, definePersona as q, gitWorkspace as r, loopUntil as rt, createWaterfallCollector as s, verify as st, computeFindingId$1 as t, fanout as tt, fsSurfaceReader as u, buildSteerContext as ut, closingWorkerNote as v, inlineSandboxClient as vt, patchDelivered as w, sentinelCompletion as wt, copyUntrackedIntoClone as x, superviseDispatch as xt, composeWorkerEvidence as y, loopCampaignDispatch as yt, printBenchmarkReport as z, envKeyProvider as zt };
|
|
6594
6594
|
|
|
6595
|
-
//# sourceMappingURL=runtime-
|
|
6595
|
+
//# sourceMappingURL=runtime-VwxvxGN7.js.map
|