@tangle-network/agent-eval 0.143.0 → 0.144.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 (79) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +21 -8
  3. package/dist/analyst/index.d.ts +82 -17
  4. package/dist/analyst/index.d.ts.map +1 -1
  5. package/dist/analyst/index.js +4 -4
  6. package/dist/{benchmark-command-CSddvlq7.js → benchmark-command-95Zqd1e8.js} +333 -111
  7. package/dist/benchmark-command-95Zqd1e8.js.map +1 -0
  8. package/dist/benchmarks/index.d.ts +1 -1
  9. package/dist/benchmarks/index.js +1 -1
  10. package/dist/{benchmarks-Dg0B56tK.js → benchmarks-CRT4ScEA.js} +4 -4
  11. package/dist/{benchmarks-Dg0B56tK.js.map → benchmarks-CRT4ScEA.js.map} +1 -1
  12. package/dist/campaign/index.d.ts +4 -3
  13. package/dist/campaign/index.js +4 -4
  14. package/dist/{campaign-C7ZGiZYG.js → campaign-CefP3fPS.js} +12 -10
  15. package/dist/campaign-CefP3fPS.js.map +1 -0
  16. package/dist/cli.js +2 -2
  17. package/dist/contract/index.d.ts +1 -1
  18. package/dist/contract/index.js +3 -3
  19. package/dist/{default-registry-BupFSXSN.js → default-registry-SOyHB6qG.js} +3 -3
  20. package/dist/{default-registry-BupFSXSN.js.map → default-registry-SOyHB6qG.js.map} +1 -1
  21. package/dist/{dspy-rlm-engine-CJ4sN8Wx.js → dspy-rlm-engine-BR7TtB0o.js} +69 -31
  22. package/dist/dspy-rlm-engine-BR7TtB0o.js.map +1 -0
  23. package/dist/{eval-campaign-YdkpWWoT.js → eval-campaign-lI7wB9DH.js} +2 -2
  24. package/dist/{eval-campaign-YdkpWWoT.js.map → eval-campaign-lI7wB9DH.js.map} +1 -1
  25. package/dist/external-optimizer-contracts-CdmX2K2S.d.ts +165 -0
  26. package/dist/external-optimizer-contracts-CdmX2K2S.d.ts.map +1 -0
  27. package/dist/{index-BKjcUH13.d.ts → index-BZUe-ODI.d.ts} +41 -5
  28. package/dist/index-BZUe-ODI.d.ts.map +1 -0
  29. package/dist/{index-DY83M1WL.d.ts → index-BrpxwELi.d.ts} +9 -8
  30. package/dist/{index-DY83M1WL.d.ts.map → index-BrpxwELi.d.ts.map} +1 -1
  31. package/dist/{index-CaOjqCli.d.ts → index-DRI1DU5z.d.ts} +3 -3
  32. package/dist/{index-CaOjqCli.d.ts.map → index-DRI1DU5z.d.ts.map} +1 -1
  33. package/dist/index.d.ts +7 -7
  34. package/dist/index.js +12 -11
  35. package/dist/index.js.map +1 -1
  36. package/dist/{integrity-hruKe6oe.js → integrity-DY6tIbl0.js} +48 -18
  37. package/dist/integrity-DY6tIbl0.js.map +1 -0
  38. package/dist/{llm-client-B3WXSH5Y.js → llm-client-D3EoChAU.js} +7 -7
  39. package/dist/llm-client-D3EoChAU.js.map +1 -0
  40. package/dist/openapi.json +1 -1
  41. package/dist/rl.js +1 -1
  42. package/dist/{semantic-concept-judge-DJQtFr95.js → semantic-concept-judge-l8Lb3Kqz.js} +2 -2
  43. package/dist/{semantic-concept-judge-DJQtFr95.js.map → semantic-concept-judge-l8Lb3Kqz.js.map} +1 -1
  44. package/dist/{server-Cu4M3NSO.js → server-Df00sdwz.js} +3 -3
  45. package/dist/{server-Cu4M3NSO.js.map → server-Df00sdwz.js.map} +1 -1
  46. package/dist/single-run-lock-B-cFnnNn.js +1799 -0
  47. package/dist/single-run-lock-B-cFnnNn.js.map +1 -0
  48. package/dist/{skill-usage-CRqaHi0R.d.ts → skill-usage-3vUWdZ9n.d.ts} +24 -5
  49. package/dist/skill-usage-3vUWdZ9n.d.ts.map +1 -0
  50. package/dist/{skillopt-optimization-method-Di8Xkalt.js → skillopt-optimization-method-DA5mJmFE.js} +225 -347
  51. package/dist/skillopt-optimization-method-DA5mJmFE.js.map +1 -0
  52. package/dist/{skillopt-optimization-method-CwRvi-rL.d.ts → skillopt-optimization-method-DNniakI5.d.ts} +47 -9
  53. package/dist/skillopt-optimization-method-DNniakI5.d.ts.map +1 -0
  54. package/dist/supervisor-run/index.d.ts +3 -3
  55. package/dist/supervisor-run/index.js +3 -3
  56. package/dist/{supervisor-run-BEns49Nx.js → supervisor-run-DiyQVczd.js} +301 -25
  57. package/dist/supervisor-run-DiyQVczd.js.map +1 -0
  58. package/dist/types-BjMFz88h.d.ts.map +1 -1
  59. package/dist/{types-Dea6tiVI.d.ts → types-yLK8gXE9.d.ts} +15 -2
  60. package/dist/types-yLK8gXE9.d.ts.map +1 -0
  61. package/dist/wire/index.js +1 -1
  62. package/docs/campaign-proposers.md +11 -7
  63. package/docs/trace-analysis.md +43 -32
  64. package/package.json +1 -1
  65. package/dist/benchmark-command-CSddvlq7.js.map +0 -1
  66. package/dist/campaign-C7ZGiZYG.js.map +0 -1
  67. package/dist/dspy-rlm-engine-CJ4sN8Wx.js.map +0 -1
  68. package/dist/external-optimizer-contracts-nb7c_WAR.d.ts +0 -42
  69. package/dist/external-optimizer-contracts-nb7c_WAR.d.ts.map +0 -1
  70. package/dist/index-BKjcUH13.d.ts.map +0 -1
  71. package/dist/integrity-hruKe6oe.js.map +0 -1
  72. package/dist/llm-client-B3WXSH5Y.js.map +0 -1
  73. package/dist/single-run-lock-Do-8vBIJ.js +0 -1049
  74. package/dist/single-run-lock-Do-8vBIJ.js.map +0 -1
  75. package/dist/skill-usage-CRqaHi0R.d.ts.map +0 -1
  76. package/dist/skillopt-optimization-method-CwRvi-rL.d.ts.map +0 -1
  77. package/dist/skillopt-optimization-method-Di8Xkalt.js.map +0 -1
  78. package/dist/supervisor-run-BEns49Nx.js.map +0 -1
  79. package/dist/types-Dea6tiVI.d.ts.map +0 -1
@@ -1,1049 +0,0 @@
1
- import { c as ValidationError } from "./errors-D-LKuDhb.js";
2
- import { c as costForTokenPricing, i as CostLedger } from "./cost-ledger-DMFxsLKr.js";
3
- import { a as appendLedgerLine, d as tryAcquireAtomicFileLock, o as tryWithLedgerFileLock, u as probeAtomicFileLock } from "./ledger-core-Dxz0Rkwa.js";
4
- import { createRequire } from "node:module";
5
- import { isAbsolute, join, resolve } from "node:path";
6
- import { randomBytes } from "node:crypto";
7
- import { createServer } from "node:http";
8
- import { spawn } from "node:child_process";
9
- import { lstat, mkdtemp, open, rm, writeFile } from "node:fs/promises";
10
- import { tmpdir } from "node:os";
11
- //#region src/campaign/external-optimizer-contracts.ts
12
- const MAX_TIMER_DELAY_MS$1 = 2147483647;
13
- function isCandidateText(value, maxChars) {
14
- return typeof value === "string" && value.trim().length > 0 && value.length <= maxChars;
15
- }
16
- function isExternalTextCandidate(value) {
17
- if (typeof value === "string") return value.trim().length > 0;
18
- if (!isRecord(value)) return false;
19
- const entries = Object.entries(value);
20
- return entries.length > 0 && entries.every(([name, content]) => name.trim().length > 0 && name.trim() === name && typeof content === "string");
21
- }
22
- function assertJsonValue(value, label, seen = /* @__PURE__ */ new Set()) {
23
- if (value === null || typeof value === "string" || typeof value === "boolean") return;
24
- if (typeof value === "number" && Number.isFinite(value)) return;
25
- if (Array.isArray(value)) {
26
- if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`);
27
- seen.add(value);
28
- for (const item of value) assertJsonValue(item, label, seen);
29
- seen.delete(value);
30
- return;
31
- }
32
- if (typeof value === "object") {
33
- if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`);
34
- const prototype = Object.getPrototypeOf(value);
35
- if (prototype !== Object.prototype && prototype !== null) throw new Error(`${label} must be JSON-serializable`);
36
- seen.add(value);
37
- for (const item of Object.values(value)) assertJsonValue(item, label, seen);
38
- seen.delete(value);
39
- return;
40
- }
41
- throw new Error(`${label} must be JSON-serializable`);
42
- }
43
- function assertNoCredentialValues(value, path, credentialLocation = "runner.env") {
44
- if (Array.isArray(value)) {
45
- for (const [index, item] of value.entries()) assertNoCredentialValues(item, `${path}[${index}]`, credentialLocation);
46
- return;
47
- }
48
- if (!isRecord(value)) return;
49
- for (const [key, item] of Object.entries(value)) {
50
- if (isCredentialKey(key)) throw new Error(`${path}.${key} must be supplied through ${credentialLocation}`);
51
- assertNoCredentialValues(item, `${path}.${key}`, credentialLocation);
52
- }
53
- }
54
- function removeCredentialEnvironment(environment) {
55
- const sanitized = {};
56
- for (const [key, value] of Object.entries(environment)) if (value !== void 0 && !isCredentialKey(key)) sanitized[key] = value;
57
- return sanitized;
58
- }
59
- function assertExternalOptimizerModelBudget(value, label) {
60
- if (!value || typeof value !== "object") throw new Error(`${label} is required`);
61
- for (const [field, entry] of [
62
- ["maxRequests", value.maxRequests],
63
- ["maxRequestBytes", value.maxRequestBytes],
64
- ["maxResponseBytes", value.maxResponseBytes],
65
- ["maxOutputTokensPerRequest", value.maxOutputTokensPerRequest]
66
- ]) if (!Number.isSafeInteger(entry) || entry <= 0) throw new Error(`${label}.${field} must be a positive safe integer`);
67
- if (!Number.isFinite(value.maxCostUsd) || value.maxCostUsd <= 0) throw new Error(`${label}.maxCostUsd must be positive and finite`);
68
- if (value.requestTimeoutMs !== void 0 && (!Number.isSafeInteger(value.requestTimeoutMs) || value.requestTimeoutMs <= 0 || value.requestTimeoutMs > MAX_TIMER_DELAY_MS$1)) throw new Error(`${label}.requestTimeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS$1}`);
69
- costForTokenPricing(value.pricing, {
70
- inputTokens: 1,
71
- outputTokens: 1
72
- });
73
- }
74
- function safePathComponent(value) {
75
- return value.replace(/[^a-zA-Z0-9._-]/g, "_");
76
- }
77
- function isCredentialKey(key) {
78
- return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/-/g, "_").toLowerCase().split("_").some((segment) => [
79
- "auth",
80
- "authorization",
81
- "cookie",
82
- "credential",
83
- "credentials",
84
- "key",
85
- "password",
86
- "secret",
87
- "session",
88
- "token"
89
- ].includes(segment));
90
- }
91
- function isRecord(value) {
92
- return typeof value === "object" && value !== null && !Array.isArray(value);
93
- }
94
- //#endregion
95
- //#region src/campaign/external-optimizer-http.ts
96
- function listenLocal(server) {
97
- return new Promise((resolvePromise, reject) => {
98
- server.once("error", reject);
99
- server.listen(0, "127.0.0.1", () => {
100
- server.off("error", reject);
101
- const address = server.address();
102
- if (!address || typeof address === "string") {
103
- reject(/* @__PURE__ */ new Error("external optimizer callback did not bind a TCP port"));
104
- return;
105
- }
106
- resolvePromise(address.port);
107
- });
108
- });
109
- }
110
- function closeServer(server) {
111
- return new Promise((resolvePromise, reject) => {
112
- server.close((error) => error ? reject(error) : resolvePromise());
113
- });
114
- }
115
- function sendJson(response, status, body) {
116
- response.writeHead(status, { "content-type": "application/json; charset=utf-8" });
117
- response.end(JSON.stringify(body));
118
- }
119
- //#endregion
120
- //#region src/campaign/external-optimizer-model-proxy.ts
121
- const MODEL_PROXY_PATHS = /* @__PURE__ */ new Set(["/v1/chat/completions", "/v1/responses"]);
122
- /**
123
- * Backoff before repeating an upstream fetch the provider answered with 429.
124
- * One admitted request retries at most this many times, each retry consuming
125
- * one budgeted request slot, before the final 429 is forwarded to the child.
126
- * Only HTTP 429 is retried: any other status or a transport error keeps
127
- * failing immediately.
128
- */
129
- const RATE_LIMIT_RETRY_DELAYS_MS = [
130
- 2e3,
131
- 8e3,
132
- 3e4
133
- ];
134
- /** Uniform 0..25% added to each delay so concurrent workers do not resynchronize. */
135
- const RATE_LIMIT_RETRY_JITTER_RATIO = .25;
136
- /**
137
- * Put an OpenAI-compatible optimizer behind the shared cost ledger.
138
- *
139
- * The child process receives only a loopback URL and an ephemeral token.
140
- * Provider credentials stay in this process. Every request reserves its
141
- * conservative byte-count input bound plus the provider-enforced output cap
142
- * before it leaves the machine.
143
- */
144
- async function startExternalOptimizerModelProxy(args) {
145
- assertModelProxyConfig(args);
146
- args.signal?.throwIfAborted();
147
- const token = randomLocalToken();
148
- const fetchImpl = args.fetchImpl ?? fetch;
149
- const sleepImpl = args.sleepImpl ?? abortableDelay;
150
- let requestCount = 0;
151
- let successfulCompletionCount = 0;
152
- let rateLimitRetryCount = 0;
153
- let totalRequestCount = args.initialUsage?.requests ?? 0;
154
- let committedForBudget = args.initialUsage?.costUsd ?? 0;
155
- let reservedForBudget = 0;
156
- let accepting = true;
157
- let closePromise;
158
- const activeControllers = /* @__PURE__ */ new Set();
159
- const activeHandlers = /* @__PURE__ */ new Set();
160
- const server = createServer((request, response) => {
161
- if (!accepting) {
162
- sendJsonIfOpen(response, 503, { error: "external optimizer model proxy is closing" });
163
- return;
164
- }
165
- const controller = new AbortController();
166
- const abortRequest = () => {
167
- request.destroy();
168
- response.destroy();
169
- };
170
- activeControllers.add(controller);
171
- controller.signal.addEventListener("abort", abortRequest, { once: true });
172
- let handler;
173
- handler = handleModelProxyRequest({
174
- request,
175
- response,
176
- controller,
177
- token,
178
- args,
179
- fetchImpl,
180
- nextReservation: (maximumCostUsd) => {
181
- if (totalRequestCount >= args.budget.maxRequests) return {
182
- accepted: false,
183
- reason: "optimizer model request limit reached"
184
- };
185
- if (committedForBudget + reservedForBudget + maximumCostUsd > args.budget.maxCostUsd + Number.EPSILON) return {
186
- accepted: false,
187
- reason: "optimizer model cost limit reached"
188
- };
189
- requestCount += 1;
190
- totalRequestCount += 1;
191
- reservedForBudget += maximumCostUsd;
192
- return { accepted: true };
193
- },
194
- settleReservation: (maximumCostUsd, chargedCostUsd) => {
195
- reservedForBudget = Math.max(0, reservedForBudget - maximumCostUsd);
196
- committedForBudget += chargedCostUsd;
197
- },
198
- recordSuccessfulCompletion: () => {
199
- successfulCompletionCount += 1;
200
- },
201
- tryConsumeRateLimitRetry: () => {
202
- if (totalRequestCount >= args.budget.maxRequests) return false;
203
- requestCount += 1;
204
- totalRequestCount += 1;
205
- rateLimitRetryCount += 1;
206
- return true;
207
- },
208
- sleepImpl
209
- }).finally(() => {
210
- controller.signal.removeEventListener("abort", abortRequest);
211
- activeControllers.delete(controller);
212
- activeHandlers.delete(handler);
213
- });
214
- activeHandlers.add(handler);
215
- handler.catch(() => void 0);
216
- });
217
- const port = await listenLocal(server);
218
- const close = () => {
219
- closePromise ??= closeModelProxy();
220
- return closePromise;
221
- };
222
- const onAbort = () => {
223
- close().catch(() => void 0);
224
- };
225
- args.signal?.addEventListener("abort", onAbort, { once: true });
226
- if (args.signal?.aborted) onAbort();
227
- return {
228
- baseUrl: `http://127.0.0.1:${port}/v1`,
229
- apiKey: token,
230
- requestAttempts: () => requestCount,
231
- successfulCompletions: () => successfulCompletionCount,
232
- rateLimitRetries: () => rateLimitRetryCount,
233
- close
234
- };
235
- async function closeModelProxy() {
236
- args.signal?.removeEventListener("abort", onAbort);
237
- accepting = false;
238
- const closingServer = closeServer(server);
239
- server.closeIdleConnections?.();
240
- for (const controller of activeControllers) controller.abort();
241
- const [serverResult] = await Promise.allSettled([closingServer, waitForActiveHandlers(activeHandlers)]);
242
- if (activeControllers.size !== 0 || activeHandlers.size !== 0) throw new Error("external optimizer model proxy closed with active request work");
243
- if (serverResult?.status === "rejected") throw serverResult.reason;
244
- }
245
- }
246
- async function handleModelProxyRequest(args) {
247
- const { controller, request, response } = args;
248
- try {
249
- const path = request.url ? new URL(request.url, "http://127.0.0.1").pathname : "";
250
- if (request.method !== "POST" || !MODEL_PROXY_PATHS.has(path)) {
251
- sendJsonIfOpen(response, 404, { error: "not found" });
252
- return;
253
- }
254
- if (request.headers.authorization !== `Bearer ${args.token}`) {
255
- sendJsonIfOpen(response, 401, { error: "unauthorized" });
256
- return;
257
- }
258
- const body = await readBody(request, args.args.budget.maxRequestBytes);
259
- const parsed = parseModelProxyRequest(body, args.args.model, args.args.budget);
260
- const maximumUsage = conservativeMaximumUsage(body.byteLength, parsed.maxOutputTokens + (args.args.budget.maxReasoningTokensPerRequest ?? 0), args.args.budget.pricing);
261
- const maximumCostUsd = costForTokenPricing(args.args.budget.pricing, maximumUsage);
262
- const reservation = args.nextReservation(maximumCostUsd);
263
- if (!reservation.accepted) {
264
- sendJsonIfOpen(response, 429, { error: reservation.reason });
265
- return;
266
- }
267
- const timeout = setTimeout(() => controller.abort(), args.args.budget.requestTimeoutMs ?? 3e5);
268
- let chargedForBudget = maximumCostUsd;
269
- try {
270
- const paid = await args.args.costLedger.runPaidCall({
271
- channel: args.args.channel ?? "optimizer",
272
- phase: args.args.phase,
273
- actor: args.args.actor,
274
- ...args.args.tags ? { tags: args.args.tags } : {},
275
- model: args.args.model,
276
- maximumCharge: {
277
- customTokenPricing: args.args.budget.pricing,
278
- ...maximumUsage
279
- },
280
- execute: async () => {
281
- for (let retries = 0;; retries += 1) {
282
- const forwarded = await forwardModelProxyRequest({
283
- fetchImpl: args.fetchImpl,
284
- upstreamBaseUrl: args.args.upstreamBaseUrl,
285
- upstreamApiKey: args.args.upstreamApiKey,
286
- path,
287
- body,
288
- model: args.args.model,
289
- pricing: args.args.budget.pricing,
290
- maxOutputTokens: parsed.maxOutputTokens,
291
- ...args.args.budget.maxReasoningTokensPerRequest === void 0 ? {} : { maxReasoningTokens: args.args.budget.maxReasoningTokensPerRequest },
292
- maxResponseBytes: args.args.budget.maxResponseBytes,
293
- signal: controller.signal
294
- });
295
- if (forwarded.status !== 429 || retries >= RATE_LIMIT_RETRY_DELAYS_MS.length || !args.tryConsumeRateLimitRetry()) return forwarded;
296
- const baseDelayMs = RATE_LIMIT_RETRY_DELAYS_MS[retries];
297
- await args.sleepImpl(Math.round(baseDelayMs * (1 + Math.random() * RATE_LIMIT_RETRY_JITTER_RATIO)), controller.signal);
298
- }
299
- },
300
- receipt: (result) => result.receipt,
301
- receiptFromError: () => ({
302
- model: args.args.model,
303
- inputTokens: 0,
304
- outputTokens: 0,
305
- costUnknown: true,
306
- usageUnknown: true
307
- })
308
- });
309
- if (!paid.succeeded) {
310
- chargedForBudget = paid.receipt ? paid.receipt.usageUnknown || paid.receipt.costUnknown ? maximumCostUsd : paid.receipt.costUsd : 0;
311
- sendJsonIfOpen(response, isAbortError(paid.error) ? 504 : paid.error instanceof ProviderResponseTooLargeError ? 502 : 429, { error: paid.error.message });
312
- return;
313
- }
314
- chargedForBudget = paid.value.usageComplete ? paid.receipt.costUsd : maximumCostUsd;
315
- if (paid.value.usageRejected) {
316
- sendJsonIfOpen(response, 502, { error: paid.value.usageRejected });
317
- return;
318
- }
319
- if (paid.value.status >= 200 && paid.value.status < 300) args.recordSuccessfulCompletion();
320
- if (response.destroyed || response.writableEnded) return;
321
- response.writeHead(paid.value.status, {
322
- "content-type": paid.value.contentType,
323
- "content-length": String(paid.value.body.byteLength)
324
- });
325
- response.end(paid.value.body);
326
- } finally {
327
- clearTimeout(timeout);
328
- args.settleReservation(maximumCostUsd, chargedForBudget);
329
- }
330
- } catch (error) {
331
- sendJsonIfOpen(response, error instanceof RequestBodyTooLargeError ? 413 : error instanceof Error && isAbortError(error) ? 503 : 400, { error: toErrorMessage(error) });
332
- }
333
- }
334
- async function waitForActiveHandlers(activeHandlers) {
335
- while (activeHandlers.size > 0) await Promise.allSettled([...activeHandlers]);
336
- }
337
- function sendJsonIfOpen(response, status, body) {
338
- if (response.destroyed || response.writableEnded) return;
339
- sendJson(response, status, body);
340
- }
341
- async function forwardModelProxyRequest(args) {
342
- const upstream = modelProxyUpstreamUrl(args.upstreamBaseUrl, args.path);
343
- const response = await args.fetchImpl(upstream, {
344
- method: "POST",
345
- headers: {
346
- authorization: `Bearer ${args.upstreamApiKey}`,
347
- "content-type": "application/json"
348
- },
349
- body: args.body.buffer.slice(args.body.byteOffset, args.body.byteOffset + args.body.byteLength),
350
- signal: args.signal,
351
- redirect: "error"
352
- });
353
- const body = await readProviderResponseBody(response, args.maxResponseBytes);
354
- const usage = parseProviderUsage(body);
355
- const successful = response.status >= 200 && response.status < 300;
356
- const zeroUsage = successful && usage !== void 0 && usage.inputTokens + usage.outputTokens + (usage.cachedTokens ?? 0) + (usage.cacheWriteTokens ?? 0) === 0;
357
- const completionTokens = usage === void 0 ? 0 : usage.outputTokens - (usage.reasoningTokens ?? 0);
358
- const reasoningTokens = usage?.reasoningTokens ?? 0;
359
- const usageRejected = successful && usage !== void 0 && completionTokens > args.maxOutputTokens ? `optimizer model provider reported ${completionTokens} completion tokens, exceeding requested limit ${args.maxOutputTokens}` : successful && args.maxReasoningTokens !== void 0 && reasoningTokens > args.maxReasoningTokens ? `optimizer model provider reported ${reasoningTokens} reasoning tokens, exceeding the declared budget ${args.maxReasoningTokens}` : void 0;
360
- return {
361
- status: response.status,
362
- contentType: response.headers.get("content-type") ?? "application/json",
363
- body,
364
- receipt: usage && !zeroUsage ? {
365
- model: args.model,
366
- ...usage,
367
- ...usage.actualCostUsd === void 0 ? { customTokenPricing: args.pricing } : {}
368
- } : {
369
- model: args.model,
370
- inputTokens: 0,
371
- outputTokens: 0,
372
- costUnknown: true,
373
- usageUnknown: true
374
- },
375
- usageComplete: usage !== void 0 && !zeroUsage,
376
- ...usageRejected ? { usageRejected } : {}
377
- };
378
- }
379
- function parseModelProxyRequest(body, expectedModel, budget) {
380
- let value;
381
- try {
382
- value = JSON.parse(Buffer.from(body).toString("utf8"));
383
- } catch {
384
- throw new Error("optimizer model request must be valid JSON");
385
- }
386
- if (!isRecord(value)) throw new Error("optimizer model request must be a JSON object");
387
- if (value.model !== expectedModel) throw new Error(`optimizer model request must use configured model '${expectedModel}'`);
388
- if (value.stream !== void 0 && value.stream !== false) throw new Error("streaming optimizer model requests are not supported");
389
- for (const field of [
390
- "n",
391
- "best_of",
392
- "candidate_count",
393
- "num_candidates"
394
- ]) if (value[field] !== void 0 && value[field] !== 1) throw new Error(`optimizer model request ${field} must be 1 when supplied`);
395
- const suppliedMaximums = [
396
- value.max_output_tokens,
397
- value.max_completion_tokens,
398
- value.max_tokens
399
- ].filter((maximum) => maximum !== void 0);
400
- if (suppliedMaximums.length === 0 || suppliedMaximums.some((maximum) => !Number.isSafeInteger(maximum) || maximum <= 0)) throw new Error("optimizer model request requires a positive output-token limit");
401
- const maxOutputTokens = Math.max(...suppliedMaximums);
402
- if (maxOutputTokens > budget.maxOutputTokensPerRequest) throw new Error("optimizer model request exceeds maxOutputTokensPerRequest");
403
- return { maxOutputTokens };
404
- }
405
- /**
406
- * Resolve the upstream URL the way an OpenAI-compatible client does.
407
- *
408
- * This proxy exposes `/v1/...` to its child for client compatibility. Whether
409
- * that prefix belongs upstream depends on the caller's base URL: a base that
410
- * already names a version segment (`/v1`, `/api/coding/paas/v4`) receives only
411
- * the endpoint, and a base without one receives the whole versioned path.
412
- * Forwarding the prefix unconditionally produced `/v4/v1/chat/completions`,
413
- * which providers answer with 404.
414
- */
415
- function modelProxyUpstreamUrl(baseUrl, requestPath) {
416
- const upstream = new URL(baseUrl);
417
- const basePath = upstream.pathname.replace(/\/+$/, "");
418
- const lastSegment = basePath.split("/").at(-1) ?? "";
419
- upstream.pathname = `${basePath}${/^v\d+/.test(lastSegment) ? requestPath.replace(/^\/v1(?=\/)/, "") : requestPath}`;
420
- return upstream.toString();
421
- }
422
- function parseProviderUsage(body) {
423
- let value;
424
- try {
425
- value = JSON.parse(Buffer.from(body).toString("utf8"));
426
- } catch {
427
- return;
428
- }
429
- if (!isRecord(value) || !isRecord(value.usage)) return void 0;
430
- const usage = value.usage;
431
- const totalInputTokens = usage.input_tokens ?? usage.prompt_tokens;
432
- const outputTokens = usage.output_tokens ?? usage.completion_tokens;
433
- if (!Number.isSafeInteger(totalInputTokens) || totalInputTokens < 0 || !Number.isSafeInteger(outputTokens) || outputTokens < 0) return;
434
- const inputDetails = isRecord(usage.input_tokens_details) ? usage.input_tokens_details : isRecord(usage.prompt_tokens_details) ? usage.prompt_tokens_details : {};
435
- const outputDetails = isRecord(usage.output_tokens_details) ? usage.output_tokens_details : isRecord(usage.completion_tokens_details) ? usage.completion_tokens_details : {};
436
- const cachedTokens = optionalTokenCount(inputDetails, [
437
- "cached_tokens",
438
- "cache_read_tokens",
439
- "cache_read_input_tokens"
440
- ]);
441
- const cacheWriteTokens = optionalTokenCount(inputDetails, [
442
- "cache_write_tokens",
443
- "cache_creation_tokens",
444
- "cache_creation_input_tokens"
445
- ]);
446
- const reasoningTokens = optionalTokenCount(outputDetails, ["reasoning_tokens"]);
447
- const actualCostUsd = typeof usage.cost === "number" && Number.isFinite(usage.cost) && usage.cost >= 0 ? usage.cost : void 0;
448
- if (cachedTokens === INVALID_TOKEN_COUNT || cacheWriteTokens === INVALID_TOKEN_COUNT || reasoningTokens === INVALID_TOKEN_COUNT) return;
449
- const classifiedInputTokens = (cachedTokens ?? 0) + (cacheWriteTokens ?? 0);
450
- if (classifiedInputTokens > totalInputTokens || (reasoningTokens ?? 0) > outputTokens) return;
451
- return {
452
- inputTokens: totalInputTokens - classifiedInputTokens,
453
- outputTokens,
454
- ...cachedTokens === void 0 ? {} : { cachedTokens },
455
- ...cacheWriteTokens === void 0 ? {} : { cacheWriteTokens },
456
- ...reasoningTokens === void 0 ? {} : { reasoningTokens },
457
- ...actualCostUsd === void 0 ? {} : { actualCostUsd }
458
- };
459
- }
460
- const INVALID_TOKEN_COUNT = Symbol("invalid-token-count");
461
- function optionalTokenCount(details, fields) {
462
- let found;
463
- for (const field of fields) {
464
- const value = details[field];
465
- if (value === void 0 || value === null) continue;
466
- if (!Number.isSafeInteger(value) || value < 0) return INVALID_TOKEN_COUNT;
467
- if (found !== void 0 && found !== value) return INVALID_TOKEN_COUNT;
468
- found = value;
469
- }
470
- return found;
471
- }
472
- function conservativeMaximumUsage(inputTokenUpperBound, outputTokenUpperBound, pricing) {
473
- const inputRates = [
474
- pricing.inputUsdPerMillion,
475
- pricing.cachedInputUsdPerMillion ?? pricing.inputUsdPerMillion,
476
- pricing.cacheWriteUsdPerMillion ?? pricing.inputUsdPerMillion
477
- ];
478
- const mostExpensiveInputClass = inputRates.indexOf(Math.max(...inputRates));
479
- return {
480
- inputTokens: mostExpensiveInputClass === 0 ? inputTokenUpperBound : 0,
481
- ...mostExpensiveInputClass === 1 ? { cachedTokens: inputTokenUpperBound } : {},
482
- ...mostExpensiveInputClass === 2 ? { cacheWriteTokens: inputTokenUpperBound } : {},
483
- outputTokens: outputTokenUpperBound
484
- };
485
- }
486
- async function readProviderResponseBody(response, maxBytes) {
487
- const declaredLength = response.headers.get("content-length");
488
- if (declaredLength !== null) {
489
- const parsedLength = Number(declaredLength);
490
- if (Number.isFinite(parsedLength) && parsedLength > maxBytes) throw new ProviderResponseTooLargeError();
491
- }
492
- if (!response.body) return /* @__PURE__ */ new Uint8Array();
493
- const reader = response.body.getReader();
494
- const chunks = [];
495
- let totalBytes = 0;
496
- try {
497
- while (true) {
498
- const next = await reader.read();
499
- if (next.done) break;
500
- totalBytes += next.value.byteLength;
501
- if (totalBytes > maxBytes) {
502
- await reader.cancel();
503
- throw new ProviderResponseTooLargeError();
504
- }
505
- chunks.push(next.value);
506
- }
507
- } finally {
508
- reader.releaseLock();
509
- }
510
- const body = new Uint8Array(totalBytes);
511
- let offset = 0;
512
- for (const chunk of chunks) {
513
- body.set(chunk, offset);
514
- offset += chunk.byteLength;
515
- }
516
- return body;
517
- }
518
- function assertModelProxyConfig(args) {
519
- for (const [label, value] of [
520
- ["upstreamBaseUrl", args.upstreamBaseUrl],
521
- ["upstreamApiKey", args.upstreamApiKey],
522
- ["model", args.model],
523
- ["phase", args.phase],
524
- ["actor", args.actor]
525
- ]) if (typeof value !== "string" || !value.trim() || value.trim() !== value) throw new Error(`external optimizer model proxy: ${label} must be trimmed and non-empty`);
526
- let parsed;
527
- try {
528
- parsed = new URL(args.upstreamBaseUrl);
529
- } catch {
530
- throw new Error("external optimizer model proxy: upstreamBaseUrl must be an HTTP(S) URL");
531
- }
532
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.search || parsed.hash) throw new Error("external optimizer model proxy: upstreamBaseUrl must be an HTTP(S) URL without credentials, query, or fragment");
533
- assertExternalOptimizerModelBudget(args.budget, "external optimizer model proxy: budget");
534
- if (args.tags !== void 0) {
535
- for (const [key, value] of Object.entries(args.tags)) if (!key.trim() || key.trim() !== key || !value.trim() || value.trim() !== value) throw new Error("external optimizer model proxy: tags must be trimmed and non-empty");
536
- }
537
- if (args.initialUsage !== void 0) {
538
- if (!Number.isSafeInteger(args.initialUsage.requests) || args.initialUsage.requests < 0 || !Number.isFinite(args.initialUsage.costUsd) || args.initialUsage.costUsd < 0) throw new Error("external optimizer model proxy: initialUsage must contain non-negative requests and cost");
539
- if (args.initialUsage.requests > args.budget.maxRequests || args.initialUsage.costUsd > args.budget.maxCostUsd + Number.EPSILON) throw new Error("external optimizer model proxy: initialUsage exceeds the configured budget");
540
- }
541
- }
542
- var RequestBodyTooLargeError = class extends Error {};
543
- var ProviderResponseTooLargeError = class extends Error {
544
- constructor() {
545
- super("optimizer model response exceeds maxResponseBytes");
546
- }
547
- };
548
- function readBody(request, maximumBytes) {
549
- return new Promise((resolvePromise, reject) => {
550
- let size = 0;
551
- let tooLarge = false;
552
- const chunks = [];
553
- request.on("data", (chunk) => {
554
- if (tooLarge) return;
555
- size += chunk.byteLength;
556
- if (size > maximumBytes) {
557
- tooLarge = true;
558
- chunks.length = 0;
559
- return;
560
- }
561
- chunks.push(chunk);
562
- });
563
- request.on("error", reject);
564
- request.on("end", () => {
565
- if (tooLarge) {
566
- reject(new RequestBodyTooLargeError("optimizer model request body too large"));
567
- return;
568
- }
569
- resolvePromise(new Uint8Array(Buffer.concat(chunks)));
570
- });
571
- });
572
- }
573
- function randomLocalToken() {
574
- return randomBytes(32).toString("hex");
575
- }
576
- function abortableDelay(ms, signal) {
577
- return new Promise((resolve, reject) => {
578
- const abortError = () => signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("optimizer model retry backoff aborted");
579
- if (signal.aborted) {
580
- reject(abortError());
581
- return;
582
- }
583
- const onAbort = () => {
584
- clearTimeout(timer);
585
- reject(abortError());
586
- };
587
- const timer = setTimeout(() => {
588
- signal.removeEventListener("abort", onAbort);
589
- resolve();
590
- }, ms);
591
- signal.addEventListener("abort", onAbort, { once: true });
592
- });
593
- }
594
- function isAbortError(error) {
595
- return error.name === "AbortError" || error.message.toLowerCase().includes("abort");
596
- }
597
- function toErrorMessage(error) {
598
- return error instanceof Error ? error.message : String(error);
599
- }
600
- //#endregion
601
- //#region src/campaign/external-optimizer-resources.ts
602
- async function runWithCleanup(args) {
603
- let value;
604
- let operationError;
605
- try {
606
- value = await args.run();
607
- } catch (cause) {
608
- operationError = toError(cause);
609
- }
610
- let cleanupError;
611
- try {
612
- await args.cleanup();
613
- } catch (cause) {
614
- cleanupError = toError(cause);
615
- }
616
- if (operationError && cleanupError) throw new AggregateError([operationError, cleanupError], `${operationError.message}; ${args.label} cleanup failed: ${cleanupError.message}`);
617
- if (operationError) throw operationError;
618
- if (cleanupError) throw new Error(`${args.label} cleanup failed: ${cleanupError.message}`, { cause: cleanupError });
619
- return value;
620
- }
621
- async function closeExternalOptimizerResources(args) {
622
- const errors = (await Promise.allSettled([...args.modelProxy ? [args.modelProxy.close()] : [], args.callback.close()])).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
623
- if (errors.length > 0) throw new AggregateError(errors, `${args.label}: failed to close optimizer resources`);
624
- }
625
- function toError(cause) {
626
- return cause instanceof Error ? cause : new Error(String(cause));
627
- }
628
- //#endregion
629
- //#region src/campaign/external-optimizer-subprocess.ts
630
- const MAX_PROCESS_OUTPUT_CHARS = 64e3;
631
- const MAX_PROCESS_INPUT_BYTES = 64 * 1024 * 1024;
632
- const MAX_PROCESS_RESULT_BYTES = 4 * 1024 * 1024;
633
- const PROCESS_TERMINATION_GRACE_MS = 5e3;
634
- const PROCESS_TERMINATION_POLL_MS = 25;
635
- const PROCESS_KILL_WAIT_MS = 1e3;
636
- const MAX_TIMER_DELAY_MS = 2147483647;
637
- const PROCESS_OUTPUT_HEAD_CHARS = MAX_PROCESS_OUTPUT_CHARS / 2;
638
- async function runExternalOptimizerProcess(args) {
639
- if (!Number.isSafeInteger(args.timeoutMs) || args.timeoutMs <= 0 || args.timeoutMs > MAX_TIMER_DELAY_MS) throw new Error(`${args.label} timeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS}`);
640
- if (process.platform === "win32") throw new Error(`${args.label} requires POSIX process-group cleanup; run the optimizer through WSL or Linux`);
641
- throwIfAborted(args.signal, args.label);
642
- const dir = await mkdtemp(join(tmpdir(), args.tempPrefix));
643
- const inputPath = join(dir, "input.json");
644
- const outputPath = join(dir, "output.json");
645
- return runWithCleanup({
646
- label: `${args.label} temporary directory`,
647
- run: async () => {
648
- const serializedInput = JSON.stringify(args.input);
649
- if (serializedInput === void 0) throw new Error(`${args.label} input must be JSON-serializable`);
650
- const inputJson = `${serializedInput}\n`;
651
- const inputBytes = Buffer.byteLength(inputJson);
652
- if (inputBytes > MAX_PROCESS_INPUT_BYTES) throw new Error(`${args.label} input exceeds ${MAX_PROCESS_INPUT_BYTES} bytes (${inputBytes})`);
653
- await writeFile(inputPath, inputJson);
654
- const command = resolveRunnerCommand(args.runner?.command ?? "python");
655
- const commandArgs = [
656
- ...args.runner?.args ?? ["-m", args.module],
657
- "--input",
658
- inputPath,
659
- "--output",
660
- outputPath
661
- ];
662
- await runProcess({
663
- label: args.label,
664
- command,
665
- args: commandArgs,
666
- cwd: dir,
667
- env: args.runner?.env,
668
- timeoutMs: args.timeoutMs,
669
- signal: args.signal
670
- });
671
- throwIfAborted(args.signal, args.label);
672
- const raw = JSON.parse(await readBoundedTextFile(outputPath, MAX_PROCESS_RESULT_BYTES, `${args.label} output`));
673
- throwIfAborted(args.signal, args.label);
674
- if (!isRecord(raw)) throw new Error(`${args.label} output must be a JSON object`);
675
- return raw;
676
- },
677
- cleanup: () => rm(dir, {
678
- recursive: true,
679
- force: true
680
- })
681
- });
682
- }
683
- function resolveRunnerCommand(command) {
684
- if (isAbsolute(command) || !command.includes("/") && !command.includes("\\")) return command;
685
- return resolve(command);
686
- }
687
- async function readBoundedTextFile(path, maxBytes, label) {
688
- if (!(await lstat(path)).isFile()) throw new Error(`${label} must be a regular file`);
689
- const file = await open(path, "r");
690
- try {
691
- const buffer = Buffer.allocUnsafe(maxBytes + 1);
692
- let bytesRead = 0;
693
- while (bytesRead < buffer.byteLength) {
694
- const chunk = await file.read(buffer, bytesRead, buffer.byteLength - bytesRead, bytesRead);
695
- if (chunk.bytesRead === 0) break;
696
- bytesRead += chunk.bytesRead;
697
- }
698
- if (bytesRead > maxBytes) throw new Error(`${label} exceeds ${maxBytes} bytes`);
699
- return buffer.subarray(0, bytesRead).toString("utf8");
700
- } finally {
701
- await file.close();
702
- }
703
- }
704
- function runProcess(args) {
705
- throwIfAborted(args.signal, args.label);
706
- return new Promise((resolvePromise, reject) => {
707
- const child = spawn(args.command, args.args, {
708
- cwd: args.cwd,
709
- env: {
710
- ...safeProcessEnvironment(),
711
- ...args.env
712
- },
713
- stdio: [
714
- "ignore",
715
- "pipe",
716
- "pipe"
717
- ],
718
- detached: process.platform !== "win32",
719
- windowsHide: true
720
- });
721
- const stdout = createProcessOutputCapture();
722
- const stderr = createProcessOutputCapture();
723
- let settled = false;
724
- let timeout;
725
- const onAbort = () => finish(abortReason(args.signal, args.label));
726
- const finish = (error) => {
727
- if (settled) return;
728
- settled = true;
729
- if (timeout) clearTimeout(timeout);
730
- args.signal?.removeEventListener("abort", onAbort);
731
- terminateProcessTree(child).then(() => {
732
- if (error) reject(error);
733
- else resolvePromise();
734
- }, (cleanupError) => {
735
- if (error) {
736
- const cleanup = cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError));
737
- reject(new AggregateError([error, cleanup], `${error.message}; ${args.label} process cleanup failed: ${cleanup.message}`));
738
- return;
739
- }
740
- reject(/* @__PURE__ */ new Error(`${args.label} process cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`));
741
- });
742
- };
743
- timeout = setTimeout(() => {
744
- finish(/* @__PURE__ */ new Error(`${args.label} exceeded ${args.timeoutMs}ms`));
745
- }, args.timeoutMs);
746
- args.signal?.addEventListener("abort", onAbort, { once: true });
747
- if (args.signal?.aborted) onAbort();
748
- child.stdout.on("data", (chunk) => {
749
- appendProcessOutput(stdout, chunk);
750
- });
751
- child.stderr.on("data", (chunk) => {
752
- appendProcessOutput(stderr, chunk);
753
- });
754
- child.on("error", (error) => {
755
- finish(/* @__PURE__ */ new Error(`${args.label} could not start: ${error.message}`));
756
- });
757
- child.on("close", (code) => {
758
- if (code === 0) {
759
- finish();
760
- return;
761
- }
762
- finish(/* @__PURE__ */ new Error(`${args.label} exited ${String(code)}. stderr=${summarizeProcessOutput(stderr)} stdout=${summarizeProcessOutput(stdout)}`));
763
- });
764
- });
765
- }
766
- function throwIfAborted(signal, label) {
767
- if (signal?.aborted) throw abortReason(signal, label);
768
- }
769
- function abortReason(signal, label) {
770
- return signal.reason instanceof Error ? signal.reason : new Error(`${label} aborted`, { cause: signal.reason });
771
- }
772
- function safeProcessEnvironment() {
773
- return Object.fromEntries([
774
- "PATH",
775
- "HOME",
776
- "USER",
777
- "LOGNAME",
778
- "SHELL",
779
- "TMPDIR",
780
- "TMP",
781
- "TEMP",
782
- "LANG",
783
- "LANGUAGE",
784
- "LC_ALL",
785
- "VIRTUAL_ENV",
786
- "PYTHONPATH",
787
- "SYSTEMROOT",
788
- "COMSPEC",
789
- "PATHEXT",
790
- "WINDIR"
791
- ].flatMap((name) => {
792
- const value = process.env[name];
793
- return value === void 0 ? [] : [[name, value]];
794
- }));
795
- }
796
- async function terminateProcessTree(child) {
797
- const pid = child.pid;
798
- if (!pid) return;
799
- if (process.platform === "win32") throw new Error("native Windows process-tree cleanup is unsupported");
800
- if (!signalProcessGroup(pid, "SIGTERM")) return;
801
- if (await waitForProcessGroupExit(pid, PROCESS_TERMINATION_GRACE_MS)) return;
802
- if (!signalProcessGroup(pid, "SIGKILL")) return;
803
- if (await waitForProcessGroupExit(pid, PROCESS_KILL_WAIT_MS)) return;
804
- throw new Error(`process group ${pid} remained alive after SIGKILL`);
805
- }
806
- function signalProcessGroup(pid, signal) {
807
- try {
808
- process.kill(-pid, signal);
809
- return true;
810
- } catch (error) {
811
- if (isMissingProcessError(error)) return false;
812
- throw error;
813
- }
814
- }
815
- async function waitForProcessGroupExit(pid, timeoutMs) {
816
- const deadline = Date.now() + timeoutMs;
817
- while (processGroupExists(pid)) {
818
- const remainingMs = deadline - Date.now();
819
- if (remainingMs <= 0) return false;
820
- await new Promise((resolve) => setTimeout(resolve, Math.min(PROCESS_TERMINATION_POLL_MS, remainingMs)));
821
- }
822
- return true;
823
- }
824
- function processGroupExists(pid) {
825
- try {
826
- process.kill(-pid, 0);
827
- return true;
828
- } catch (error) {
829
- if (isMissingProcessError(error)) return false;
830
- throw error;
831
- }
832
- }
833
- function isMissingProcessError(error) {
834
- return typeof error === "object" && error !== null && "code" in error && error.code === "ESRCH";
835
- }
836
- function createProcessOutputCapture() {
837
- return {
838
- full: "",
839
- head: "",
840
- tail: "",
841
- totalChars: 0
842
- };
843
- }
844
- function appendProcessOutput(capture, chunk) {
845
- const text = chunk.toString();
846
- capture.totalChars += text.length;
847
- if (capture.full !== void 0) {
848
- const combined = `${capture.full}${text}`;
849
- if (combined.length <= MAX_PROCESS_OUTPUT_CHARS) {
850
- capture.full = combined;
851
- return;
852
- }
853
- capture.head = combined.slice(0, PROCESS_OUTPUT_HEAD_CHARS);
854
- capture.tail = combined.slice(-32e3);
855
- capture.full = void 0;
856
- return;
857
- }
858
- capture.tail = `${capture.tail}${text}`.slice(-32e3);
859
- }
860
- function summarizeProcessOutput(capture, max = 4e3) {
861
- const compact = (capture.full ?? `${capture.head}\n...[${capture.totalChars - capture.head.length - capture.tail.length} chars omitted]...\n${capture.tail}`).trim().replace(/\s+/g, " ");
862
- if (compact.length <= max) return compact;
863
- const headChars = Math.floor(max / 3);
864
- const tailChars = max - headChars;
865
- return `${compact.slice(0, headChars)}...[${compact.length - max} chars omitted]...${compact.slice(-tailChars)}`;
866
- }
867
- //#endregion
868
- //#region src/campaign/search-ledger-errors.ts
869
- /** Base error for invalid search-ledger input or operations. */
870
- var SearchLedgerError = class extends ValidationError {};
871
- /** Error raised when durable search-ledger data fails an integrity check. */
872
- var SearchLedgerIntegrityError = class extends SearchLedgerError {};
873
- /** Error raised when an event identifier is reused with different content. */
874
- var SearchLedgerConflictError = class extends SearchLedgerError {};
875
- //#endregion
876
- //#region src/campaign/search-ledger-file.ts
877
- /** Campaign binding of the generic journal file layer to search-ledger errors. */
878
- const SEARCH_LEDGER_FILE_CONTEXT = {
879
- subject: "search ledger",
880
- integrityError: (message, options) => new SearchLedgerIntegrityError(message, options)
881
- };
882
- function appendSearchLedgerLine(path, line) {
883
- appendLedgerLine(path, line, SEARCH_LEDGER_FILE_CONTEXT);
884
- }
885
- function tryWithSearchLedgerFileLock(ledgerPath, run) {
886
- return tryWithLedgerFileLock(ledgerPath, SEARCH_LEDGER_FILE_CONTEXT, run);
887
- }
888
- //#endregion
889
- //#region src/campaign/storage.ts
890
- /** Node-filesystem storage — the default. Lazily requires `node:fs` so the
891
- * module imports cleanly in non-Node runtimes (where the caller passes
892
- * `inMemoryCampaignStorage` instead and never constructs this).
893
- *
894
- * `createRequire(import.meta.url)` is the ESM-native lazy require — a bare
895
- * `require` is a ReferenceError under `"type": "module"`, which is exactly
896
- * the shape this package publishes. */
897
- function fsCampaignStorage() {
898
- const { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } = createRequire(import.meta.url)("node:fs");
899
- return {
900
- ensureDir(dir) {
901
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
902
- },
903
- exists(path) {
904
- return existsSync(path);
905
- },
906
- read(path) {
907
- try {
908
- return readFileSync(path, "utf8");
909
- } catch {
910
- return;
911
- }
912
- },
913
- write(path, content) {
914
- writeFileSync(path, content);
915
- },
916
- append(path, content, expectedBytes) {
917
- const result = tryWithSearchLedgerFileLock(path, () => {
918
- let actualBytes = 0;
919
- try {
920
- actualBytes = statSync(path).size;
921
- } catch (error) {
922
- if (error.code !== "ENOENT") throw error;
923
- }
924
- if (actualBytes !== expectedBytes) return void 0;
925
- appendSearchLedgerLine(path, content);
926
- return expectedBytes + Buffer.byteLength(content);
927
- });
928
- return result.acquired ? result.value : void 0;
929
- }
930
- };
931
- }
932
- /** In-memory storage for filesystem-less runtimes. Artifacts + trace spans
933
- * live in a `Map` for the duration of the run; the `CampaignResult` is
934
- * fully populated, but nothing is persisted to disk. */
935
- function inMemoryCampaignStorage() {
936
- const files = /* @__PURE__ */ new Map();
937
- const dirs = /* @__PURE__ */ new Set();
938
- return {
939
- ensureDir(dir) {
940
- dirs.add(dir);
941
- },
942
- exists(path) {
943
- return files.has(path) || dirs.has(path);
944
- },
945
- read(path) {
946
- const value = files.get(path);
947
- if (value === void 0) return void 0;
948
- return typeof value === "string" ? value : new TextDecoder().decode(value);
949
- },
950
- write(path, content) {
951
- files.set(path, content);
952
- },
953
- append(path, content, expectedBytes) {
954
- const current = files.get(path);
955
- const currentText = current === void 0 ? "" : typeof current === "string" ? current : new TextDecoder().decode(current);
956
- const currentBytes = new TextEncoder().encode(currentText).byteLength;
957
- if (currentBytes !== expectedBytes) return void 0;
958
- files.set(path, `${currentText}${content}`);
959
- return currentBytes + new TextEncoder().encode(content).byteLength;
960
- }
961
- };
962
- }
963
- /** Open the durable spend account stored beside a logical run. */
964
- function createRunCostLedger(input) {
965
- const path = join(input.runDir, "cost-ledger.jsonl");
966
- if (input.ensureRunDir ?? true) input.storage.ensureDir(input.runDir);
967
- return new CostLedger({
968
- costCeilingUsd: input.costCeilingUsd,
969
- persistence: {
970
- read: () => {
971
- const stored = input.storage.read(path);
972
- if (stored === void 0 && input.storage.exists(path)) throw new Error(`CostLedger: cannot read existing event log '${path}'`);
973
- const events = stored ?? "";
974
- return {
975
- revision: String(new TextEncoder().encode(events).byteLength),
976
- events
977
- };
978
- },
979
- append: (expectedRevision, event) => {
980
- const expectedBytes = Number(expectedRevision);
981
- if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0) throw new Error(`CostLedger: invalid storage revision '${expectedRevision}'`);
982
- const next = input.storage.append(path, event, expectedBytes);
983
- return next === void 0 ? void 0 : String(next);
984
- }
985
- }
986
- });
987
- }
988
- //#endregion
989
- //#region src/campaign/single-run-lock.ts
990
- /**
991
- * Single-run lock for evaluations that share one mutable environment.
992
- *
993
- * Two concurrent runs against a shared stateful gym silently corrupt each
994
- * other: each resets/mutates environment state mid-cell of the other, and
995
- * every score from both becomes garbage that LOOKS like worker variance
996
- * (agent-lab R357 burned hours on flip-flopping scores before tracing them
997
- * to exactly this). The fix is a pid lockfile: refuse to start while a live
998
- * holder exists, reclaim stale locks whose pid is gone, release only if the
999
- * lock is still ours.
1000
- *
1001
- * `alsoCheck` exists because independent runners can guard the same shared
1002
- * resource with differently named lockfiles; a runner must respect all of
1003
- * them even though it writes only its own.
1004
- */
1005
- function assertAvailable(path) {
1006
- const unavailable = probeAtomicFileLock({ lockPath: path });
1007
- if (unavailable) throw unavailableError(path, unavailable);
1008
- }
1009
- function unavailableError(path, unavailable) {
1010
- if (unavailable.reason === "recovery") return /* @__PURE__ */ new Error(`single-run lock recovery is already in progress (${path}); refusing a concurrent run`);
1011
- return /* @__PURE__ */ new Error(`single-run lock held by live pid ${unavailable.holder.pid} (${path}); refusing a concurrent run on the shared resource`);
1012
- }
1013
- /**
1014
- * Acquire the lock or throw naming the live holder. A stale lock (holder pid
1015
- * no longer running) is reclaimed by one contender. An interrupted reclaim
1016
- * leaves a marker that fails closed instead of admitting overlapping runs.
1017
- */
1018
- function acquireSingleRunLock(opts) {
1019
- const pid = opts.pid ?? process.pid;
1020
- if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("single-run lock pid must be a positive integer");
1021
- for (const path of opts.alsoCheck ?? []) assertAvailable(path);
1022
- const acquisition = tryAcquireAtomicFileLock({
1023
- lockPath: opts.lockPath,
1024
- pid
1025
- });
1026
- if (!acquisition.acquired) throw unavailableError(opts.lockPath, acquisition);
1027
- const releaseOnExit = opts.releaseOnExit ?? true;
1028
- let released = false;
1029
- const release = () => {
1030
- if (released) return;
1031
- released = true;
1032
- if (releaseOnExit) process.off("exit", release);
1033
- try {
1034
- acquisition.lock.release();
1035
- } catch {}
1036
- };
1037
- try {
1038
- for (const path of opts.alsoCheck ?? []) assertAvailable(path);
1039
- } catch (error) {
1040
- release();
1041
- throw error;
1042
- }
1043
- if (releaseOnExit) process.on("exit", release);
1044
- return { release };
1045
- }
1046
- //#endregion
1047
- export { safePathComponent as C, removeCredentialEnvironment as S, assertJsonValue as _, SEARCH_LEDGER_FILE_CONTEXT as a, isExternalTextCandidate as b, SearchLedgerIntegrityError as c, runWithCleanup as d, startExternalOptimizerModelProxy as f, assertExternalOptimizerModelBudget as g, sendJson as h, inMemoryCampaignStorage as i, runExternalOptimizerProcess as l, listenLocal as m, createRunCostLedger as n, SearchLedgerConflictError as o, closeServer as p, fsCampaignStorage as r, SearchLedgerError as s, acquireSingleRunLock as t, closeExternalOptimizerResources as u, assertNoCredentialValues as v, isRecord as x, isCandidateText as y };
1048
-
1049
- //# sourceMappingURL=single-run-lock-Do-8vBIJ.js.map