@tangle-network/agent-runtime 0.105.0 → 0.106.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +2 -2
  2. package/dist/activation-CRjVfOiy.js +203 -0
  3. package/dist/activation-CRjVfOiy.js.map +1 -0
  4. package/dist/activation-DyWB0K6E.d.ts +98 -0
  5. package/dist/agent.d.ts +216 -234
  6. package/dist/agent.js +615 -547
  7. package/dist/agent.js.map +1 -1
  8. package/dist/analyst-loop-DGdtVENg.js +517 -0
  9. package/dist/analyst-loop-DGdtVENg.js.map +1 -0
  10. package/dist/analyst-loop.d.ts +10 -43
  11. package/dist/analyst-loop.js +2 -11
  12. package/dist/backends-CiOCyRHb.js +743 -0
  13. package/dist/backends-CiOCyRHb.js.map +1 -0
  14. package/dist/candidate-execution/index.d.ts +4 -192
  15. package/dist/candidate-execution/index.js +5 -66
  16. package/dist/candidate-execution-DqMbv1rU.js +488 -0
  17. package/dist/candidate-execution-DqMbv1rU.js.map +1 -0
  18. package/dist/coder-yhVWbdWc.js +40 -0
  19. package/dist/coder-yhVWbdWc.js.map +1 -0
  20. package/dist/conversation-BpLQZGPH.js +1265 -0
  21. package/dist/conversation-BpLQZGPH.js.map +1 -0
  22. package/dist/conversation.d.ts +2 -804
  23. package/dist/conversation.js +2 -55
  24. package/dist/environment-provider-CfLUmKmf.js +1168 -0
  25. package/dist/environment-provider-CfLUmKmf.js.map +1 -0
  26. package/dist/environment-provider-IUGU3epE.d.ts +964 -0
  27. package/dist/environment-provider.d.ts +2 -78
  28. package/dist/environment-provider.js +2 -18
  29. package/dist/errors-DEAvWQPy.js +111 -0
  30. package/dist/errors-DEAvWQPy.js.map +1 -0
  31. package/dist/improvement-adapter-Cr5TBSji.d.ts +166 -0
  32. package/dist/improvement-cycle-C095kS_g.js +2624 -0
  33. package/dist/improvement-cycle-C095kS_g.js.map +1 -0
  34. package/dist/index-BGdxAwfO.d.ts +838 -0
  35. package/dist/index-C-FYUuFG.d.ts +193 -0
  36. package/dist/index-CbNM40xG.d.ts +140 -0
  37. package/dist/index-DruSKs3Z.d.ts +7224 -0
  38. package/dist/index-Efjb3nrQ.d.ts +671 -0
  39. package/dist/index.d.ts +14 -1058
  40. package/dist/index.js +2106 -2082
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +768 -889
  43. package/dist/intelligence.js +1466 -1367
  44. package/dist/intelligence.js.map +1 -1
  45. package/dist/{kb-gate-CwHO0vz6.d.ts → kb-gate-C8z2juK8.d.ts} +33 -31
  46. package/dist/kb-gate-DpaSwXVx.js +80 -0
  47. package/dist/kb-gate-DpaSwXVx.js.map +1 -0
  48. package/dist/knowledge-Ku-mPP4f.js +433 -0
  49. package/dist/knowledge-Ku-mPP4f.js.map +1 -0
  50. package/dist/knowledge.d.ts +2 -150
  51. package/dist/knowledge.js +2 -40
  52. package/dist/local-harness-Dh8PJ0ot.d.ts +455 -0
  53. package/dist/loop-runner-bin-BXsFEUcf.d.ts +162 -0
  54. package/dist/loop-runner-bin-CRagyuNb.js +268 -0
  55. package/dist/loop-runner-bin-CRagyuNb.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -15
  57. package/dist/loop-runner-bin.js +2 -24
  58. package/dist/loops.d.ts +5 -4164
  59. package/dist/loops.js +8 -419
  60. package/dist/mcp/bin.d.ts +1 -1
  61. package/dist/mcp/bin.js +116 -146
  62. package/dist/mcp/bin.js.map +1 -1
  63. package/dist/mcp/index.d.ts +295 -436
  64. package/dist/mcp/index.js +1242 -1177
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/mcp/memory-bin.d.ts +1 -1
  67. package/dist/mcp/memory-bin.js +37 -16
  68. package/dist/mcp/memory-bin.js.map +1 -1
  69. package/dist/memory-server-DL6cE2Ag.js +234 -0
  70. package/dist/memory-server-DL6cE2Ag.js.map +1 -0
  71. package/dist/model-resolution-Btd9iIKV.js +98 -0
  72. package/dist/model-resolution-Btd9iIKV.js.map +1 -0
  73. package/dist/openai-tools-B68JaOCx.d.ts +24 -0
  74. package/dist/openai-tools-CKLy1C7M.js +44 -0
  75. package/dist/openai-tools-CKLy1C7M.js.map +1 -0
  76. package/dist/otel-export-D34IQW1C.js +843 -0
  77. package/dist/otel-export-D34IQW1C.js.map +1 -0
  78. package/dist/platform.d.ts +188 -185
  79. package/dist/platform.js +185 -218
  80. package/dist/platform.js.map +1 -1
  81. package/dist/prepare-B53sPV7M.js +4292 -0
  82. package/dist/prepare-B53sPV7M.js.map +1 -0
  83. package/dist/primeintellect/index.d.ts +149 -145
  84. package/dist/primeintellect/index.js +626 -1003
  85. package/dist/primeintellect/index.js.map +1 -1
  86. package/dist/profiles.d.ts +296 -490
  87. package/dist/profiles.js +722 -749
  88. package/dist/profiles.js.map +1 -1
  89. package/dist/protected-model-port-BLPH5VVv.js +722 -0
  90. package/dist/protected-model-port-BLPH5VVv.js.map +1 -0
  91. package/dist/protected-model-port-BP6Z4eau.d.ts +283 -0
  92. package/dist/protected-redaction--F3v1oo8.js +200 -0
  93. package/dist/protected-redaction--F3v1oo8.js.map +1 -0
  94. package/dist/redact-D-u-rrcn.js +82 -0
  95. package/dist/redact-D-u-rrcn.js.map +1 -0
  96. package/dist/redact-kbIOjfjM.d.ts +452 -0
  97. package/dist/researcher-CoVqNhfI.js +433 -0
  98. package/dist/researcher-CoVqNhfI.js.map +1 -0
  99. package/dist/runtime-5zM5XxLr.js +5408 -0
  100. package/dist/runtime-5zM5XxLr.js.map +1 -0
  101. package/dist/sandbox-events-DeI5xX8P.js +316 -0
  102. package/dist/sandbox-events-DeI5xX8P.js.map +1 -0
  103. package/dist/spawn-journal-CwPvKUTa.js +456 -0
  104. package/dist/spawn-journal-CwPvKUTa.js.map +1 -0
  105. package/dist/structural-rollout-IXUEplky.js +1445 -0
  106. package/dist/structural-rollout-IXUEplky.js.map +1 -0
  107. package/dist/substrate-B0TYNrXn.js +27 -0
  108. package/dist/substrate-B0TYNrXn.js.map +1 -0
  109. package/dist/{substrate-Dyiqmd3o.d.ts → substrate-BcnuSHXm.d.ts} +57 -54
  110. package/dist/supervise-BiRutHS9.js +7321 -0
  111. package/dist/supervise-BiRutHS9.js.map +1 -0
  112. package/dist/supervisor-DTKhF-RV.js +3826 -0
  113. package/dist/supervisor-DTKhF-RV.js.map +1 -0
  114. package/dist/testing.d.ts +4 -3
  115. package/dist/testing.js +2478 -2637
  116. package/dist/testing.js.map +1 -1
  117. package/dist/tool-server-RcWgLIsL.js +141 -0
  118. package/dist/tool-server-RcWgLIsL.js.map +1 -0
  119. package/dist/trace-propagation-CJJC7SVB.js +57 -0
  120. package/dist/trace-propagation-CJJC7SVB.js.map +1 -0
  121. package/dist/types-BaIpb0XT.d.ts +492 -0
  122. package/dist/types-BevOjfTY.d.ts +765 -0
  123. package/dist/types-C9j4qg6l.d.ts +500 -0
  124. package/dist/types-Cja5OTGh.d.ts +190 -0
  125. package/dist/util-MVgdwuIS.js +145 -0
  126. package/dist/util-MVgdwuIS.js.map +1 -0
  127. package/dist/workspace-archive-BosQiotA.js +575 -0
  128. package/dist/workspace-archive-BosQiotA.js.map +1 -0
  129. package/package.json +44 -56
  130. package/skills/build-with-agent-runtime/SKILL.md +1 -0
  131. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  132. package/dist/analyst-loop.js.map +0 -1
  133. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  134. package/dist/candidate-execution/index.js.map +0 -1
  135. package/dist/chunk-2KGAN2HM.js +0 -1256
  136. package/dist/chunk-2KGAN2HM.js.map +0 -1
  137. package/dist/chunk-2VZYRB55.js +0 -834
  138. package/dist/chunk-2VZYRB55.js.map +0 -1
  139. package/dist/chunk-3MDZX7YU.js +0 -125
  140. package/dist/chunk-3MDZX7YU.js.map +0 -1
  141. package/dist/chunk-5IBQAPVB.js +0 -29
  142. package/dist/chunk-5IBQAPVB.js.map +0 -1
  143. package/dist/chunk-5QOB7H74.js +0 -387
  144. package/dist/chunk-5QOB7H74.js.map +0 -1
  145. package/dist/chunk-C5RTIBNZ.js +0 -48
  146. package/dist/chunk-C5RTIBNZ.js.map +0 -1
  147. package/dist/chunk-CTRA64LY.js +0 -680
  148. package/dist/chunk-CTRA64LY.js.map +0 -1
  149. package/dist/chunk-DPEUKJRO.js +0 -27
  150. package/dist/chunk-DPEUKJRO.js.map +0 -1
  151. package/dist/chunk-FD2MBMOH.js +0 -494
  152. package/dist/chunk-FD2MBMOH.js.map +0 -1
  153. package/dist/chunk-H5QPIZNX.js +0 -907
  154. package/dist/chunk-H5QPIZNX.js.map +0 -1
  155. package/dist/chunk-HLKC4UYB.js +0 -3514
  156. package/dist/chunk-HLKC4UYB.js.map +0 -1
  157. package/dist/chunk-HNP72PNU.js +0 -192
  158. package/dist/chunk-HNP72PNU.js.map +0 -1
  159. package/dist/chunk-ISPWRSEC.js +0 -408
  160. package/dist/chunk-ISPWRSEC.js.map +0 -1
  161. package/dist/chunk-KRBFHMV6.js +0 -1228
  162. package/dist/chunk-KRBFHMV6.js.map +0 -1
  163. package/dist/chunk-M22PL4GH.js +0 -171
  164. package/dist/chunk-M22PL4GH.js.map +0 -1
  165. package/dist/chunk-NURIQBJQ.js +0 -72
  166. package/dist/chunk-NURIQBJQ.js.map +0 -1
  167. package/dist/chunk-OPVWXJ2H.js +0 -75
  168. package/dist/chunk-OPVWXJ2H.js.map +0 -1
  169. package/dist/chunk-PZZKQVQV.js +0 -52
  170. package/dist/chunk-PZZKQVQV.js.map +0 -1
  171. package/dist/chunk-Q2JSAVQ3.js +0 -671
  172. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  173. package/dist/chunk-RDOAVVHY.js +0 -699
  174. package/dist/chunk-RDOAVVHY.js.map +0 -1
  175. package/dist/chunk-SGKPNBXE.js +0 -60
  176. package/dist/chunk-SGKPNBXE.js.map +0 -1
  177. package/dist/chunk-SMQXZGLZ.js +0 -351
  178. package/dist/chunk-SMQXZGLZ.js.map +0 -1
  179. package/dist/chunk-UHEZW5BU.js +0 -2918
  180. package/dist/chunk-UHEZW5BU.js.map +0 -1
  181. package/dist/chunk-UPWGXKXB.js +0 -254
  182. package/dist/chunk-UPWGXKXB.js.map +0 -1
  183. package/dist/chunk-VISA6CI3.js +0 -200
  184. package/dist/chunk-VISA6CI3.js.map +0 -1
  185. package/dist/chunk-WMTCUOQL.js +0 -474
  186. package/dist/chunk-WMTCUOQL.js.map +0 -1
  187. package/dist/chunk-WRTOVNN4.js +0 -4728
  188. package/dist/chunk-WRTOVNN4.js.map +0 -1
  189. package/dist/chunk-WSTRQZYQ.js +0 -5576
  190. package/dist/chunk-WSTRQZYQ.js.map +0 -1
  191. package/dist/chunk-XBG2W2VW.js +0 -6434
  192. package/dist/chunk-XBG2W2VW.js.map +0 -1
  193. package/dist/chunk-YEJR7IXO.js +0 -68
  194. package/dist/chunk-YEJR7IXO.js.map +0 -1
  195. package/dist/chunk-YJZA2BIK.js +0 -1338
  196. package/dist/chunk-YJZA2BIK.js.map +0 -1
  197. package/dist/completion-gate-BMy5LGoP.d.ts +0 -256
  198. package/dist/conversation.js.map +0 -1
  199. package/dist/coordination-BZZSVYpZ.d.ts +0 -2570
  200. package/dist/environment-provider.js.map +0 -1
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-BDNcl6jI.d.ts +0 -175
  204. package/dist/loop-runner-bin-68aoM9-7.d.ts +0 -199
  205. package/dist/loop-runner-bin.js.map +0 -1
  206. package/dist/loops.js.map +0 -1
  207. package/dist/openai-tools-fnj6SRVg.d.ts +0 -46
  208. package/dist/protected-model-port-B4t-OQjL.d.ts +0 -271
  209. package/dist/redact-BuFjxBUJ.d.ts +0 -481
  210. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  211. package/dist/structural-rollout-DEh6CEsa.d.ts +0 -446
  212. package/dist/supervise-4_48wwvy.d.ts +0 -379
  213. package/dist/types-BCoemcXU.d.ts +0 -802
  214. package/dist/types-BwoZWq-i.d.ts +0 -510
  215. package/dist/types-Cbp72qyu.d.ts +0 -491
  216. package/dist/types-CmYCMbFT.d.ts +0 -203
  217. package/dist/types-CvNwMzQt.d.ts +0 -957
  218. package/dist/worktree-fanout-DxhAWr5Z.d.ts +0 -999
@@ -1,907 +0,0 @@
1
- import {
2
- CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV,
3
- CANDIDATE_KNOWLEDGE_ROOT_ENV,
4
- assertExactObjectKeys,
5
- candidateKnowledgeExecutionPaths,
6
- canonicalCandidateBytes,
7
- canonicalCandidateDigest,
8
- immutableCandidateValue,
9
- sealAgentCandidateModelSettlement,
10
- sha256Bytes,
11
- usdToNanos
12
- } from "./chunk-WSTRQZYQ.js";
13
-
14
- // src/candidate-execution/exact-process-executor.ts
15
- import { posix } from "path";
16
- import { isDeepStrictEqual } from "util";
17
- var DEFAULT_PROVISION_TIMEOUT_MS = 12e4;
18
- var DEFAULT_RECOVERY_RETENTION_MS = 15 * 6e4;
19
- function exactProcessProviderAsCandidateExecutor(options) {
20
- return new ExactProcessAgentCandidateExecutor(options);
21
- }
22
- var ExactProcessAgentCandidateExecutor = class {
23
- constructor(options) {
24
- this.options = options;
25
- if (!options.provider.exactProcess) {
26
- throw new Error(
27
- `agent environment provider "${options.provider.name}" does not implement exact processes`
28
- );
29
- }
30
- this.exactProcess = options.provider.exactProcess;
31
- this.resources = exactResources(options.resources);
32
- this.provisionTimeoutMs = positiveInteger(
33
- options.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS,
34
- "exact process provision timeout"
35
- );
36
- this.recoveryRetentionMs = positiveInteger(
37
- options.recoveryRetentionMs ?? DEFAULT_RECOVERY_RETENTION_MS,
38
- "exact process recovery retention"
39
- );
40
- this.providerOptions = options.providerOptions ? immutableCandidateValue(options.providerOptions) : void 0;
41
- }
42
- options;
43
- states = /* @__PURE__ */ new Map();
44
- exactProcess;
45
- resources;
46
- provisionTimeoutMs;
47
- recoveryRetentionMs;
48
- providerOptions;
49
- capabilitiesPromise;
50
- async execute(request, context) {
51
- assertSupportedRequest(request);
52
- const outcome = request.benchmark.task.outcome;
53
- if (outcome.kind !== "output") throw new Error("exact process executor requires an output task");
54
- const network = request.executionPlan.value.material.model.access.network;
55
- const egress = network.mode === "disabled" ? { mode: "blocked" } : { mode: "strict", allowDomains: [...network.domains] };
56
- await this.assertCapability(egress.mode);
57
- context.signal.throwIfAborted();
58
- const key = executionKey(request.executionId, request.executionPlan.value.digest);
59
- if (this.states.has(key)) throw new Error("candidate execution environment is already active");
60
- const image = exactImage(
61
- request.executionPlan.value.material.container.image,
62
- request.executionPlan.value.material.container.manifestDigest
63
- );
64
- const maxLifetimeMs = environmentLifetimeMs(
65
- request.hardLimits.timeoutMs,
66
- this.recoveryRetentionMs
67
- );
68
- const createMaterial = immutableCandidateValue({
69
- kind: "agent-candidate-exact-process-create",
70
- provider: this.options.provider.name,
71
- executionId: request.executionId,
72
- executionPlanDigest: request.executionPlan.value.digest,
73
- image,
74
- egress,
75
- maxLifetimeMs,
76
- provisionTimeoutMs: this.provisionTimeoutMs,
77
- resources: this.resources,
78
- output: { mediaType: outcome.mediaType, maxBytes: outcome.maxBytes },
79
- ...this.providerOptions ? { providerOptions: this.providerOptions } : {}
80
- });
81
- const createInputDigest = canonicalCandidateDigest(createMaterial);
82
- const metadata = immutableCandidateValue({
83
- kind: "agent-candidate-execution",
84
- provider: this.options.provider.name,
85
- executionId: request.executionId,
86
- executionPlanDigest: request.executionPlan.value.digest,
87
- createInputDigest,
88
- outputMediaType: outcome.mediaType,
89
- outputMaxBytes: outcome.maxBytes
90
- });
91
- const environment = await this.exactProcess.create({
92
- image,
93
- egress,
94
- maxLifetimeMs,
95
- provisionTimeoutMs: this.provisionTimeoutMs,
96
- resources: this.resources,
97
- metadata,
98
- idempotencyKey: executionIdempotencyKey(
99
- request.executionId,
100
- request.executionPlan.value.digest
101
- ),
102
- signal: context.signal,
103
- ...this.providerOptions ? { providerOptions: this.providerOptions } : {}
104
- });
105
- try {
106
- assertExecutionEnvironment(environment, metadata, this.options.provider.name);
107
- } catch (error) {
108
- try {
109
- await environment.destroy();
110
- } catch (cleanupError) {
111
- throw new AggregateError(
112
- [error, cleanupError],
113
- "exact process validation and cleanup both failed"
114
- );
115
- }
116
- throw error;
117
- }
118
- const state = { environment };
119
- this.states.set(key, state);
120
- const existing = await environment.process.list();
121
- if (existing.length !== 0) {
122
- throw new Error("fresh candidate environment already contains a process");
123
- }
124
- await materializeRequest(environment, request, context.signal);
125
- const launch = exactLaunch(request);
126
- const startedAt = Date.now();
127
- state.trace = {
128
- runId: request.trace.runId,
129
- scenarioId: request.benchmark.task.scenario.id,
130
- startedAt,
131
- deadlineAtMs: context.deadlineAtMs,
132
- timeoutMs: request.hardLimits.timeoutMs,
133
- tags: {
134
- ...request.trace.tags,
135
- environmentId: environment.id,
136
- environmentProvider: environment.provider
137
- },
138
- written: false
139
- };
140
- const process = await environment.process.spawn(launch, { signal: context.signal });
141
- const outputPromise = collectOutput(process, outcome.maxBytes);
142
- void outputPromise.catch(() => void 0);
143
- let cancellation;
144
- let processExited = false;
145
- const cancel = () => {
146
- if (!processExited) cancellation ??= stopProcess(process);
147
- };
148
- context.signal.addEventListener("abort", cancel, { once: true });
149
- if (context.signal.aborted) cancel();
150
- try {
151
- const termination = await process.wait();
152
- processExited = true;
153
- context.signal.removeEventListener("abort", cancel);
154
- if (cancellation) await cancellation;
155
- const status = await process.status();
156
- assertTerminalStatus(status, termination);
157
- state.output = await awaitOutput(outputPromise, context.signal, context.deadlineAtMs);
158
- state.termination = termination;
159
- await appendExactProcessTrace(state, context.traceStore, status);
160
- return { executionId: request.executionId, termination };
161
- } finally {
162
- context.signal.removeEventListener("abort", cancel);
163
- }
164
- }
165
- async stop(request, context) {
166
- await this.assertCapability();
167
- context.signal.throwIfAborted();
168
- const environment = await this.resolve(request, true);
169
- if (!environment) return { stopped: true };
170
- let statuses = await environment.process.list();
171
- if (statuses.length > 1) {
172
- throw new Error("candidate exact process environment contains more than one process");
173
- }
174
- const status = statuses[0];
175
- if (status?.running) {
176
- const process = await environment.process.get(status.pid);
177
- if (!process) throw new Error("candidate environment lost its running process handle");
178
- await stopProcess(process);
179
- }
180
- context.signal.throwIfAborted();
181
- statuses = await environment.process.list();
182
- if (statuses.some((entry) => entry.running)) {
183
- throw new Error("candidate exact process termination is not proven");
184
- }
185
- const finalStatus = statuses[0];
186
- if (finalStatus) assertTerminalStatus(finalStatus);
187
- const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest));
188
- if (state) {
189
- state.termination = finalStatus?.termination ?? state.termination;
190
- if (context.reason === "timeout" && state.trace) {
191
- state.runtimeTermination = {
192
- kind: "timeout",
193
- timeoutMs: state.trace.timeoutMs
194
- };
195
- }
196
- await appendExactProcessTrace(state, context.traceStore, finalStatus);
197
- }
198
- return { stopped: true };
199
- }
200
- async capture(request, context) {
201
- await this.assertCapability();
202
- context.signal.throwIfAborted();
203
- const environment = await this.resolve(request, false);
204
- const statuses = await environment.process.list();
205
- const status = statuses[0];
206
- if (statuses.length !== 1 || !status || status.running) {
207
- throw new Error("candidate environment must contain one stopped process before capture");
208
- }
209
- assertTerminalStatus(status);
210
- const process = await environment.process.get(status.pid);
211
- if (!process) throw new Error("candidate environment lost its captured process handle");
212
- const currentStatus = await process.status();
213
- assertTerminalStatus(currentStatus, status.termination);
214
- const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest));
215
- const output = state?.output ?? await awaitOutput(
216
- collectOutput(process, outputSpec(environment).maxBytes),
217
- context.signal,
218
- Date.now() + this.provisionTimeoutMs
219
- );
220
- context.signal.throwIfAborted();
221
- const evidence = canonicalCandidateBytes({
222
- kind: "agent-candidate-exact-process-capture",
223
- provider: environment.provider,
224
- environmentId: environment.id,
225
- executionId: request.executionId,
226
- executionPlanDigest: request.executionPlanDigest,
227
- createInputDigest: environment.metadata?.createInputDigest,
228
- process: {
229
- pid: status.pid,
230
- exitCode: status.exitCode,
231
- ...status.exitSignal ? { exitSignal: status.exitSignal } : {},
232
- termination: status.termination
233
- },
234
- ...state?.runtimeTermination ? { runtimeTermination: state.runtimeTermination } : {},
235
- output: { sha256: sha256Bytes(output), byteLength: output.byteLength }
236
- });
237
- return {
238
- taskOutcome: { kind: "output", bytes: output },
239
- evidence
240
- };
241
- }
242
- async dispose(request, context) {
243
- await this.assertCapability();
244
- context.signal.throwIfAborted();
245
- const environment = await this.resolve(request, true);
246
- if (!environment) return { disposed: true };
247
- let destroyError;
248
- try {
249
- await environment.destroy();
250
- } catch (error) {
251
- destroyError = error;
252
- }
253
- const remaining = await this.exactProcess.get(environment.id);
254
- if (remaining) {
255
- throw new Error("exact process environment disposal is not proven", { cause: destroyError });
256
- }
257
- context.signal.throwIfAborted();
258
- this.states.delete(executionKey(request.executionId, request.executionPlanDigest));
259
- return { disposed: true };
260
- }
261
- async assertCapability(mode) {
262
- const pending = this.capabilitiesPromise ?? Promise.resolve(this.options.provider.capabilities());
263
- this.capabilitiesPromise = pending;
264
- let capabilities;
265
- try {
266
- capabilities = await pending;
267
- } catch (error) {
268
- if (this.capabilitiesPromise === pending) this.capabilitiesPromise = void 0;
269
- throw error;
270
- }
271
- const exact = capabilities.exactProcess;
272
- if (!exact) {
273
- throw new Error(
274
- `agent environment provider "${this.options.provider.name}" does not declare exact process support`
275
- );
276
- }
277
- if (mode && !exact.egress.includes(mode)) {
278
- throw new Error(
279
- `agent environment provider "${this.options.provider.name}" does not declare ${mode} exact egress`
280
- );
281
- }
282
- }
283
- async resolve(request, missingIsDeleted) {
284
- const key = executionKey(request.executionId, request.executionPlanDigest);
285
- const active = this.states.get(key)?.environment;
286
- if (active) return active;
287
- const metadata = {
288
- kind: "agent-candidate-execution",
289
- provider: this.options.provider.name,
290
- executionId: request.executionId,
291
- executionPlanDigest: request.executionPlanDigest
292
- };
293
- const listed = await this.exactProcess.list({
294
- metadata,
295
- ...this.providerOptions ? { providerOptions: this.providerOptions } : {}
296
- });
297
- const matches = listed.filter(
298
- (environment2) => environment2.provider === this.options.provider.name && Object.entries(metadata).every(
299
- ([name, value]) => isDeepStrictEqual(environment2.metadata?.[name], value)
300
- )
301
- );
302
- if (matches.length > 1) {
303
- throw new Error("multiple exact process environments match one candidate execution");
304
- }
305
- const environment = matches[0];
306
- if (!environment) {
307
- if (missingIsDeleted) return void 0;
308
- throw new Error("candidate exact process evidence is unavailable");
309
- }
310
- if (!isSha256Digest(environment.metadata?.createInputDigest)) {
311
- throw new Error("candidate exact process create-input digest is unavailable");
312
- }
313
- this.states.set(key, { environment });
314
- return environment;
315
- }
316
- };
317
- async function appendExactProcessTrace(state, traceStore, status) {
318
- const trace = state.trace;
319
- if (!trace || trace.written) return;
320
- const endedAt = Math.max(trace.startedAt, Math.min(Date.now(), trace.deadlineAtMs));
321
- const termination = state.runtimeTermination ?? state.termination ?? status?.termination;
322
- await traceStore.appendRun({
323
- runId: trace.runId,
324
- scenarioId: trace.scenarioId,
325
- startedAt: trace.startedAt,
326
- endedAt,
327
- status: termination?.kind === "exit" && termination.exitCode === 0 ? "completed" : "failed",
328
- tags: trace.tags
329
- });
330
- trace.written = true;
331
- }
332
- function assertSupportedRequest(request) {
333
- if (request.benchmark.task.outcome.kind !== "output") {
334
- throw new Error(
335
- "exact process candidate executor does not support workspace outcomes; use Pier"
336
- );
337
- }
338
- if (request.executionPlan.value.material.codeKind !== "disabled" || request.inputs.candidate) {
339
- throw new Error("exact process candidate executor does not support code workspaces; use Pier");
340
- }
341
- if (request.memory.mode !== "disabled") {
342
- throw new Error("exact process candidate executor does not support isolated memory");
343
- }
344
- const mediaType = request.benchmark.task.outcome.mediaType.toLowerCase();
345
- if (!(mediaType.startsWith("text/") || mediaType === "application/json" || mediaType.endsWith("+json"))) {
346
- throw new Error("exact process candidate executor supports only UTF-8 text and JSON outputs");
347
- }
348
- if (!posix.isAbsolute(request.launch.executable) && !request.launch.env.PATH?.trim()) {
349
- throw new Error("exact process candidate executable must be absolute or declare a signed PATH");
350
- }
351
- }
352
- async function materializeRequest(environment, request, signal) {
353
- const knowledgePaths = assertKnowledgeExecutionBinding(request);
354
- for (const file of request.inputs.task.files) {
355
- await environment.writeFile(beneath(request.roots.taskRoot, file.path), file.bytes, {
356
- mode: file.mode,
357
- signal
358
- });
359
- }
360
- const profileRoot = request.executionPlan.value.material.profile.targetWorkspace === "task" ? request.roots.taskRoot : request.roots.candidateRoot;
361
- if (!profileRoot) throw new Error("candidate profile targets a missing workspace");
362
- for (const file of request.profileActivation.files) {
363
- await environment.writeFile(
364
- beneath(profileRoot, file.path),
365
- Buffer.from(file.content, "utf8"),
366
- { mode: file.mode, signal }
367
- );
368
- }
369
- if (request.knowledge && knowledgePaths) {
370
- for (const file of request.knowledge.files) {
371
- await environment.writeFile(beneath(knowledgePaths.root, file.path), file.bytes, {
372
- mode: file.mode,
373
- signal
374
- });
375
- }
376
- if (request.knowledge.retrievalConfig && knowledgePaths.retrievalConfig) {
377
- await environment.writeFile(
378
- knowledgePaths.retrievalConfig,
379
- request.knowledge.retrievalConfig,
380
- { mode: 420, signal }
381
- );
382
- }
383
- }
384
- if (request.instruction.delivery.kind === "utf8-file") {
385
- await environment.writeFile(request.instruction.delivery.path, request.instruction.bytes, {
386
- mode: 420,
387
- signal
388
- });
389
- }
390
- }
391
- function assertKnowledgeExecutionBinding(request) {
392
- const knowledge = request.knowledge;
393
- if (!knowledge) {
394
- if (request.launch.env[CANDIDATE_KNOWLEDGE_ROOT_ENV] !== void 0 || request.launch.env[CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV] !== void 0) {
395
- throw new Error("candidate launch declares knowledge paths without verified knowledge");
396
- }
397
- return void 0;
398
- }
399
- const paths = candidateKnowledgeExecutionPaths(
400
- request.roots.taskRoot,
401
- knowledge.retrievalConfig !== void 0
402
- );
403
- if (request.launch.env[CANDIDATE_KNOWLEDGE_ROOT_ENV] !== paths.root || request.launch.env[CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV] !== paths.retrievalConfig) {
404
- throw new Error("candidate knowledge paths do not match the signed launch environment");
405
- }
406
- const reserved = [paths.root, paths.retrievalConfig].filter(
407
- (value) => value !== void 0
408
- );
409
- const profileRoot = request.executionPlan.value.material.profile.targetWorkspace === "task" ? request.roots.taskRoot : request.roots.candidateRoot;
410
- const otherFiles = [
411
- ...request.inputs.task.files.map((file) => beneath(request.roots.taskRoot, file.path)),
412
- ...profileRoot ? request.profileActivation.files.map((file) => beneath(profileRoot, file.path)) : [],
413
- ...request.instruction.delivery.kind === "utf8-file" ? [request.instruction.delivery.path] : []
414
- ];
415
- if (otherFiles.some(
416
- (path) => reserved.some(
417
- (reservedPath) => path === reservedPath || path.startsWith(`${reservedPath}/`) || reservedPath.startsWith(`${path}/`)
418
- )
419
- )) {
420
- throw new Error("candidate knowledge paths overlap other execution inputs");
421
- }
422
- return paths;
423
- }
424
- function exactLaunch(request) {
425
- const instruction = new TextDecoder("utf-8", { fatal: true }).decode(request.instruction.bytes);
426
- const base = {
427
- executable: request.launch.executable,
428
- args: request.launch.args,
429
- cwd: request.launch.cwd,
430
- env: request.launch.env,
431
- timeoutMs: 0
432
- };
433
- switch (request.instruction.delivery.kind) {
434
- case "argv-append":
435
- return { ...base, args: [...base.args, instruction] };
436
- case "stdin-utf8":
437
- return { ...base, stdin: instruction };
438
- case "utf8-file":
439
- return base;
440
- }
441
- }
442
- async function collectOutput(process, maxBytes) {
443
- const chunks = [];
444
- let byteLength = 0;
445
- for await (const chunk of process.stdout()) {
446
- const bytes = Buffer.from(chunk, "utf8");
447
- byteLength += bytes.byteLength;
448
- if (byteLength > maxBytes) {
449
- let stopError;
450
- try {
451
- await stopProcess(process);
452
- } catch (error) {
453
- stopError = error;
454
- }
455
- throw new Error(`candidate output exceeds its ${maxBytes}-byte maximum`, {
456
- cause: stopError
457
- });
458
- }
459
- chunks.push(bytes);
460
- }
461
- return Uint8Array.from(Buffer.concat(chunks, byteLength));
462
- }
463
- async function awaitOutput(output, signal, deadlineAtMs) {
464
- signal.throwIfAborted();
465
- const remainingMs = deadlineAtMs - Date.now();
466
- if (remainingMs <= 0) throw new Error("candidate output deadline expired");
467
- let timer;
468
- let onAbort;
469
- try {
470
- return await Promise.race([
471
- output,
472
- new Promise((_resolve, reject) => {
473
- onAbort = () => reject(signal.reason ?? new Error("candidate output cancelled"));
474
- signal.addEventListener("abort", onAbort, { once: true });
475
- timer = setTimeout(
476
- () => reject(new Error("candidate output deadline expired")),
477
- remainingMs
478
- );
479
- })
480
- ]);
481
- } finally {
482
- if (onAbort) signal.removeEventListener("abort", onAbort);
483
- if (timer) clearTimeout(timer);
484
- }
485
- }
486
- async function stopProcess(process) {
487
- const before = await process.status();
488
- if (!before.running) return;
489
- try {
490
- await process.kill();
491
- } catch (error) {
492
- if ((await process.status()).running) throw error;
493
- }
494
- const termination = await process.wait();
495
- assertTerminalStatus(await process.status(), termination);
496
- }
497
- function assertTerminalStatus(status, expected) {
498
- if (status.running || !status.termination) {
499
- throw new Error("exact process returned no terminal reason after exit");
500
- }
501
- if (expected && !isDeepStrictEqual(status.termination, expected)) {
502
- throw new Error("exact process wait and status returned different terminal reasons");
503
- }
504
- }
505
- function assertExecutionEnvironment(environment, metadata, providerName) {
506
- if (!environment.id || environment.provider !== providerName) {
507
- throw new Error("exact process provider returned the wrong environment identity");
508
- }
509
- if (!Object.entries(metadata).every(
510
- ([name, value]) => isDeepStrictEqual(environment.metadata?.[name], value)
511
- )) {
512
- throw new Error("exact process provider did not persist candidate execution metadata");
513
- }
514
- }
515
- function outputSpec(environment) {
516
- const maxBytes = environment.metadata?.outputMaxBytes;
517
- if (!Number.isSafeInteger(maxBytes) || Number(maxBytes) < 1) {
518
- throw new Error("candidate exact process output bound is unavailable");
519
- }
520
- return { maxBytes: Number(maxBytes) };
521
- }
522
- function executionKey(executionId, executionPlanDigest) {
523
- return `${executionId}\0${executionPlanDigest}`;
524
- }
525
- function executionIdempotencyKey(executionId, executionPlanDigest) {
526
- return `candidate-${canonicalCandidateDigest({
527
- kind: "agent-candidate-execution-identity",
528
- executionId,
529
- executionPlanDigest
530
- }).slice("sha256:".length)}`;
531
- }
532
- function exactImage(image, manifestDigest) {
533
- if (isSha256Digest(image)) {
534
- if (image !== manifestDigest) {
535
- throw new Error("candidate container image conflicts with its resolved manifest");
536
- }
537
- return image;
538
- }
539
- const marker = image.lastIndexOf("@");
540
- if (marker < 0) return `${image}@${manifestDigest}`;
541
- if (image.slice(marker + 1) !== manifestDigest) {
542
- throw new Error("candidate container image conflicts with its resolved manifest");
543
- }
544
- return image;
545
- }
546
- function environmentLifetimeMs(timeoutMs, retentionMs) {
547
- const total = positiveInteger(timeoutMs, "candidate execution timeout") + retentionMs;
548
- if (!Number.isSafeInteger(total)) throw new Error("candidate environment lifetime is too large");
549
- return Math.ceil(total / 1e3) * 1e3;
550
- }
551
- function exactResources(resources) {
552
- if (!Number.isFinite(resources.cpu) || resources.cpu <= 0) {
553
- throw new Error("exact process CPU must be positive and finite");
554
- }
555
- return Object.freeze({
556
- cpu: resources.cpu,
557
- memoryMb: positiveInteger(resources.memoryMb, "exact process memory"),
558
- diskMb: positiveInteger(resources.diskMb, "exact process disk")
559
- });
560
- }
561
- function positiveInteger(value, label) {
562
- if (!Number.isSafeInteger(value) || value < 1)
563
- throw new Error(`${label} must be a positive integer`);
564
- return value;
565
- }
566
- function beneath(root, relativePath) {
567
- if (posix.isAbsolute(relativePath)) throw new Error("candidate input path must be relative");
568
- const path = posix.normalize(relativePath);
569
- if (path === ".." || path.startsWith("../")) {
570
- throw new Error("candidate input path escapes its execution root");
571
- }
572
- return posix.join(root, path);
573
- }
574
- function isSha256Digest(value) {
575
- return typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value);
576
- }
577
-
578
- // src/candidate-execution/protected-model-port.ts
579
- var MAX_RECENT_SETTLEMENTS = 4096;
580
- var RECOVERED_SETTLEMENT_RETENTION_MS = 15 * 60 * 1e3;
581
- function createProtectedAgentCandidateModelPort(options) {
582
- const gatewayDomain = assertGatewayDomain(options.gatewayDomain);
583
- const activationEnvNames = exactEnvironmentNames(options.activationEnvNames);
584
- const reservations = /* @__PURE__ */ new Map();
585
- const recentSettlements = /* @__PURE__ */ new Map();
586
- return {
587
- resolve: async (input) => {
588
- const request = immutableCandidateValue(input);
589
- const resolved = validateResolvedModel(await options.resolveModel(request), request);
590
- return immutableCandidateValue(resolved);
591
- },
592
- reserveGrant: async (input) => {
593
- pruneExpiredState(reservations, recentSettlements, Date.now());
594
- const request = immutableCandidateValue(input);
595
- validateReserveInput(request);
596
- const requestDigest = canonicalCandidateDigest(request);
597
- const key = reservationKey(request.executionId, request.preparationId);
598
- if (recentSettlements.has(key)) {
599
- throw new Error("protected model reservation is already settled");
600
- }
601
- const previous = reservations.get(key);
602
- if (previous && previous.requestDigest !== requestDigest) {
603
- throw new Error("protected model reservation retry changed immutable input");
604
- }
605
- const reservation = validateReservation(
606
- await options.client.reserve(request),
607
- request,
608
- gatewayDomain
609
- );
610
- const responseDigest = canonicalCandidateDigest(reservation);
611
- if (recentSettlements.has(key)) {
612
- throw new Error("protected model reservation completed after the grant was settled");
613
- }
614
- const recorded = previous ?? reservations.get(key);
615
- if (recorded && recorded.requestDigest !== requestDigest) {
616
- throw new Error("protected model reservation retry changed immutable input");
617
- }
618
- if (recorded && recorded.responseDigest !== responseDigest) {
619
- throw new Error("protected model reservation retry returned different evidence");
620
- }
621
- if (!recorded) {
622
- reservations.set(key, {
623
- requestDigest,
624
- responseDigest,
625
- executionId: request.executionId,
626
- preparationId: request.preparationId,
627
- grantDigest: reservation.digest,
628
- expiresAtMs: request.expiresAtMs,
629
- resolved: immutableCandidateValue(request.resolved),
630
- limits: immutableCandidateValue(request.limits),
631
- maxCostUsdNanos: usdToNanos(request.limits.maxCostUsd, "reserved maxCostUsd"),
632
- activation: "reserved"
633
- });
634
- }
635
- return reservation;
636
- },
637
- activateGrant: async (input) => {
638
- pruneExpiredState(reservations, recentSettlements, Date.now());
639
- const request = immutableCandidateValue(input);
640
- const key = reservationKey(request.executionId, request.preparationId);
641
- if (recentSettlements.has(key)) throw new Error("protected model grant is already settled");
642
- const state = reservations.get(key);
643
- if (!state) throw new Error("protected model grant was not reserved by this port");
644
- assertGrantIdentity(state, request);
645
- if (state.settlementDigest) throw new Error("protected model grant is already settled");
646
- if (state.activation !== "reserved") {
647
- throw new Error("protected model grant activation is single-use");
648
- }
649
- if (!Number.isSafeInteger(request.deadlineAtMs) || request.deadlineAtMs <= 0) {
650
- throw new Error("protected model activation deadline must be a positive safe integer");
651
- }
652
- if (request.deadlineAtMs <= Date.now()) {
653
- throw new Error("protected model activation deadline must be in the future");
654
- }
655
- if (request.deadlineAtMs > state.expiresAtMs) {
656
- throw new Error("protected model activation deadline exceeds the reserved expiry");
657
- }
658
- state.activation = "activating";
659
- try {
660
- const activation = validateActivation(
661
- await options.client.activate(request),
662
- state.limits.maxModelCalls === 0 ? [] : activationEnvNames
663
- );
664
- if (recentSettlements.has(key) || reservations.get(key) !== state) {
665
- throw new Error("protected model grant settled while activation was in flight");
666
- }
667
- state.activation = "activated";
668
- return activation;
669
- } catch (error) {
670
- state.activation = "reserved";
671
- throw error;
672
- }
673
- },
674
- settleGrant: async (input) => {
675
- const now = Date.now();
676
- pruneExpiredState(reservations, recentSettlements, now);
677
- const request = immutableCandidateValue(input);
678
- const key = reservationKey(request.executionId, request.preparationId);
679
- const state = reservations.get(key);
680
- if (state) assertGrantIdentity(state, request);
681
- const remembered = state ?? recentSettlements.get(key);
682
- if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {
683
- throw new Error("protected model settlement retry changed the termination reason");
684
- }
685
- const sealed = sealAgentCandidateModelSettlement(await options.client.settle(request), {
686
- preparationId: request.preparationId,
687
- grantDigest: request.grantDigest,
688
- model: request.resolved.model
689
- });
690
- if (state) assertWithinReservedLimits(sealed.usage, state);
691
- const settlementDigest = canonicalCandidateDigest(sealed.value);
692
- if (remembered?.settlementDigest && remembered.settlementDigest !== settlementDigest) {
693
- throw new Error("protected model settlement retry returned a different final ledger");
694
- }
695
- if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {
696
- throw new Error("protected model settlement retry changed the termination reason");
697
- }
698
- const expiresAtMs = state?.expiresAtMs ?? now + RECOVERED_SETTLEMENT_RETENTION_MS;
699
- if (state) {
700
- state.settlementDigest = settlementDigest;
701
- state.settlementReason = request.reason;
702
- }
703
- reservations.delete(key);
704
- rememberSettlement(recentSettlements, key, {
705
- settlementDigest,
706
- settlementReason: request.reason,
707
- expiresAtMs
708
- });
709
- return sealed.value;
710
- }
711
- };
712
- }
713
- function validateReserveInput(input) {
714
- if (!Number.isSafeInteger(input.expiresAtMs) || input.expiresAtMs <= 0) {
715
- throw new Error("protected model reservation expiry must be a positive safe integer");
716
- }
717
- if (input.expiresAtMs <= Date.now()) {
718
- throw new Error("protected model reservation expiry must be in the future");
719
- }
720
- for (const [name, value] of [
721
- ["maxModelCalls", input.limits.maxModelCalls],
722
- ["maxInputTokens", input.limits.maxInputTokens],
723
- ["maxOutputTokens", input.limits.maxOutputTokens]
724
- ]) {
725
- if (!Number.isSafeInteger(value) || value < 0) {
726
- throw new Error(`protected model reservation ${name} must be a nonnegative safe integer`);
727
- }
728
- }
729
- usdToNanos(input.limits.maxCostUsd, "reserved maxCostUsd");
730
- }
731
- function validateReservation(value, expected, gatewayDomain) {
732
- const source = exactRecord(
733
- value,
734
- ["preparationId", "digest", "expiresAtMs", "enforcedLimits", "network"],
735
- "protected model reservation response"
736
- );
737
- if (source.preparationId !== expected.preparationId) {
738
- throw new Error("protected model reservation response changed preparation identity");
739
- }
740
- if (!isSha256Digest2(source.digest)) {
741
- throw new Error("protected model reservation response has an invalid digest");
742
- }
743
- if (source.expiresAtMs !== expected.expiresAtMs) {
744
- throw new Error("protected model reservation response changed expiry");
745
- }
746
- exactRecord(
747
- source.enforcedLimits,
748
- ["maxModelCalls", "maxInputTokens", "maxOutputTokens", "maxCostUsd"],
749
- "protected model reservation enforced limits"
750
- );
751
- if (canonicalCandidateDigest(source.enforcedLimits) !== canonicalCandidateDigest(expected.limits)) {
752
- throw new Error("protected model reservation response changed enforced limits");
753
- }
754
- const network = validateReservationNetwork(
755
- source.network,
756
- expected.limits.maxModelCalls,
757
- gatewayDomain
758
- );
759
- return immutableCandidateValue({
760
- preparationId: source.preparationId,
761
- digest: source.digest,
762
- expiresAtMs: source.expiresAtMs,
763
- enforcedLimits: source.enforcedLimits,
764
- network
765
- });
766
- }
767
- function validateReservationNetwork(value, maxModelCalls, gatewayDomain) {
768
- if (maxModelCalls === 0) {
769
- const source2 = exactRecord(value, ["mode"], "protected model reservation network");
770
- if (source2.mode !== "disabled") {
771
- throw new Error("zero-call protected model reservation must disable gateway access");
772
- }
773
- return { mode: "disabled" };
774
- }
775
- const source = exactRecord(value, ["mode", "domains"], "protected model reservation network");
776
- if (source.mode !== "gateway-only") {
777
- throw new Error("protected model reservation must allow only its model gateway");
778
- }
779
- if (!Array.isArray(source.domains) || source.domains.length !== 1 || source.domains[0] !== gatewayDomain) {
780
- throw new Error("protected model reservation returned an unexpected gateway domain");
781
- }
782
- return { mode: "gateway-only", domains: [gatewayDomain] };
783
- }
784
- function validateActivation(value, expectedNames) {
785
- const source = exactRecord(value, ["env"], "protected model activation response");
786
- const env = record(source.env, "protected model activation environment");
787
- const actualNames = Object.keys(env).sort();
788
- if (actualNames.length !== expectedNames.length || actualNames.some((name, index) => name !== expectedNames[index])) {
789
- throw new Error("protected model activation returned unexpected environment names");
790
- }
791
- const detached = /* @__PURE__ */ Object.create(null);
792
- for (const name of expectedNames) {
793
- const value2 = env[name];
794
- if (typeof value2 !== "string" || value2.length < 8 || value2.length > 65536) {
795
- throw new Error(`protected model activation ${name} must be a non-empty protected value`);
796
- }
797
- detached[name] = value2;
798
- }
799
- return Object.freeze({ env: Object.freeze(detached) });
800
- }
801
- function validateResolvedModel(value, expected) {
802
- const source = exactRecord(
803
- value,
804
- ["requested", "provider", "model", "snapshot", "reasoningEffort"],
805
- "resolved candidate model"
806
- );
807
- if (source.requested !== expected.requested) {
808
- throw new Error("model resolver changed the evaluator-owned request");
809
- }
810
- if (source.reasoningEffort !== expected.reasoningEffort) {
811
- throw new Error("model resolver changed the evaluator-owned reasoning effort");
812
- }
813
- for (const name of ["requested", "provider", "model", "snapshot"]) {
814
- if (typeof source[name] !== "string" || source[name].length === 0) {
815
- throw new Error(`resolved candidate model ${name} must be non-empty`);
816
- }
817
- }
818
- return source;
819
- }
820
- function assertGrantIdentity(expected, actual) {
821
- if (actual.executionId !== expected.executionId || actual.preparationId !== expected.preparationId || actual.grantDigest !== expected.grantDigest || canonicalCandidateDigest(actual.resolved) !== canonicalCandidateDigest(expected.resolved)) {
822
- throw new Error("protected model grant input does not match its immutable reservation");
823
- }
824
- }
825
- function assertWithinReservedLimits(usage, reservation) {
826
- for (const [name, actual, limit] of [
827
- ["model calls", usage.modelCalls, reservation.limits.maxModelCalls],
828
- ["input tokens", usage.inputTokens, reservation.limits.maxInputTokens],
829
- ["output tokens", usage.outputTokens, reservation.limits.maxOutputTokens],
830
- ["cost USD nanos", usage.costUsdNanos, reservation.maxCostUsdNanos]
831
- ]) {
832
- if (actual > limit) {
833
- throw new Error(`protected model settlement ${name} ${actual} exceeds reserved ${limit}`);
834
- }
835
- }
836
- }
837
- function exactEnvironmentNames(values) {
838
- if (values.length === 0) {
839
- throw new Error("protected model activation environment names must not be empty");
840
- }
841
- const names = [...values].sort();
842
- if (new Set(names).size !== names.length) {
843
- throw new Error("protected model activation environment names must be unique");
844
- }
845
- for (const name of names) {
846
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || ["__proto__", "constructor", "prototype"].includes(name)) {
847
- throw new Error(`protected model activation environment name is invalid: ${name}`);
848
- }
849
- }
850
- return Object.freeze(names);
851
- }
852
- function assertGatewayDomain(value) {
853
- if (value.length > 253 || value !== value.toLowerCase() || value.endsWith(".") || value.includes(":") || value === "localhost" || value.endsWith(".localhost") || value === "metadata.google" || value === "metadata.google.internal") {
854
- throw new Error("protected model gateway must be an exact lowercase public DNS name");
855
- }
856
- const labels = value.split(".");
857
- if (labels.length < 2 || !labels.every(
858
- (label) => label.length >= 1 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label)
859
- ) || !/[a-z]/.test(labels.at(-1) ?? "")) {
860
- throw new Error("protected model gateway must be an exact lowercase public DNS name");
861
- }
862
- return value;
863
- }
864
- function reservationKey(executionId, preparationId) {
865
- return canonicalCandidateDigest({ executionId, preparationId });
866
- }
867
- function pruneExpiredState(reservations, settlements, now) {
868
- for (const [key, value] of reservations) {
869
- if (value.expiresAtMs <= now) reservations.delete(key);
870
- }
871
- for (const [key, value] of settlements) {
872
- if (value.expiresAtMs <= now) settlements.delete(key);
873
- }
874
- }
875
- function rememberSettlement(settlements, key, value) {
876
- settlements.delete(key);
877
- settlements.set(key, value);
878
- while (settlements.size > MAX_RECENT_SETTLEMENTS) {
879
- const oldest = settlements.keys().next().value;
880
- if (oldest === void 0) return;
881
- settlements.delete(oldest);
882
- }
883
- }
884
- function isSha256Digest2(value) {
885
- return typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value);
886
- }
887
- function exactRecord(value, keys, label) {
888
- const source = record(value, label);
889
- assertExactObjectKeys(source, keys, label);
890
- return source;
891
- }
892
- function record(value, label) {
893
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
894
- throw new Error(`${label} must be an object`);
895
- }
896
- const prototype = Object.getPrototypeOf(value);
897
- if (prototype !== Object.prototype && prototype !== null) {
898
- throw new Error(`${label} must be a plain object`);
899
- }
900
- return value;
901
- }
902
-
903
- export {
904
- exactProcessProviderAsCandidateExecutor,
905
- createProtectedAgentCandidateModelPort
906
- };
907
- //# sourceMappingURL=chunk-H5QPIZNX.js.map