@tangle-network/agent-runtime 0.104.0 → 0.106.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/README.md +176 -42
  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-Dy8NujB4.js +713 -0
  13. package/dist/backends-Dy8NujB4.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-XucG_K3l.js +1265 -0
  21. package/dist/conversation-XucG_K3l.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 -1134
  40. package/dist/index.js +2134 -1972
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +776 -888
  43. package/dist/intelligence.js +1466 -1410
  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-BwjQ1NfH.js +268 -0
  55. package/dist/loop-runner-bin-BwjQ1NfH.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -17
  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 -437
  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 +150 -147
  84. package/dist/primeintellect/index.js +626 -1004
  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-BG0BziaP.js +5408 -0
  100. package/dist/runtime-BG0BziaP.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 +43 -55
  130. package/skills/build-with-agent-runtime/SKILL.md +16 -9
  131. package/skills/loop-writer/SKILL.md +1 -1
  132. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  133. package/dist/analyst-loop.js.map +0 -1
  134. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  135. package/dist/candidate-execution/index.js.map +0 -1
  136. package/dist/chunk-2KGAN2HM.js +0 -1256
  137. package/dist/chunk-2KGAN2HM.js.map +0 -1
  138. package/dist/chunk-2QJSNOGK.js +0 -48
  139. package/dist/chunk-2QJSNOGK.js.map +0 -1
  140. package/dist/chunk-2UABGGUB.js +0 -474
  141. package/dist/chunk-2UABGGUB.js.map +0 -1
  142. package/dist/chunk-2VZYRB55.js +0 -834
  143. package/dist/chunk-2VZYRB55.js.map +0 -1
  144. package/dist/chunk-2X65HYMI.js +0 -3526
  145. package/dist/chunk-2X65HYMI.js.map +0 -1
  146. package/dist/chunk-3MDZX7YU.js +0 -125
  147. package/dist/chunk-3MDZX7YU.js.map +0 -1
  148. package/dist/chunk-3PPVCS75.js +0 -199
  149. package/dist/chunk-3PPVCS75.js.map +0 -1
  150. package/dist/chunk-5HNDYWUT.js +0 -6424
  151. package/dist/chunk-5HNDYWUT.js.map +0 -1
  152. package/dist/chunk-5IBQAPVB.js +0 -29
  153. package/dist/chunk-5IBQAPVB.js.map +0 -1
  154. package/dist/chunk-5QOB7H74.js +0 -387
  155. package/dist/chunk-5QOB7H74.js.map +0 -1
  156. package/dist/chunk-ATDFUJYI.js +0 -4728
  157. package/dist/chunk-ATDFUJYI.js.map +0 -1
  158. package/dist/chunk-B7K7V22Y.js +0 -699
  159. package/dist/chunk-B7K7V22Y.js.map +0 -1
  160. package/dist/chunk-DPEUKJRO.js +0 -27
  161. package/dist/chunk-DPEUKJRO.js.map +0 -1
  162. package/dist/chunk-FD2MBMOH.js +0 -494
  163. package/dist/chunk-FD2MBMOH.js.map +0 -1
  164. package/dist/chunk-FJI3EXU3.js +0 -2402
  165. package/dist/chunk-FJI3EXU3.js.map +0 -1
  166. package/dist/chunk-HAO4CXHP.js +0 -200
  167. package/dist/chunk-HAO4CXHP.js.map +0 -1
  168. package/dist/chunk-ISPWRSEC.js +0 -408
  169. package/dist/chunk-ISPWRSEC.js.map +0 -1
  170. package/dist/chunk-KRBFHMV6.js +0 -1228
  171. package/dist/chunk-KRBFHMV6.js.map +0 -1
  172. package/dist/chunk-L5DST3QC.js +0 -351
  173. package/dist/chunk-L5DST3QC.js.map +0 -1
  174. package/dist/chunk-M22PL4GH.js +0 -171
  175. package/dist/chunk-M22PL4GH.js.map +0 -1
  176. package/dist/chunk-NURIQBJQ.js +0 -72
  177. package/dist/chunk-NURIQBJQ.js.map +0 -1
  178. package/dist/chunk-PZZKQVQV.js +0 -52
  179. package/dist/chunk-PZZKQVQV.js.map +0 -1
  180. package/dist/chunk-Q2JSAVQ3.js +0 -671
  181. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  182. package/dist/chunk-SBTWKPVR.js +0 -5576
  183. package/dist/chunk-SBTWKPVR.js.map +0 -1
  184. package/dist/chunk-SGKPNBXE.js +0 -60
  185. package/dist/chunk-SGKPNBXE.js.map +0 -1
  186. package/dist/chunk-SNSMRT6H.js +0 -680
  187. package/dist/chunk-SNSMRT6H.js.map +0 -1
  188. package/dist/chunk-STJEHM5F.js +0 -1338
  189. package/dist/chunk-STJEHM5F.js.map +0 -1
  190. package/dist/chunk-UPWGXKXB.js +0 -254
  191. package/dist/chunk-UPWGXKXB.js.map +0 -1
  192. package/dist/chunk-YEJR7IXO.js +0 -68
  193. package/dist/chunk-YEJR7IXO.js.map +0 -1
  194. package/dist/chunk-ZXICDSAK.js +0 -907
  195. package/dist/chunk-ZXICDSAK.js.map +0 -1
  196. package/dist/completion-gate-Bv47cOnn.d.ts +0 -256
  197. package/dist/conversation.js.map +0 -1
  198. package/dist/coordination-CxtzMxSM.d.ts +0 -2570
  199. package/dist/environment-provider.js.map +0 -1
  200. package/dist/improve--2A0gK1-.d.ts +0 -440
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-CtK9dSny.d.ts +0 -175
  204. package/dist/loop-runner-bin-DUOGtvOl.d.ts +0 -207
  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-DzkUY3HQ.d.ts +0 -271
  209. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  210. package/dist/structural-rollout-C4mabf87.d.ts +0 -446
  211. package/dist/supervise-7q9F5brx.d.ts +0 -379
  212. package/dist/types-BCoemcXU.d.ts +0 -802
  213. package/dist/types-BwoZWq-i.d.ts +0 -510
  214. package/dist/types-Cbp72qyu.d.ts +0 -491
  215. package/dist/types-CmYCMbFT.d.ts +0 -203
  216. package/dist/types-CvNwMzQt.d.ts +0 -957
  217. package/dist/worktree-fanout-WsOzt8qu.d.ts +0 -999
@@ -0,0 +1,722 @@
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-B53sPV7M.js";
2
+ import { posix } from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ //#region src/candidate-execution/exact-process-executor.ts
5
+ const DEFAULT_PROVISION_TIMEOUT_MS = 12e4;
6
+ const DEFAULT_RECOVERY_RETENTION_MS = 15 * 6e4;
7
+ /** Adapt one neutral exact-process provider to Runtime's trusted candidate boundary. */
8
+ function exactProcessProviderAsCandidateExecutor(options) {
9
+ return new ExactProcessAgentCandidateExecutor(options);
10
+ }
11
+ var ExactProcessAgentCandidateExecutor = class {
12
+ options;
13
+ states = /* @__PURE__ */ new Map();
14
+ exactProcess;
15
+ resources;
16
+ provisionTimeoutMs;
17
+ recoveryRetentionMs;
18
+ providerOptions;
19
+ capabilitiesPromise;
20
+ constructor(options) {
21
+ this.options = options;
22
+ if (!options.provider.exactProcess) throw new Error(`agent environment provider "${options.provider.name}" does not implement exact processes`);
23
+ this.exactProcess = options.provider.exactProcess;
24
+ this.resources = exactResources(options.resources);
25
+ this.provisionTimeoutMs = positiveInteger(options.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS, "exact process provision timeout");
26
+ this.recoveryRetentionMs = positiveInteger(options.recoveryRetentionMs ?? DEFAULT_RECOVERY_RETENTION_MS, "exact process recovery retention");
27
+ this.providerOptions = options.providerOptions ? immutableCandidateValue(options.providerOptions) : void 0;
28
+ }
29
+ async execute(request, context) {
30
+ assertSupportedRequest(request);
31
+ const outcome = request.benchmark.task.outcome;
32
+ if (outcome.kind !== "output") throw new Error("exact process executor requires an output task");
33
+ const network = request.executionPlan.value.material.model.access.network;
34
+ const egress = network.mode === "disabled" ? { mode: "blocked" } : {
35
+ mode: "strict",
36
+ allowDomains: [...network.domains]
37
+ };
38
+ await this.assertCapability(egress.mode);
39
+ context.signal.throwIfAborted();
40
+ const key = executionKey(request.executionId, request.executionPlan.value.digest);
41
+ if (this.states.has(key)) throw new Error("candidate execution environment is already active");
42
+ const image = exactImage(request.executionPlan.value.material.container.image, request.executionPlan.value.material.container.manifestDigest);
43
+ const maxLifetimeMs = environmentLifetimeMs(request.hardLimits.timeoutMs, this.recoveryRetentionMs);
44
+ const createInputDigest = canonicalCandidateDigest(immutableCandidateValue({
45
+ kind: "agent-candidate-exact-process-create",
46
+ provider: this.options.provider.name,
47
+ executionId: request.executionId,
48
+ executionPlanDigest: request.executionPlan.value.digest,
49
+ image,
50
+ egress,
51
+ maxLifetimeMs,
52
+ provisionTimeoutMs: this.provisionTimeoutMs,
53
+ resources: this.resources,
54
+ output: {
55
+ mediaType: outcome.mediaType,
56
+ maxBytes: outcome.maxBytes
57
+ },
58
+ ...this.providerOptions ? { providerOptions: this.providerOptions } : {}
59
+ }));
60
+ const metadata = immutableCandidateValue({
61
+ kind: "agent-candidate-execution",
62
+ provider: this.options.provider.name,
63
+ executionId: request.executionId,
64
+ executionPlanDigest: request.executionPlan.value.digest,
65
+ createInputDigest,
66
+ outputMediaType: outcome.mediaType,
67
+ outputMaxBytes: outcome.maxBytes
68
+ });
69
+ const environment = await this.exactProcess.create({
70
+ image,
71
+ egress,
72
+ maxLifetimeMs,
73
+ provisionTimeoutMs: this.provisionTimeoutMs,
74
+ resources: this.resources,
75
+ metadata,
76
+ idempotencyKey: executionIdempotencyKey(request.executionId, request.executionPlan.value.digest),
77
+ signal: context.signal,
78
+ ...this.providerOptions ? { providerOptions: this.providerOptions } : {}
79
+ });
80
+ try {
81
+ assertExecutionEnvironment(environment, metadata, this.options.provider.name);
82
+ } catch (error) {
83
+ try {
84
+ await environment.destroy();
85
+ } catch (cleanupError) {
86
+ throw new AggregateError([error, cleanupError], "exact process validation and cleanup both failed");
87
+ }
88
+ throw error;
89
+ }
90
+ const state = { environment };
91
+ this.states.set(key, state);
92
+ if ((await environment.process.list()).length !== 0) throw new Error("fresh candidate environment already contains a process");
93
+ await materializeRequest(environment, request, context.signal);
94
+ const launch = exactLaunch(request);
95
+ const startedAt = Date.now();
96
+ state.trace = {
97
+ runId: request.trace.runId,
98
+ scenarioId: request.benchmark.task.scenario.id,
99
+ startedAt,
100
+ deadlineAtMs: context.deadlineAtMs,
101
+ timeoutMs: request.hardLimits.timeoutMs,
102
+ tags: {
103
+ ...request.trace.tags,
104
+ environmentId: environment.id,
105
+ environmentProvider: environment.provider
106
+ },
107
+ written: false
108
+ };
109
+ const process = await environment.process.spawn(launch, { signal: context.signal });
110
+ const outputPromise = collectOutput(process, outcome.maxBytes);
111
+ outputPromise.catch(() => void 0);
112
+ let cancellation;
113
+ let processExited = false;
114
+ const cancel = () => {
115
+ if (!processExited) cancellation ??= stopProcess(process);
116
+ };
117
+ context.signal.addEventListener("abort", cancel, { once: true });
118
+ if (context.signal.aborted) cancel();
119
+ try {
120
+ const termination = await process.wait();
121
+ processExited = true;
122
+ context.signal.removeEventListener("abort", cancel);
123
+ if (cancellation) await cancellation;
124
+ const status = await process.status();
125
+ assertTerminalStatus(status, termination);
126
+ state.output = await awaitOutput(outputPromise, context.signal, context.deadlineAtMs);
127
+ state.termination = termination;
128
+ await appendExactProcessTrace(state, context.traceStore, status);
129
+ return {
130
+ executionId: request.executionId,
131
+ termination
132
+ };
133
+ } finally {
134
+ context.signal.removeEventListener("abort", cancel);
135
+ }
136
+ }
137
+ async stop(request, context) {
138
+ await this.assertCapability();
139
+ context.signal.throwIfAborted();
140
+ const environment = await this.resolve(request, true);
141
+ if (!environment) return { stopped: true };
142
+ let statuses = await environment.process.list();
143
+ if (statuses.length > 1) throw new Error("candidate exact process environment contains more than one process");
144
+ const status = statuses[0];
145
+ if (status?.running) {
146
+ const process = await environment.process.get(status.pid);
147
+ if (!process) throw new Error("candidate environment lost its running process handle");
148
+ await stopProcess(process);
149
+ }
150
+ context.signal.throwIfAborted();
151
+ statuses = await environment.process.list();
152
+ if (statuses.some((entry) => entry.running)) throw new Error("candidate exact process termination is not proven");
153
+ const finalStatus = statuses[0];
154
+ if (finalStatus) assertTerminalStatus(finalStatus);
155
+ const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest));
156
+ if (state) {
157
+ state.termination = finalStatus?.termination ?? state.termination;
158
+ if (context.reason === "timeout" && state.trace) state.runtimeTermination = {
159
+ kind: "timeout",
160
+ timeoutMs: state.trace.timeoutMs
161
+ };
162
+ await appendExactProcessTrace(state, context.traceStore, finalStatus);
163
+ }
164
+ return { stopped: true };
165
+ }
166
+ async capture(request, context) {
167
+ await this.assertCapability();
168
+ context.signal.throwIfAborted();
169
+ const environment = await this.resolve(request, false);
170
+ const statuses = await environment.process.list();
171
+ const status = statuses[0];
172
+ if (statuses.length !== 1 || !status || status.running) throw new Error("candidate environment must contain one stopped process before capture");
173
+ assertTerminalStatus(status);
174
+ const process = await environment.process.get(status.pid);
175
+ if (!process) throw new Error("candidate environment lost its captured process handle");
176
+ assertTerminalStatus(await process.status(), status.termination);
177
+ const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest));
178
+ const output = state?.output ?? await awaitOutput(collectOutput(process, outputSpec(environment).maxBytes), context.signal, Date.now() + this.provisionTimeoutMs);
179
+ context.signal.throwIfAborted();
180
+ const evidence = canonicalCandidateBytes({
181
+ kind: "agent-candidate-exact-process-capture",
182
+ provider: environment.provider,
183
+ environmentId: environment.id,
184
+ executionId: request.executionId,
185
+ executionPlanDigest: request.executionPlanDigest,
186
+ createInputDigest: environment.metadata?.createInputDigest,
187
+ process: {
188
+ pid: status.pid,
189
+ exitCode: status.exitCode,
190
+ ...status.exitSignal ? { exitSignal: status.exitSignal } : {},
191
+ termination: status.termination
192
+ },
193
+ ...state?.runtimeTermination ? { runtimeTermination: state.runtimeTermination } : {},
194
+ output: {
195
+ sha256: sha256Bytes(output),
196
+ byteLength: output.byteLength
197
+ }
198
+ });
199
+ return {
200
+ taskOutcome: {
201
+ kind: "output",
202
+ bytes: output
203
+ },
204
+ evidence
205
+ };
206
+ }
207
+ async dispose(request, context) {
208
+ await this.assertCapability();
209
+ context.signal.throwIfAborted();
210
+ const environment = await this.resolve(request, true);
211
+ if (!environment) return { disposed: true };
212
+ let destroyError;
213
+ try {
214
+ await environment.destroy();
215
+ } catch (error) {
216
+ destroyError = error;
217
+ }
218
+ if (await this.exactProcess.get(environment.id)) throw new Error("exact process environment disposal is not proven", { cause: destroyError });
219
+ context.signal.throwIfAborted();
220
+ this.states.delete(executionKey(request.executionId, request.executionPlanDigest));
221
+ return { disposed: true };
222
+ }
223
+ async assertCapability(mode) {
224
+ const pending = this.capabilitiesPromise ?? Promise.resolve(this.options.provider.capabilities());
225
+ this.capabilitiesPromise = pending;
226
+ let capabilities;
227
+ try {
228
+ capabilities = await pending;
229
+ } catch (error) {
230
+ if (this.capabilitiesPromise === pending) this.capabilitiesPromise = void 0;
231
+ throw error;
232
+ }
233
+ const exact = capabilities.exactProcess;
234
+ if (!exact) throw new Error(`agent environment provider "${this.options.provider.name}" does not declare exact process support`);
235
+ if (mode && !exact.egress.includes(mode)) throw new Error(`agent environment provider "${this.options.provider.name}" does not declare ${mode} exact egress`);
236
+ }
237
+ async resolve(request, missingIsDeleted) {
238
+ const key = executionKey(request.executionId, request.executionPlanDigest);
239
+ const active = this.states.get(key)?.environment;
240
+ if (active) return active;
241
+ const metadata = {
242
+ kind: "agent-candidate-execution",
243
+ provider: this.options.provider.name,
244
+ executionId: request.executionId,
245
+ executionPlanDigest: request.executionPlanDigest
246
+ };
247
+ const matches = (await this.exactProcess.list({
248
+ metadata,
249
+ ...this.providerOptions ? { providerOptions: this.providerOptions } : {}
250
+ })).filter((environment) => environment.provider === this.options.provider.name && Object.entries(metadata).every(([name, value]) => isDeepStrictEqual(environment.metadata?.[name], value)));
251
+ if (matches.length > 1) throw new Error("multiple exact process environments match one candidate execution");
252
+ const environment = matches[0];
253
+ if (!environment) {
254
+ if (missingIsDeleted) return void 0;
255
+ throw new Error("candidate exact process evidence is unavailable");
256
+ }
257
+ if (!isSha256Digest$1(environment.metadata?.createInputDigest)) throw new Error("candidate exact process create-input digest is unavailable");
258
+ this.states.set(key, { environment });
259
+ return environment;
260
+ }
261
+ };
262
+ async function appendExactProcessTrace(state, traceStore, status) {
263
+ const trace = state.trace;
264
+ if (!trace || trace.written) return;
265
+ const endedAt = Math.max(trace.startedAt, Math.min(Date.now(), trace.deadlineAtMs));
266
+ const termination = state.runtimeTermination ?? state.termination ?? status?.termination;
267
+ await traceStore.appendRun({
268
+ runId: trace.runId,
269
+ scenarioId: trace.scenarioId,
270
+ startedAt: trace.startedAt,
271
+ endedAt,
272
+ status: termination?.kind === "exit" && termination.exitCode === 0 ? "completed" : "failed",
273
+ tags: trace.tags
274
+ });
275
+ trace.written = true;
276
+ }
277
+ function assertSupportedRequest(request) {
278
+ if (request.benchmark.task.outcome.kind !== "output") throw new Error("exact process candidate executor does not support workspace outcomes; use Pier");
279
+ if (request.executionPlan.value.material.codeKind !== "disabled" || request.inputs.candidate) throw new Error("exact process candidate executor does not support code workspaces; use Pier");
280
+ if (request.memory.mode !== "disabled") throw new Error("exact process candidate executor does not support isolated memory");
281
+ const mediaType = request.benchmark.task.outcome.mediaType.toLowerCase();
282
+ if (!(mediaType.startsWith("text/") || mediaType === "application/json" || mediaType.endsWith("+json"))) throw new Error("exact process candidate executor supports only UTF-8 text and JSON outputs");
283
+ if (!posix.isAbsolute(request.launch.executable) && !request.launch.env.PATH?.trim()) throw new Error("exact process candidate executable must be absolute or declare a signed PATH");
284
+ }
285
+ async function materializeRequest(environment, request, signal) {
286
+ const knowledgePaths = assertKnowledgeExecutionBinding(request);
287
+ for (const file of request.inputs.task.files) await environment.writeFile(beneath(request.roots.taskRoot, file.path), file.bytes, {
288
+ mode: file.mode,
289
+ signal
290
+ });
291
+ const profileRoot = request.executionPlan.value.material.profile.targetWorkspace === "task" ? request.roots.taskRoot : request.roots.candidateRoot;
292
+ if (!profileRoot) throw new Error("candidate profile targets a missing workspace");
293
+ for (const file of request.profileActivation.files) await environment.writeFile(beneath(profileRoot, file.path), Buffer.from(file.content, "utf8"), {
294
+ mode: file.mode,
295
+ signal
296
+ });
297
+ if (request.knowledge && knowledgePaths) {
298
+ for (const file of request.knowledge.files) await environment.writeFile(beneath(knowledgePaths.root, file.path), file.bytes, {
299
+ mode: file.mode,
300
+ signal
301
+ });
302
+ if (request.knowledge.retrievalConfig && knowledgePaths.retrievalConfig) await environment.writeFile(knowledgePaths.retrievalConfig, request.knowledge.retrievalConfig, {
303
+ mode: 420,
304
+ signal
305
+ });
306
+ }
307
+ if (request.instruction.delivery.kind === "utf8-file") await environment.writeFile(request.instruction.delivery.path, request.instruction.bytes, {
308
+ mode: 420,
309
+ signal
310
+ });
311
+ }
312
+ function assertKnowledgeExecutionBinding(request) {
313
+ const knowledge = request.knowledge;
314
+ if (!knowledge) {
315
+ if (request.launch.env["TANGLE_CANDIDATE_KNOWLEDGE_ROOT"] !== void 0 || request.launch.env["TANGLE_CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG"] !== void 0) throw new Error("candidate launch declares knowledge paths without verified knowledge");
316
+ return;
317
+ }
318
+ const paths = candidateKnowledgeExecutionPaths(request.roots.taskRoot, knowledge.retrievalConfig !== void 0);
319
+ if (request.launch.env["TANGLE_CANDIDATE_KNOWLEDGE_ROOT"] !== paths.root || request.launch.env["TANGLE_CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG"] !== paths.retrievalConfig) throw new Error("candidate knowledge paths do not match the signed launch environment");
320
+ const reserved = [paths.root, paths.retrievalConfig].filter((value) => value !== void 0);
321
+ const profileRoot = request.executionPlan.value.material.profile.targetWorkspace === "task" ? request.roots.taskRoot : request.roots.candidateRoot;
322
+ if ([
323
+ ...request.inputs.task.files.map((file) => beneath(request.roots.taskRoot, file.path)),
324
+ ...profileRoot ? request.profileActivation.files.map((file) => beneath(profileRoot, file.path)) : [],
325
+ ...request.instruction.delivery.kind === "utf8-file" ? [request.instruction.delivery.path] : []
326
+ ].some((path) => reserved.some((reservedPath) => path === reservedPath || path.startsWith(`${reservedPath}/`) || reservedPath.startsWith(`${path}/`)))) throw new Error("candidate knowledge paths overlap other execution inputs");
327
+ return paths;
328
+ }
329
+ function exactLaunch(request) {
330
+ const instruction = new TextDecoder("utf-8", { fatal: true }).decode(request.instruction.bytes);
331
+ const base = {
332
+ executable: request.launch.executable,
333
+ args: request.launch.args,
334
+ cwd: request.launch.cwd,
335
+ env: request.launch.env,
336
+ timeoutMs: 0
337
+ };
338
+ switch (request.instruction.delivery.kind) {
339
+ case "argv-append": return {
340
+ ...base,
341
+ args: [...base.args, instruction]
342
+ };
343
+ case "stdin-utf8": return {
344
+ ...base,
345
+ stdin: instruction
346
+ };
347
+ case "utf8-file": return base;
348
+ }
349
+ }
350
+ async function collectOutput(process, maxBytes) {
351
+ const chunks = [];
352
+ let byteLength = 0;
353
+ for await (const chunk of process.stdout()) {
354
+ const bytes = Buffer.from(chunk, "utf8");
355
+ byteLength += bytes.byteLength;
356
+ if (byteLength > maxBytes) {
357
+ let stopError;
358
+ try {
359
+ await stopProcess(process);
360
+ } catch (error) {
361
+ stopError = error;
362
+ }
363
+ throw new Error(`candidate output exceeds its ${maxBytes}-byte maximum`, { cause: stopError });
364
+ }
365
+ chunks.push(bytes);
366
+ }
367
+ return Uint8Array.from(Buffer.concat(chunks, byteLength));
368
+ }
369
+ async function awaitOutput(output, signal, deadlineAtMs) {
370
+ signal.throwIfAborted();
371
+ const remainingMs = deadlineAtMs - Date.now();
372
+ if (remainingMs <= 0) throw new Error("candidate output deadline expired");
373
+ let timer;
374
+ let onAbort;
375
+ try {
376
+ return await Promise.race([output, new Promise((_resolve, reject) => {
377
+ onAbort = () => reject(signal.reason ?? /* @__PURE__ */ new Error("candidate output cancelled"));
378
+ signal.addEventListener("abort", onAbort, { once: true });
379
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error("candidate output deadline expired")), remainingMs);
380
+ })]);
381
+ } finally {
382
+ if (onAbort) signal.removeEventListener("abort", onAbort);
383
+ if (timer) clearTimeout(timer);
384
+ }
385
+ }
386
+ async function stopProcess(process) {
387
+ if (!(await process.status()).running) return;
388
+ try {
389
+ await process.kill();
390
+ } catch (error) {
391
+ if ((await process.status()).running) throw error;
392
+ }
393
+ const termination = await process.wait();
394
+ assertTerminalStatus(await process.status(), termination);
395
+ }
396
+ function assertTerminalStatus(status, expected) {
397
+ if (status.running || !status.termination) throw new Error("exact process returned no terminal reason after exit");
398
+ if (expected && !isDeepStrictEqual(status.termination, expected)) throw new Error("exact process wait and status returned different terminal reasons");
399
+ }
400
+ function assertExecutionEnvironment(environment, metadata, providerName) {
401
+ if (!environment.id || environment.provider !== providerName) throw new Error("exact process provider returned the wrong environment identity");
402
+ if (!Object.entries(metadata).every(([name, value]) => isDeepStrictEqual(environment.metadata?.[name], value))) throw new Error("exact process provider did not persist candidate execution metadata");
403
+ }
404
+ function outputSpec(environment) {
405
+ const maxBytes = environment.metadata?.outputMaxBytes;
406
+ if (!Number.isSafeInteger(maxBytes) || Number(maxBytes) < 1) throw new Error("candidate exact process output bound is unavailable");
407
+ return { maxBytes: Number(maxBytes) };
408
+ }
409
+ function executionKey(executionId, executionPlanDigest) {
410
+ return `${executionId}\0${executionPlanDigest}`;
411
+ }
412
+ function executionIdempotencyKey(executionId, executionPlanDigest) {
413
+ return `candidate-${canonicalCandidateDigest({
414
+ kind: "agent-candidate-execution-identity",
415
+ executionId,
416
+ executionPlanDigest
417
+ }).slice(7)}`;
418
+ }
419
+ function exactImage(image, manifestDigest) {
420
+ if (isSha256Digest$1(image)) {
421
+ if (image !== manifestDigest) throw new Error("candidate container image conflicts with its resolved manifest");
422
+ return image;
423
+ }
424
+ const marker = image.lastIndexOf("@");
425
+ if (marker < 0) return `${image}@${manifestDigest}`;
426
+ if (image.slice(marker + 1) !== manifestDigest) throw new Error("candidate container image conflicts with its resolved manifest");
427
+ return image;
428
+ }
429
+ function environmentLifetimeMs(timeoutMs, retentionMs) {
430
+ const total = positiveInteger(timeoutMs, "candidate execution timeout") + retentionMs;
431
+ if (!Number.isSafeInteger(total)) throw new Error("candidate environment lifetime is too large");
432
+ return Math.ceil(total / 1e3) * 1e3;
433
+ }
434
+ function exactResources(resources) {
435
+ if (!Number.isFinite(resources.cpu) || resources.cpu <= 0) throw new Error("exact process CPU must be positive and finite");
436
+ return Object.freeze({
437
+ cpu: resources.cpu,
438
+ memoryMb: positiveInteger(resources.memoryMb, "exact process memory"),
439
+ diskMb: positiveInteger(resources.diskMb, "exact process disk")
440
+ });
441
+ }
442
+ function positiveInteger(value, label) {
443
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${label} must be a positive integer`);
444
+ return value;
445
+ }
446
+ function beneath(root, relativePath) {
447
+ if (posix.isAbsolute(relativePath)) throw new Error("candidate input path must be relative");
448
+ const path = posix.normalize(relativePath);
449
+ if (path === ".." || path.startsWith("../")) throw new Error("candidate input path escapes its execution root");
450
+ return posix.join(root, path);
451
+ }
452
+ function isSha256Digest$1(value) {
453
+ return typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value);
454
+ }
455
+ //#endregion
456
+ //#region src/candidate-execution/protected-model-port.ts
457
+ const MAX_RECENT_SETTLEMENTS = 4096;
458
+ const RECOVERED_SETTLEMENT_RETENTION_MS = 900 * 1e3;
459
+ /**
460
+ * Bind a protected model-grant service to the immutable candidate runtime.
461
+ *
462
+ * The service remains the authority for expiry, admission, revocation, and
463
+ * metering. This adapter independently checks every response before allowing
464
+ * it to cross into candidate execution or durable receipt finalization.
465
+ */
466
+ function createProtectedAgentCandidateModelPort(options) {
467
+ const gatewayDomain = assertGatewayDomain(options.gatewayDomain);
468
+ const activationEnvNames = exactEnvironmentNames(options.activationEnvNames);
469
+ const reservations = /* @__PURE__ */ new Map();
470
+ const recentSettlements = /* @__PURE__ */ new Map();
471
+ return {
472
+ resolve: async (input) => {
473
+ const request = immutableCandidateValue(input);
474
+ return immutableCandidateValue(validateResolvedModel(await options.resolveModel(request), request));
475
+ },
476
+ reserveGrant: async (input) => {
477
+ pruneExpiredState(reservations, recentSettlements, Date.now());
478
+ const request = immutableCandidateValue(input);
479
+ validateReserveInput(request);
480
+ const requestDigest = canonicalCandidateDigest(request);
481
+ const key = reservationKey(request.executionId, request.preparationId);
482
+ if (recentSettlements.has(key)) throw new Error("protected model reservation is already settled");
483
+ const previous = reservations.get(key);
484
+ if (previous && previous.requestDigest !== requestDigest) throw new Error("protected model reservation retry changed immutable input");
485
+ const reservation = validateReservation(await options.client.reserve(request), request, gatewayDomain);
486
+ const responseDigest = canonicalCandidateDigest(reservation);
487
+ if (recentSettlements.has(key)) throw new Error("protected model reservation completed after the grant was settled");
488
+ const recorded = previous ?? reservations.get(key);
489
+ if (recorded && recorded.requestDigest !== requestDigest) throw new Error("protected model reservation retry changed immutable input");
490
+ if (recorded && recorded.responseDigest !== responseDigest) throw new Error("protected model reservation retry returned different evidence");
491
+ if (!recorded) reservations.set(key, {
492
+ requestDigest,
493
+ responseDigest,
494
+ executionId: request.executionId,
495
+ preparationId: request.preparationId,
496
+ grantDigest: reservation.digest,
497
+ expiresAtMs: request.expiresAtMs,
498
+ resolved: immutableCandidateValue(request.resolved),
499
+ limits: immutableCandidateValue(request.limits),
500
+ maxCostUsdNanos: usdToNanos(request.limits.maxCostUsd, "reserved maxCostUsd"),
501
+ activation: "reserved"
502
+ });
503
+ return reservation;
504
+ },
505
+ activateGrant: async (input) => {
506
+ pruneExpiredState(reservations, recentSettlements, Date.now());
507
+ const request = immutableCandidateValue(input);
508
+ const key = reservationKey(request.executionId, request.preparationId);
509
+ if (recentSettlements.has(key)) throw new Error("protected model grant is already settled");
510
+ const state = reservations.get(key);
511
+ if (!state) throw new Error("protected model grant was not reserved by this port");
512
+ assertGrantIdentity(state, request);
513
+ if (state.settlementDigest) throw new Error("protected model grant is already settled");
514
+ if (state.activation !== "reserved") throw new Error("protected model grant activation is single-use");
515
+ if (!Number.isSafeInteger(request.deadlineAtMs) || request.deadlineAtMs <= 0) throw new Error("protected model activation deadline must be a positive safe integer");
516
+ if (request.deadlineAtMs <= Date.now()) throw new Error("protected model activation deadline must be in the future");
517
+ if (request.deadlineAtMs > state.expiresAtMs) throw new Error("protected model activation deadline exceeds the reserved expiry");
518
+ state.activation = "activating";
519
+ try {
520
+ const activation = validateActivation(await options.client.activate(request), state.limits.maxModelCalls === 0 ? [] : activationEnvNames);
521
+ if (recentSettlements.has(key) || reservations.get(key) !== state) throw new Error("protected model grant settled while activation was in flight");
522
+ state.activation = "activated";
523
+ return activation;
524
+ } catch (error) {
525
+ state.activation = "reserved";
526
+ throw error;
527
+ }
528
+ },
529
+ settleGrant: async (input) => {
530
+ const now = Date.now();
531
+ pruneExpiredState(reservations, recentSettlements, now);
532
+ const request = immutableCandidateValue(input);
533
+ const key = reservationKey(request.executionId, request.preparationId);
534
+ const state = reservations.get(key);
535
+ if (state) assertGrantIdentity(state, request);
536
+ const remembered = state ?? recentSettlements.get(key);
537
+ if (remembered?.settlementReason && remembered.settlementReason !== request.reason) throw new Error("protected model settlement retry changed the termination reason");
538
+ const sealed = sealAgentCandidateModelSettlement(await options.client.settle(request), {
539
+ preparationId: request.preparationId,
540
+ grantDigest: request.grantDigest,
541
+ model: request.resolved.model
542
+ });
543
+ if (state) assertWithinReservedLimits(sealed.usage, state);
544
+ const settlementDigest = canonicalCandidateDigest(sealed.value);
545
+ if (remembered?.settlementDigest && remembered.settlementDigest !== settlementDigest) throw new Error("protected model settlement retry returned a different final ledger");
546
+ if (remembered?.settlementReason && remembered.settlementReason !== request.reason) throw new Error("protected model settlement retry changed the termination reason");
547
+ const expiresAtMs = state?.expiresAtMs ?? now + RECOVERED_SETTLEMENT_RETENTION_MS;
548
+ if (state) {
549
+ state.settlementDigest = settlementDigest;
550
+ state.settlementReason = request.reason;
551
+ }
552
+ reservations.delete(key);
553
+ rememberSettlement(recentSettlements, key, {
554
+ settlementDigest,
555
+ settlementReason: request.reason,
556
+ expiresAtMs
557
+ });
558
+ return sealed.value;
559
+ }
560
+ };
561
+ }
562
+ function validateReserveInput(input) {
563
+ if (!Number.isSafeInteger(input.expiresAtMs) || input.expiresAtMs <= 0) throw new Error("protected model reservation expiry must be a positive safe integer");
564
+ if (input.expiresAtMs <= Date.now()) throw new Error("protected model reservation expiry must be in the future");
565
+ for (const [name, value] of [
566
+ ["maxModelCalls", input.limits.maxModelCalls],
567
+ ["maxInputTokens", input.limits.maxInputTokens],
568
+ ["maxOutputTokens", input.limits.maxOutputTokens]
569
+ ]) if (!Number.isSafeInteger(value) || value < 0) throw new Error(`protected model reservation ${name} must be a nonnegative safe integer`);
570
+ usdToNanos(input.limits.maxCostUsd, "reserved maxCostUsd");
571
+ }
572
+ function validateReservation(value, expected, gatewayDomain) {
573
+ const source = exactRecord(value, [
574
+ "preparationId",
575
+ "digest",
576
+ "expiresAtMs",
577
+ "enforcedLimits",
578
+ "network"
579
+ ], "protected model reservation response");
580
+ if (source.preparationId !== expected.preparationId) throw new Error("protected model reservation response changed preparation identity");
581
+ if (!isSha256Digest(source.digest)) throw new Error("protected model reservation response has an invalid digest");
582
+ 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");
589
+ if (canonicalCandidateDigest(source.enforcedLimits) !== canonicalCandidateDigest(expected.limits)) throw new Error("protected model reservation response changed enforced limits");
590
+ const network = validateReservationNetwork(source.network, expected.limits.maxModelCalls, gatewayDomain);
591
+ return immutableCandidateValue({
592
+ preparationId: source.preparationId,
593
+ digest: source.digest,
594
+ expiresAtMs: source.expiresAtMs,
595
+ enforcedLimits: source.enforcedLimits,
596
+ network
597
+ });
598
+ }
599
+ function validateReservationNetwork(value, maxModelCalls, gatewayDomain) {
600
+ if (maxModelCalls === 0) {
601
+ if (exactRecord(value, ["mode"], "protected model reservation network").mode !== "disabled") throw new Error("zero-call protected model reservation must disable gateway access");
602
+ return { mode: "disabled" };
603
+ }
604
+ const source = exactRecord(value, ["mode", "domains"], "protected model reservation network");
605
+ if (source.mode !== "gateway-only") throw new Error("protected model reservation must allow only its model gateway");
606
+ if (!Array.isArray(source.domains) || source.domains.length !== 1 || source.domains[0] !== gatewayDomain) throw new Error("protected model reservation returned an unexpected gateway domain");
607
+ return {
608
+ mode: "gateway-only",
609
+ domains: [gatewayDomain]
610
+ };
611
+ }
612
+ function validateActivation(value, expectedNames) {
613
+ const env = record(exactRecord(value, ["env"], "protected model activation response").env, "protected model activation environment");
614
+ const actualNames = Object.keys(env).sort();
615
+ if (actualNames.length !== expectedNames.length || actualNames.some((name, index) => name !== expectedNames[index])) throw new Error("protected model activation returned unexpected environment names");
616
+ const detached = Object.create(null);
617
+ for (const name of expectedNames) {
618
+ const value = env[name];
619
+ if (typeof value !== "string" || value.length < 8 || value.length > 65536) throw new Error(`protected model activation ${name} must be a non-empty protected value`);
620
+ detached[name] = value;
621
+ }
622
+ return Object.freeze({ env: Object.freeze(detached) });
623
+ }
624
+ function validateResolvedModel(value, expected) {
625
+ const source = exactRecord(value, [
626
+ "requested",
627
+ "provider",
628
+ "model",
629
+ "snapshot",
630
+ "reasoningEffort"
631
+ ], "resolved candidate model");
632
+ if (source.requested !== expected.requested) throw new Error("model resolver changed the evaluator-owned request");
633
+ if (source.reasoningEffort !== expected.reasoningEffort) throw new Error("model resolver changed the evaluator-owned reasoning effort");
634
+ for (const name of [
635
+ "requested",
636
+ "provider",
637
+ "model",
638
+ "snapshot"
639
+ ]) if (typeof source[name] !== "string" || source[name].length === 0) throw new Error(`resolved candidate model ${name} must be non-empty`);
640
+ return source;
641
+ }
642
+ function assertGrantIdentity(expected, actual) {
643
+ if (actual.executionId !== expected.executionId || actual.preparationId !== expected.preparationId || actual.grantDigest !== expected.grantDigest || canonicalCandidateDigest(actual.resolved) !== canonicalCandidateDigest(expected.resolved)) throw new Error("protected model grant input does not match its immutable reservation");
644
+ }
645
+ function assertWithinReservedLimits(usage, reservation) {
646
+ for (const [name, actual, limit] of [
647
+ [
648
+ "model calls",
649
+ usage.modelCalls,
650
+ reservation.limits.maxModelCalls
651
+ ],
652
+ [
653
+ "input tokens",
654
+ usage.inputTokens,
655
+ reservation.limits.maxInputTokens
656
+ ],
657
+ [
658
+ "output tokens",
659
+ usage.outputTokens,
660
+ reservation.limits.maxOutputTokens
661
+ ],
662
+ [
663
+ "cost USD nanos",
664
+ usage.costUsdNanos,
665
+ reservation.maxCostUsdNanos
666
+ ]
667
+ ]) if (actual > limit) throw new Error(`protected model settlement ${name} ${actual} exceeds reserved ${limit}`);
668
+ }
669
+ function exactEnvironmentNames(values) {
670
+ if (values.length === 0) throw new Error("protected model activation environment names must not be empty");
671
+ const names = [...values].sort();
672
+ if (new Set(names).size !== names.length) throw new Error("protected model activation environment names must be unique");
673
+ for (const name of names) if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || [
674
+ "__proto__",
675
+ "constructor",
676
+ "prototype"
677
+ ].includes(name)) throw new Error(`protected model activation environment name is invalid: ${name}`);
678
+ return Object.freeze(names);
679
+ }
680
+ function assertGatewayDomain(value) {
681
+ if (value.length > 253 || value !== value.toLowerCase() || value.endsWith(".") || value.includes(":") || value === "localhost" || value.endsWith(".localhost") || value === "metadata.google" || value === "metadata.google.internal") throw new Error("protected model gateway must be an exact lowercase public DNS name");
682
+ const labels = value.split(".");
683
+ if (labels.length < 2 || !labels.every((label) => label.length >= 1 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label)) || !/[a-z]/.test(labels.at(-1) ?? "")) throw new Error("protected model gateway must be an exact lowercase public DNS name");
684
+ return value;
685
+ }
686
+ function reservationKey(executionId, preparationId) {
687
+ return canonicalCandidateDigest({
688
+ executionId,
689
+ preparationId
690
+ });
691
+ }
692
+ function pruneExpiredState(reservations, settlements, now) {
693
+ for (const [key, value] of reservations) if (value.expiresAtMs <= now) reservations.delete(key);
694
+ for (const [key, value] of settlements) if (value.expiresAtMs <= now) settlements.delete(key);
695
+ }
696
+ function rememberSettlement(settlements, key, value) {
697
+ settlements.delete(key);
698
+ settlements.set(key, value);
699
+ while (settlements.size > MAX_RECENT_SETTLEMENTS) {
700
+ const oldest = settlements.keys().next().value;
701
+ if (oldest === void 0) return;
702
+ settlements.delete(oldest);
703
+ }
704
+ }
705
+ function isSha256Digest(value) {
706
+ return typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value);
707
+ }
708
+ function exactRecord(value, keys, label) {
709
+ const source = record(value, label);
710
+ assertExactObjectKeys(source, keys, label);
711
+ return source;
712
+ }
713
+ function record(value, label) {
714
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object`);
715
+ const prototype = Object.getPrototypeOf(value);
716
+ if (prototype !== Object.prototype && prototype !== null) throw new Error(`${label} must be a plain object`);
717
+ return value;
718
+ }
719
+ //#endregion
720
+ export { exactProcessProviderAsCandidateExecutor as n, createProtectedAgentCandidateModelPort as t };
721
+
722
+ //# sourceMappingURL=protected-model-port-BLPH5VVv.js.map