@tangle-network/agent-runtime 6.0.1 → 6.0.3

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 (83) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/{activation-BRfZOfwb.js → activation-DNqjZEo7.js} +4 -4
  3. package/dist/{activation-BRfZOfwb.js.map → activation-DNqjZEo7.js.map} +1 -1
  4. package/dist/agent.js +4 -4
  5. package/dist/{bundle-vFFiCigS.js → bundle-BET6gl5r.js} +2 -2
  6. package/dist/{bundle-vFFiCigS.js.map → bundle-BET6gl5r.js.map} +1 -1
  7. package/dist/candidate-execution/index.js +4 -4
  8. package/dist/{coordination-manager-RSJg5GmY.js → coordination-manager-CYElgkMI.js} +7 -6
  9. package/dist/{coordination-manager-RSJg5GmY.js.map → coordination-manager-CYElgkMI.js.map} +1 -1
  10. package/dist/{coordination-map-routing-DVjW5Gx0.js → coordination-map-routing-CKRNZSaV.js} +2 -2
  11. package/dist/{coordination-map-routing-DVjW5Gx0.js.map → coordination-map-routing-CKRNZSaV.js.map} +1 -1
  12. package/dist/{delegate-C0cprMUN.js → delegate-dW2jsqFF.js} +2 -2
  13. package/dist/{delegate-C0cprMUN.js.map → delegate-dW2jsqFF.js.map} +1 -1
  14. package/dist/durable.js +12 -11
  15. package/dist/durable.js.map +1 -1
  16. package/dist/failure-cause-BzjUUsRz.js +3208 -0
  17. package/dist/failure-cause-BzjUUsRz.js.map +1 -0
  18. package/dist/{graph-cEg-gquv.js → graph-A7AvOP1I.js} +7 -6
  19. package/dist/{graph-cEg-gquv.js.map → graph-A7AvOP1I.js.map} +1 -1
  20. package/dist/{graph-registry-C-hjRx2t.js → graph-registry-C4ASeL2P.js} +1 -1
  21. package/dist/{graph-registry-B25FxBZN.js → graph-registry-DbCwfHMY.js} +3 -3
  22. package/dist/{graph-registry-B25FxBZN.js.map → graph-registry-DbCwfHMY.js.map} +1 -1
  23. package/dist/{improve-DNl4_6lP.js → improve-4qJclc9J.js} +10 -8
  24. package/dist/{improve-DNl4_6lP.js.map → improve-4qJclc9J.js.map} +1 -1
  25. package/dist/index.js +13 -11
  26. package/dist/index.js.map +1 -1
  27. package/dist/intelligence.js +8 -8
  28. package/dist/jsonl-file-BeUa5EDx.js +232 -0
  29. package/dist/jsonl-file-BeUa5EDx.js.map +1 -0
  30. package/dist/kernel.js +14 -13
  31. package/dist/{loop-runner-DQJjowz0.js → loop-runner-DZxVXLLU.js} +2 -2
  32. package/dist/{loop-runner-DQJjowz0.js.map → loop-runner-DZxVXLLU.js.map} +1 -1
  33. package/dist/loop-runner-bin.js +1 -1
  34. package/dist/mcp/bin.js +3 -3
  35. package/dist/mcp/index.js +7 -7
  36. package/dist/mcp/memory-bin.js +1 -1
  37. package/dist/{prepare-B6SQA12v.js → prepare-O1HbzOqs.js} +4 -3
  38. package/dist/{prepare-B6SQA12v.js.map → prepare-O1HbzOqs.js.map} +1 -1
  39. package/dist/{profile-DN8Dw2Kp.js → profile-DcRoyryP.js} +2 -2
  40. package/dist/{profile-DN8Dw2Kp.js.map → profile-DcRoyryP.js.map} +1 -1
  41. package/dist/{provision-supervisor-CtAaJCUa.js → provision-supervisor-CBeTMpMY.js} +7 -6
  42. package/dist/{provision-supervisor-CtAaJCUa.js.map → provision-supervisor-CBeTMpMY.js.map} +1 -1
  43. package/dist/{run-cancellation-BCuu6khW.js → run-cancellation-ZmRSYLu5.js} +4 -3
  44. package/dist/{run-cancellation-BCuu6khW.js.map → run-cancellation-ZmRSYLu5.js.map} +1 -1
  45. package/dist/{run-state-ByHiAjUs.js → run-state-Dn2AIE5m.js} +6 -6
  46. package/dist/{run-state-ByHiAjUs.js.map → run-state-Dn2AIE5m.js.map} +1 -1
  47. package/dist/{runtime-9EYvBcHG.js → runtime-D5eL70Is.js} +20 -17
  48. package/dist/{runtime-9EYvBcHG.js.map → runtime-D5eL70Is.js.map} +1 -1
  49. package/dist/{scope-DzhBJrRN.js → scope-DSm2RW5I.js} +9 -3204
  50. package/dist/scope-DSm2RW5I.js.map +1 -0
  51. package/dist/{search-executor-BJRNavck.js → search-executor-1qaSeY70.js} +6 -4
  52. package/dist/{search-executor-BJRNavck.js.map → search-executor-1qaSeY70.js.map} +1 -1
  53. package/dist/{server-DH0P6OY_.js → server-Dp4JKuTZ.js} +5 -5
  54. package/dist/{server-DH0P6OY_.js.map → server-Dp4JKuTZ.js.map} +1 -1
  55. package/dist/{settle-record-BSDDf9Z4.js → settle-record-DTh0cvF-.js} +2 -2
  56. package/dist/{settle-record-BSDDf9Z4.js.map → settle-record-DTh0cvF-.js.map} +1 -1
  57. package/dist/snapshot-Cgj2Wzi6.js +210 -0
  58. package/dist/snapshot-Cgj2Wzi6.js.map +1 -0
  59. package/dist/{structural-rollout-DgvJLTO0.js → structural-rollout-BwyAIuww.js} +6 -4
  60. package/dist/{structural-rollout-DgvJLTO0.js.map → structural-rollout-BwyAIuww.js.map} +1 -1
  61. package/dist/{supervise-Cqhkb2Oj.js → supervise-C2Do7hEd.js} +11 -10
  62. package/dist/{supervise-Cqhkb2Oj.js.map → supervise-C2Do7hEd.js.map} +1 -1
  63. package/dist/{supervision-discovery-DI5GIFBJ.js → supervision-discovery-BNChDps7.js} +5 -4
  64. package/dist/{supervision-discovery-DI5GIFBJ.js.map → supervision-discovery-BNChDps7.js.map} +1 -1
  65. package/dist/{supervisor-B6sl14OR.js → supervisor-jXN2xXiU.js} +8 -5
  66. package/dist/{supervisor-B6sl14OR.js.map → supervisor-jXN2xXiU.js.map} +1 -1
  67. package/dist/testing.js +13 -13
  68. package/dist/{tool-server-CZWd_Opp.js → tool-server-B9q2dtnW.js} +11 -8
  69. package/dist/tool-server-B9q2dtnW.js.map +1 -0
  70. package/dist/{top-web-DGoXGxH8.js → top-web-CQNkrh_j.js} +7 -6
  71. package/dist/{top-web-DGoXGxH8.js.map → top-web-CQNkrh_j.js.map} +1 -1
  72. package/dist/tui/bin.js +3 -3
  73. package/dist/tui/index.js +2 -2
  74. package/dist/util-C_cdPNC4.js +653 -0
  75. package/dist/util-C_cdPNC4.js.map +1 -0
  76. package/dist/{workspace-streams-BqNM06y4.js → workspace-streams-uB9rRbms.js} +3 -652
  77. package/dist/workspace-streams-uB9rRbms.js.map +1 -0
  78. package/package.json +3 -3
  79. package/dist/jsonl-file-CeVYTIQJ.js +0 -439
  80. package/dist/jsonl-file-CeVYTIQJ.js.map +0 -1
  81. package/dist/scope-DzhBJrRN.js.map +0 -1
  82. package/dist/tool-server-CZWd_Opp.js.map +0 -1
  83. package/dist/workspace-streams-BqNM06y4.js.map +0 -1
package/dist/tui/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { S as writeWorkerSteer, c as cancelWorker, v as supervisorRunsRoot } from "../scope-DzhBJrRN.js";
3
- import { n as cancelRun } from "../run-cancellation-BCuu6khW.js";
4
- import { c as numberValue, f as totalSpend, i as aggregateSnapshot, l as parseSpend, n as runTopWeb, s as loadTopSnapshot, u as parseTime } from "../top-web-DGoXGxH8.js";
2
+ import { S as writeWorkerSteer, c as cancelWorker, v as supervisorRunsRoot } from "../scope-DSm2RW5I.js";
3
+ import { n as cancelRun } from "../run-cancellation-ZmRSYLu5.js";
4
+ import { c as numberValue, f as totalSpend, i as aggregateSnapshot, l as parseSpend, n as runTopWeb, s as loadTopSnapshot, u as parseTime } from "../top-web-CQNkrh_j.js";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { resolve } from "node:path";
7
7
  import { hostname, userInfo } from "node:os";
package/dist/tui/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { t as provisionSupervisor } from "../provision-supervisor-CtAaJCUa.js";
2
- import { _ as topAgentMetadata, a as buildSupervisorView, d as topSnapshot, g as readTopAgentInspection, h as readTopAgentHistory, m as harnessSessionRows, o as isSpawnEvent, p as createTopAgentStream, r as serveTopWeb, s as loadTopSnapshot, t as TOP_SNAPSHOT_RECONCILE_MS, v as topAgentWorker } from "../top-web-DGoXGxH8.js";
1
+ import { t as provisionSupervisor } from "../provision-supervisor-CBeTMpMY.js";
2
+ import { _ as topAgentMetadata, a as buildSupervisorView, d as topSnapshot, g as readTopAgentInspection, h as readTopAgentHistory, m as harnessSessionRows, o as isSpawnEvent, p as createTopAgentStream, r as serveTopWeb, s as loadTopSnapshot, t as TOP_SNAPSHOT_RECONCILE_MS, v as topAgentWorker } from "../top-web-CQNkrh_j.js";
3
3
  export { TOP_SNAPSHOT_RECONCILE_MS, createTopAgentStream, harnessSessionRows, isSpawnEvent as isTopJournalEvent, loadTopSnapshot, topSnapshot as projectTopSnapshot, buildSupervisorView as projectTopSupervisor, provisionSupervisor, readTopAgentHistory, readTopAgentInspection, serveTopWeb, topAgentMetadata, topAgentWorker };
@@ -0,0 +1,653 @@
1
+ import { m as ValidationError } from "./errors-AzSuGI23.js";
2
+ import { t as runTaskQueue } from "./task-queue-DbpZAp6C.js";
3
+ // src/runtime/supervise/deadline.ts
4
+ const MAX_TIMER_DELAY_MS = 2147483647;
5
+ const DEFAULT_SUCCESSFUL_SHUTDOWN_MS = 5e3;
6
+ /** The abort reason a child's own deadline carries. */
7
+ const CHILD_DEADLINE_REASON = "child deadline exceeded";
8
+ /** The abort reason the root's budget deadline cascades to every node. */
9
+ const ROOT_DEADLINE_REASON = "root budget deadline exceeded";
10
+ /** The check-in a child receives at its own time box. */
11
+ const DEADLINE_CHECK_IN_MESSAGE = "Check-in: your time box has ended. This is not a stop. Finish the step you are on and start nothing new. Record your current state and every result you have not recorded yet, then call submit_result with what you have now; if the work is not done, mark it incomplete and name what remains. Your lead decides whether to continue you or hand the work on. You keep running while you make progress.";
12
+ /** The idle bound a check-in policy sets, or undefined when time boxes are hard kills. */
13
+ function checkInIdleMs(policy) {
14
+ if (policy === false) return void 0;
15
+ const idleMs = policy?.idleMs ?? 18e5;
16
+ if (!Number.isSafeInteger(idleMs) || idleMs <= 0) throw new ValidationError("deadlineCheckIn.idleMs must be a positive safe integer of milliseconds");
17
+ return idleMs;
18
+ }
19
+ /** How long a manager whose result was accepted has to end the turn that submitted it before an
20
+ * abort, or Runtime's cancel of its retained run, stops its harness: the turn's end meters its
21
+ * usage and commits its result; its workspace capture runs after, in the manager's owner. */
22
+ const ACCEPTED_RESULT_GRACE_MS = 3e5;
23
+ /** Whether an abort reason is a deadline: the child's own or the root budget's. */
24
+ function isDeadlineAbortReason(reason) {
25
+ return reason === "child deadline exceeded" || reason === "root budget deadline exceeded";
26
+ }
27
+ const TEARDOWN_ACKNOWLEDGEMENT_MS = 250;
28
+ /** Arm a finite wall-clock deadline in safe chunks. Resource deadlines unref by default;
29
+ * a standalone wait opts into keeping the process alive until it settles or is cancelled. */
30
+ function armDeadlineTimer(delayMs, onDeadline, keepAlive = false) {
31
+ const deadlineAtMs = Date.now() + Math.max(0, delayMs);
32
+ if (!Number.isFinite(delayMs) || !Number.isSafeInteger(Math.ceil(deadlineAtMs))) throw new ValidationError("timer delay must produce a finite safe deadline");
33
+ let cleared = false;
34
+ let timer;
35
+ const arm = () => {
36
+ if (cleared) return;
37
+ const remainingMs = Math.max(0, deadlineAtMs - Date.now());
38
+ timer = setTimeout(() => {
39
+ if (cleared) return;
40
+ if (Date.now() >= deadlineAtMs) onDeadline();
41
+ else arm();
42
+ }, Math.min(remainingMs, MAX_TIMER_DELAY_MS));
43
+ if (!keepAlive && typeof timer.unref === "function") timer.unref();
44
+ };
45
+ arm();
46
+ return () => {
47
+ cleared = true;
48
+ if (timer !== void 0) clearTimeout(timer);
49
+ };
50
+ }
51
+ /**
52
+ * Resolve a spawned child's duration into one absolute cutoff. An omitted child deadline inherits
53
+ * the parent cutoff; an explicit child duration may shorten, but never extend, that cutoff.
54
+ */
55
+ function boundedChildDeadlineAt(parentDeadlineAtMs, childDeadlineMs, nowMs) {
56
+ const parent = parentDeadlineAtMs > 0 ? parentDeadlineAtMs : void 0;
57
+ const child = childDeadlineMs === void 0 ? void 0 : nowMs + childDeadlineMs;
58
+ if (parent === void 0) return child;
59
+ if (child === void 0) return parent;
60
+ return Math.min(parent, child);
61
+ }
62
+ /** Invoke teardown once and bound how long the runtime waits for its acknowledgement. A hard
63
+ * execution deadline always wins; without one, numeric grace gets a short acknowledgement
64
+ * allowance and a brutal kill gets only that allowance. Explicit `infinity` remains unbounded
65
+ * only when no execution deadline exists. The losing promise stays observed. `ask` issues the
66
+ * request; a scope passes its per-child single-flight asker (see `singleFlightTeardown`). */
67
+ async function teardownExecutor(executor, grace, deadlineAtMs, now, ask = (requested) => Promise.resolve(executor.teardown(requested))) {
68
+ const work = Promise.resolve(ask(grace));
69
+ const requestedWaitMs = grace === "infinity" ? void 0 : grace === "brutalKill" ? executor.teardownTimeoutMs ?? TEARDOWN_ACKNOWLEDGEMENT_MS : grace + TEARDOWN_ACKNOWLEDGEMENT_MS;
70
+ const deadlineWaitMs = deadlineAtMs === void 0 ? void 0 : Math.max(0, deadlineAtMs - now()) + TEARDOWN_ACKNOWLEDGEMENT_MS;
71
+ const waitMs = requestedWaitMs === void 0 ? deadlineWaitMs : deadlineWaitMs === void 0 ? requestedWaitMs : Math.min(requestedWaitMs, deadlineWaitMs);
72
+ let receipt;
73
+ if (waitMs === void 0) receipt = await work;
74
+ else if (waitMs <= 0) {
75
+ work.catch(() => void 0);
76
+ throw new ValidationError("executor teardown did not acknowledge before its deadline");
77
+ } else {
78
+ let clearTimer;
79
+ const timedOut = new Promise((_resolve, reject) => {
80
+ clearTimer = armDeadlineTimer(waitMs, () => reject(new ValidationError(`executor teardown did not acknowledge within ${waitMs}ms`)), true);
81
+ });
82
+ try {
83
+ receipt = await Promise.race([work, timedOut]);
84
+ } finally {
85
+ clearTimer?.();
86
+ }
87
+ }
88
+ if (!receipt.destroyed) throw new ValidationError(`executor teardown reported destroyed=false${receipt.detail ? `: ${receipt.detail}` : ""}`);
89
+ }
90
+ /**
91
+ * The optional teardown surfaces a wrapping executor forwards, so wrapping never changes how a
92
+ * child is released: the acknowledgement window a remote teardown needs, the release of a
93
+ * retained execution at root settlement, and the environments an unconfirmed teardown names for
94
+ * a sweeper. A wrapper that dropped `releaseRetained` left every retained child it wrapped
95
+ * running after settlement. Each surface is present only when the inner executor implements it.
96
+ */
97
+ function teardownSurfaces(inner) {
98
+ return {
99
+ ...inner.teardownTimeoutMs === void 0 ? {} : { teardownTimeoutMs: inner.teardownTimeoutMs },
100
+ ...inner.releaseRetained === void 0 ? {} : { releaseRetained: (signal) => inner.releaseRetained(signal) },
101
+ ...inner.heldEnvironments === void 0 ? {} : { heldEnvironments: () => inner.heldEnvironments() },
102
+ ...inner.heldForContinuation === void 0 ? {} : { heldForContinuation: () => inner.heldForContinuation() }
103
+ };
104
+ }
105
+ /**
106
+ * An asker that sends an executor at most one teardown at a time. While a request is still
107
+ * running, every later ask returns that same request instead of sending another beside it.
108
+ *
109
+ * A settlement's own teardown has a short acknowledgement window, and a request that misses it
110
+ * keeps running. Without this, the first settlement retry sent a second teardown next to the
111
+ * first. An executor that does not deduplicate internally, such as one that re-issues its
112
+ * cancels, then ran two teardowns at once. `onRequest` runs once for each request actually sent.
113
+ */
114
+ function singleFlightTeardown(executor, onRequest) {
115
+ let inFlight;
116
+ return (grace) => {
117
+ if (inFlight !== void 0) return inFlight;
118
+ onRequest();
119
+ let request;
120
+ try {
121
+ request = Promise.resolve(executor.teardown(grace));
122
+ } catch (error) {
123
+ request = Promise.reject(error);
124
+ }
125
+ inFlight = request;
126
+ const settle = () => {
127
+ if (inFlight === request) inFlight = void 0;
128
+ };
129
+ request.then(settle, settle);
130
+ return request;
131
+ };
132
+ }
133
+ // src/runtime/supervise/resources.ts
134
+ /** Validate caller-owned names and units without assigning domain meaning to them. */
135
+ function assertResources(resources, kind, label) {
136
+ if (resources === void 0) return;
137
+ if (resources === null || typeof resources !== "object" || Array.isArray(resources)) throw new Error(`${label} must be a resource map`);
138
+ for (const [name, resource] of Object.entries(resources)) {
139
+ if (!name.trim() || !resource || typeof resource !== "object" || typeof resource.unit !== "string" || !resource.unit.trim()) throw new Error(`${label}: resource names and units must be non-empty strings`);
140
+ const value = kind === "limit" ? "limit" in resource ? resource.limit : void 0 : "amount" in resource ? resource.amount : void 0;
141
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${label}.${name}.${kind} must be a non-negative safe integer`);
142
+ if (kind === "amount" && (!("known" in resource) || typeof resource.known !== "boolean")) throw new Error(`${label}.${name}.known must be a boolean`);
143
+ }
144
+ }
145
+ /** Missing contributors are not usage claims; enforced omissions are marked before aggregation.
146
+ * Overflow retains a safe lower bound and marks it unknown, preserving readable component receipts. */
147
+ function addResourceSpend(...maps) {
148
+ const totals = /* @__PURE__ */ new Map();
149
+ for (const resources of maps) {
150
+ assertResources(resources, "amount", "resource spend");
151
+ for (const [name, resource] of Object.entries(resources ?? {})) {
152
+ const prior = totals.get(name);
153
+ if (prior && prior.unit !== resource.unit) throw new Error(`resource ${name}: unit mismatch`);
154
+ const amount = (prior?.amount ?? 0) + resource.amount;
155
+ totals.set(name, {
156
+ unit: resource.unit,
157
+ amount: Math.min(amount, Number.MAX_SAFE_INTEGER),
158
+ known: (prior?.known ?? true) && resource.known && Number.isSafeInteger(amount)
159
+ });
160
+ }
161
+ }
162
+ return totals.size ? { resources: Object.fromEntries(totals) } : {};
163
+ }
164
+ /** A terminal omission under an enforced ceiling is unknown, never measured zero. */
165
+ function withBudgetResources(spend, budget, notStarted = false) {
166
+ const resources = new Map(Object.entries(addResourceSpend(spend.resources).resources ?? {}));
167
+ for (const [name, limit] of Object.entries(budget.resources ?? {})) {
168
+ const observed = resources.get(name);
169
+ if (observed && observed.unit !== limit.unit) throw new Error(`resource ${name}: unit mismatch`);
170
+ if (!observed) resources.set(name, {
171
+ unit: limit.unit,
172
+ amount: 0,
173
+ known: notStarted
174
+ });
175
+ }
176
+ return resources.size ? {
177
+ ...spend,
178
+ resources: Object.fromEntries(resources)
179
+ } : spend;
180
+ }
181
+ /** Stream increments and a terminal total describe the same work; never sum them twice. */
182
+ function resourceTelemetry(streamed, terminal) {
183
+ const resources = new Map(Object.entries(addResourceSpend(terminal.resources).resources ?? {}));
184
+ for (const [name, value] of Object.entries(streamed.resources ?? {})) {
185
+ const other = resources.get(name);
186
+ if (other && other.unit !== value.unit) throw new Error(`resource ${name}: unit mismatch`);
187
+ resources.set(name, {
188
+ ...value,
189
+ amount: Math.max(value.amount, other?.amount ?? 0),
190
+ known: value.known && (other?.known ?? true) && (other === void 0 || other.amount === value.amount)
191
+ });
192
+ }
193
+ return addResourceSpend(Object.fromEntries(resources));
194
+ }
195
+ // src/runtime/util.ts
196
+ /**
197
+ * Best-effort sandbox delete. Skips instances without a `delete` (test fakes);
198
+ * swallows errors (the platform reaps on expiry). Returns `false` when delete
199
+ * threw, `true` otherwise, so callers can surface a leak if they choose.
200
+ */
201
+ async function deleteBoxSafe(box) {
202
+ if (!box || typeof box.delete !== "function") return true;
203
+ try {
204
+ await box.delete();
205
+ return true;
206
+ } catch {
207
+ return false;
208
+ }
209
+ }
210
+ /** Short base36 id for trace correlation. Not cryptographic, not collision-free. */
211
+ function randomSuffix(len = 8) {
212
+ return Math.random().toString(36).slice(2, 2 + len);
213
+ }
214
+ /** Collision-resistant id for sandbox naming (find-by-name recovery must be unique). */
215
+ function randomUuid() {
216
+ return crypto.randomUUID();
217
+ }
218
+ /** Construct an AbortError carrying the abort reason's message. Downstream code pattern-matches on `err.name`. */
219
+ function abortError(reason) {
220
+ const err = new Error(reason instanceof Error ? reason.message : reason === void 0 ? "aborted" : String(reason));
221
+ err.name = "AbortError";
222
+ return err;
223
+ }
224
+ /** Throw an AbortError. */
225
+ function throwAbort() {
226
+ throw abortError();
227
+ }
228
+ /** Throw if the signal is already aborted; otherwise no-op. */
229
+ function throwIfAborted(signal) {
230
+ if (signal?.aborted) throw abortError();
231
+ }
232
+ /** True for any error whose `name` is `AbortError` (the cross-kernel abort contract). */
233
+ function isAbortError(err) {
234
+ return err instanceof Error && err.name === "AbortError";
235
+ }
236
+ /**
237
+ * Sleep that resolves early on abort and always clears its timer so it never
238
+ * keeps the event loop alive. Resolves (does not reject) on abort — callers
239
+ * re-check the signal explicitly after the sleep.
240
+ */
241
+ function sleep(ms, signal, keepAlive = true) {
242
+ if (signal?.aborted) return Promise.resolve();
243
+ return new Promise((resolve) => {
244
+ const done = () => {
245
+ clearTimer();
246
+ signal?.removeEventListener("abort", done);
247
+ resolve();
248
+ };
249
+ const clearTimer = armDeadlineTimer(ms, done, keepAlive);
250
+ signal?.addEventListener("abort", done, { once: true });
251
+ });
252
+ }
253
+ /**
254
+ * Race a promise against a timeout. Resolves with the value if it settles in
255
+ * time, otherwise resolves with `undefined`. Always clears the timer.
256
+ */
257
+ function withTimeout(promise, ms) {
258
+ return new Promise((resolve) => {
259
+ const clearTimer = armDeadlineTimer(ms, () => resolve(void 0), true);
260
+ promise.then((value) => {
261
+ clearTimer();
262
+ resolve(value);
263
+ }, () => {
264
+ clearTimer();
265
+ resolve(void 0);
266
+ });
267
+ });
268
+ }
269
+ /**
270
+ * `JSON.stringify` with a `String()` fallback on throw (cyclic / non-JSON).
271
+ * Strings pass through unstringified so a preview of a string output is the
272
+ * string itself, not a quoted re-encoding.
273
+ */
274
+ function stringifySafe(value, opts = {}) {
275
+ let s;
276
+ try {
277
+ if (typeof value === "string") s = value;
278
+ else s = (opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value)) ?? String(value);
279
+ } catch {
280
+ s = String(value);
281
+ }
282
+ if (opts.max !== void 0 && s.length > opts.max) return `${s.slice(0, opts.max)}…`;
283
+ return s;
284
+ }
285
+ /** A fresh zero token-usage accumulator. */
286
+ function zeroTokenUsage() {
287
+ return {
288
+ input: 0,
289
+ output: 0
290
+ };
291
+ }
292
+ /**
293
+ * Sum the catalog-priced part of a dollar total across spends, as a field to spread.
294
+ *
295
+ * Returns nothing when no input carried one. A fold of pure provider receipts must not gain a
296
+ * `usdEstimated: 0`, which would read as "this runtime checked and priced none" on a path that
297
+ * never prices at all.
298
+ */
299
+ function usdEstimatedOf(...spends) {
300
+ let total = 0;
301
+ let priced = false;
302
+ for (const spend of spends) {
303
+ if (spend.usdEstimated === void 0) continue;
304
+ priced = true;
305
+ total += spend.usdEstimated;
306
+ }
307
+ return priced ? { usdEstimated: total } : {};
308
+ }
309
+ /** A conserved spend with every channel at zero and no completeness claim on it. */
310
+ function zeroSpend() {
311
+ return {
312
+ iterations: 0,
313
+ tokens: zeroTokenUsage(),
314
+ usd: 0,
315
+ ms: 0
316
+ };
317
+ }
318
+ /**
319
+ * The spend of work that HAPPENED and reported no usage receipt.
320
+ *
321
+ * Not the same value as {@link zeroSpend} even though both carry `{0,0}` tokens and `$0`. A bare
322
+ * zero asserts a MEASUREMENT — "this ran and cost nothing" — and every consumer downstream reads it
323
+ * that way: the pool keeps reporting `readout().tokensKnown === true`, the journal totals stay
324
+ * clean, the OTEL span records a priced zero, and a caller's token-denominated ceiling can never
325
+ * fire no matter how much the work really burned. A ceiling that cannot fire is worse than no
326
+ * ceiling, because it reads as protection.
327
+ *
328
+ * `tokensKnown` is the marker the substrate already threads end to end for exactly this case
329
+ * (`budget.ts`, `otel-spans.ts`, `spawn-journal.ts`, `supervisor.ts`): the work is recorded, the
330
+ * zero is labelled a floor rather than a total, and every rollup that touches it reports its
331
+ * balance as a ceiling rather than a measurement. Use this — never a bare zero — whenever a runtime
332
+ * cannot see what its worker spent.
333
+ *
334
+ * The same rule applies to dollars. A dollar-capped run must refuse an executor whose billed spend
335
+ * is unknowable; `budgetExempt` does not authorize Runtime to relabel unknown spend as a measured
336
+ * zero. Callers that require dollar accounting must use a backend with a trusted billing receipt.
337
+ */
338
+ function unmeteredSpend(ms) {
339
+ return {
340
+ iterations: 0,
341
+ tokens: zeroTokenUsage(),
342
+ tokensKnown: false,
343
+ usd: 0,
344
+ usdKnown: false,
345
+ ms
346
+ };
347
+ }
348
+ /** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */
349
+ function cloneSpend(spend) {
350
+ return {
351
+ ...addResourceSpend(spend.resources),
352
+ iterations: spend.iterations,
353
+ tokens: cloneTokenUsage(spend.tokens),
354
+ ...spend.tokensKnown === false ? { tokensKnown: false } : {},
355
+ usd: spend.usd,
356
+ ...spend.usdKnown === false ? { usdKnown: false } : {},
357
+ ...spend.usdEstimated !== void 0 ? { usdEstimated: spend.usdEstimated } : {},
358
+ ms: spend.ms,
359
+ ...boxMinutesOf(spend),
360
+ ...spend.tokensProvenance === void 0 ? {} : { tokensProvenance: spend.tokensProvenance }
361
+ };
362
+ }
363
+ /**
364
+ * Sum two conserved spends per channel. Tokens and dollars never fold into each other, an
365
+ * incomplete input keeps the sum incomplete on that channel, and the catalog-priced part of the
366
+ * dollar total is summed separately so `usd - usdEstimated` still names what a provider billed.
367
+ */
368
+ function addSpend(a, b) {
369
+ const tokens = cloneTokenUsage(a.tokens);
370
+ addTokenUsage(tokens, b.tokens);
371
+ return {
372
+ ...addResourceSpend(a.resources, b.resources),
373
+ iterations: a.iterations + b.iterations,
374
+ tokens,
375
+ ...a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {},
376
+ usd: a.usd + b.usd,
377
+ ...a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {},
378
+ ...usdEstimatedOf(a, b),
379
+ ms: a.ms + b.ms,
380
+ ...boxMinutesOf(a, b),
381
+ ...tokensProvenanceOf(a, b)
382
+ };
383
+ }
384
+ /**
385
+ * Fold the token-provenance channel across spends, as a field to spread.
386
+ *
387
+ * Returns nothing when no contributor stated one, because ABSENT already means "the executor's own
388
+ * live stream", which is what every path reported before a harness store was readable. A
389
+ * contributor that stated one and a contributor that did not therefore disagree, and the sum is
390
+ * `'mixed'` — the honest answer for a tree whose spend came from two kinds of receipt.
391
+ */
392
+ function tokensProvenanceOf(...spends) {
393
+ let folded;
394
+ let sawStated = false;
395
+ for (const spend of spends) {
396
+ const stated = spend.tokensProvenance ?? "stream-receipt";
397
+ if (spend.tokensProvenance !== void 0) sawStated = true;
398
+ folded = folded === void 0 || folded === stated ? stated : "mixed";
399
+ }
400
+ return !sawStated || folded === void 0 || folded === "stream-receipt" ? {} : { tokensProvenance: folded };
401
+ }
402
+ /**
403
+ * Fold the platform box-time channel across spends, as a field to spread.
404
+ *
405
+ * Returns nothing when no input carried the channel, so a fold over router or cli-bridge work —
406
+ * which runs no box at all — never gains a `boxMinutesProvenance: 'uncaptured'` that would claim
407
+ * a box ran and went unmetered.
408
+ *
409
+ * Three rules, one per field:
410
+ * - `boxMinutes` sums the numbers that are present, and stays ABSENT when none is. A missing
411
+ * measurement never enters the sum as a zero.
412
+ * - `boxMinutesKnown` is sticky-false, like `tokensKnown`: one contributor that could not state
413
+ * its box time makes the whole sum a floor.
414
+ * - `boxMinutesProvenance` degrades. `'observed'` survives only when every contributor that
415
+ * carried a number was observed; one derived number makes the sum `'estimated'`; no number at
416
+ * all is `'uncaptured'`.
417
+ */
418
+ function boxMinutesOf(...spends) {
419
+ const present = spends.filter((spend) => spend.boxMinutesProvenance !== void 0);
420
+ if (present.length === 0) return {};
421
+ let minutes = 0;
422
+ let sawNumber = false;
423
+ let known = true;
424
+ let observedOnly = true;
425
+ for (const spend of present) {
426
+ if (typeof spend.boxMinutes === "number" && Number.isFinite(spend.boxMinutes)) {
427
+ minutes += spend.boxMinutes;
428
+ sawNumber = true;
429
+ if (spend.boxMinutesProvenance !== "observed") observedOnly = false;
430
+ }
431
+ if (spend.boxMinutesKnown !== true) known = false;
432
+ }
433
+ return {
434
+ ...sawNumber ? { boxMinutes: roundBoxMinutes(minutes) } : {},
435
+ boxMinutesKnown: known,
436
+ boxMinutesProvenance: sawNumber ? observedOnly ? "observed" : "estimated" : "uncaptured"
437
+ };
438
+ }
439
+ /**
440
+ * Box minutes at four decimals — a tenth of a second.
441
+ *
442
+ * Fine enough that a box alive for two seconds reports `0.0333` instead of a zero that would read
443
+ * as a measured free box, and coarse enough that summing floats does not print
444
+ * `1.5000000000000002`.
445
+ */
446
+ function roundBoxMinutes(minutes) {
447
+ return Number(minutes.toFixed(4));
448
+ }
449
+ /** Copy a token subtotal without dropping optional provider cache telemetry. */
450
+ function cloneTokenUsage(usage) {
451
+ const cacheBreakdownUnknown = usage.cacheBreakdownKnown === false || usage.input > 0 && !hasClassifiedCacheBreakdown(usage);
452
+ return {
453
+ input: usage.input,
454
+ output: usage.output,
455
+ ...usage.tokensKnown === false ? { tokensKnown: false } : {},
456
+ ...usage.freshInput !== void 0 ? { freshInput: usage.freshInput } : {},
457
+ ...usage.cacheRead !== void 0 ? { cacheRead: usage.cacheRead } : {},
458
+ ...usage.cacheWrite !== void 0 ? { cacheWrite: usage.cacheWrite } : {},
459
+ ...cacheBreakdownUnknown ? { cacheBreakdownKnown: false } : {}
460
+ };
461
+ }
462
+ /** True only when every positive prompt token has a consistent cache classification. */
463
+ function hasCompleteCacheBreakdown(usage) {
464
+ if (usage.cacheBreakdownKnown === false) return false;
465
+ return hasClassifiedCacheBreakdown(usage);
466
+ }
467
+ function hasClassifiedCacheBreakdown(usage) {
468
+ if (usage.input === 0) return true;
469
+ if (usage.freshInput === void 0 || usage.cacheRead === void 0 || usage.cacheWrite === void 0) return false;
470
+ return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input;
471
+ }
472
+ /**
473
+ * The token charge for one observation: every token counted ONCE, at the moment it first enters
474
+ * the context — `input − cacheRead + output`.
475
+ *
476
+ * `input` is a rolled-up prompt total that re-counts a cached prefix on every turn that reads it,
477
+ * so charging `input` makes a 100K prefix read 40 times cost 4.1M for content authored once. A
478
+ * cache read is content that was already charged when it was written, so it is the one class the
479
+ * charge subtracts. Under a complete split the result is exactly `freshInput + cacheWrite`. No
480
+ * price weight is involved: this counts work, and money is a separate channel.
481
+ *
482
+ * The subtraction form is what makes the charge ADDITIVE. `input` and `cacheRead` both accumulate
483
+ * through `addTokenUsage`, so the charge on an aggregate equals the sum of the charges on the
484
+ * records that built it — including an aggregate that mixes classified and unclassified turns,
485
+ * where the unclassified remainder is charged in full and only the reported cache reads are
486
+ * credited. A form that read `freshInput + cacheWrite` directly loses that: one unclassified turn
487
+ * would drop the whole aggregate to `input + output` and over-charge every classified turn with it.
488
+ *
489
+ * The one arithmetic guarantee: a set of classes that does not FIT inside the prompt total it
490
+ * partitions credits nothing, so the charge is never below `output` and a class that overflows its
491
+ * own total buys no tokens. It is not a guarantee against a provider that reports a cache read it
492
+ * never served — that provider can under-report `input` just as easily, and the token channel is an
493
+ * accounting unit, not a trust boundary. Prompt tokens the provider left unclassified are charged
494
+ * in full, so a spend with no readable split charges an upper bound on newly-presented work rather
495
+ * than a measurement, and every caller that enforces a ceiling must report the difference
496
+ * (`BudgetPool` does it through `readout().cacheBreakdownKnown`).
497
+ */
498
+ function chargedTokens(usage) {
499
+ return usage.input - creditedCacheRead(usage) + usage.output;
500
+ }
501
+ /** `cacheRead` if the reported classes fit inside `input`, else nothing. */
502
+ function creditedCacheRead(usage) {
503
+ const { cacheRead } = usage;
504
+ if (cacheRead === void 0) return 0;
505
+ return classifiedTotal(usage, cacheRead) > usage.input ? 0 : cacheRead;
506
+ }
507
+ function classifiedTotal(usage, cacheRead) {
508
+ return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0);
509
+ }
510
+ /**
511
+ * Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds
512
+ * and `chargedTokens` credits.
513
+ *
514
+ * The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`
515
+ * vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the
516
+ * three outcomes are different facts that must not collapse into one another:
517
+ *
518
+ * - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,
519
+ * because a provider that says nothing about caching has not said the split is unknowable.
520
+ * - **Read and write both reported, and fitting inside `input`** — a complete partition, so
521
+ * `freshInput` is the remainder and the split is known.
522
+ * - **One counter reported, or classes that overflow `input`** — the counters that ARE measured
523
+ * pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports
524
+ * no write) still credits the read it measured, while declaring the rest unclassified so the
525
+ * charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a
526
+ * partition of a total it exceeds.
527
+ *
528
+ * A counter the provider did not report stays absent. A zero would claim the provider measured no
529
+ * cache, which is a different fact from a provider that did not report.
530
+ */
531
+ function promptCacheTokenClasses(input, promptCache) {
532
+ if (promptCache === void 0) return {};
533
+ const read = tokenCount(promptCache.readTokens);
534
+ const write = tokenCount(promptCache.writeTokens);
535
+ if (read === void 0 && write === void 0) return {};
536
+ if (input === void 0 || (read ?? 0) + (write ?? 0) > input) return { cacheBreakdownKnown: false };
537
+ if (read !== void 0 && write !== void 0) return {
538
+ freshInput: input - read - write,
539
+ cacheRead: read,
540
+ cacheWrite: write
541
+ };
542
+ return {
543
+ ...read !== void 0 ? { cacheRead: read } : {},
544
+ ...write !== void 0 ? { cacheWrite: write } : {},
545
+ cacheBreakdownKnown: false
546
+ };
547
+ }
548
+ function tokenCount(value) {
549
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
550
+ }
551
+ /**
552
+ * Add the observed subtotal into `acc`; token and cache incompleteness are sticky.
553
+ *
554
+ * A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO
555
+ * classes. Folding them in would hide the overflow: the accumulator's larger `input` can absorb a
556
+ * class total that overflowed the one delta that reported it, and `chargedTokens` would then credit
557
+ * at the aggregate a cache read it refuses at the record. That is the one way the charge could come
558
+ * out below the sum of the charges on the records that built it.
559
+ */
560
+ function addTokenUsage(acc, delta) {
561
+ acc.input += delta.input ?? 0;
562
+ acc.output += delta.output ?? 0;
563
+ if (delta.tokensKnown === false) acc.tokensKnown = false;
564
+ const input = delta.input ?? 0;
565
+ const fits = classifiedTotal(delta, delta.cacheRead ?? 0) <= input;
566
+ if (fits) {
567
+ if (delta.freshInput !== void 0) acc.freshInput = (acc.freshInput ?? 0) + delta.freshInput;
568
+ if (delta.cacheRead !== void 0) acc.cacheRead = (acc.cacheRead ?? 0) + delta.cacheRead;
569
+ if (delta.cacheWrite !== void 0) acc.cacheWrite = (acc.cacheWrite ?? 0) + delta.cacheWrite;
570
+ }
571
+ const classified = fits && delta.freshInput !== void 0 && delta.cacheRead !== void 0 && delta.cacheWrite !== void 0 && delta.freshInput + delta.cacheRead + delta.cacheWrite === input;
572
+ if (delta.cacheBreakdownKnown === false || input > 0 && !classified) acc.cacheBreakdownKnown = false;
573
+ }
574
+ /**
575
+ * Map `items` through `fn` with at most `limit` calls in flight at once,
576
+ * preserving input order in the result. On the first `fn` rejection no NEW
577
+ * items are picked up; already-in-flight calls are awaited, then the first
578
+ * error is rethrown. `limit` is clamped to ≥ 1.
579
+ *
580
+ * Used where a burst of provisioning (e.g. forking N child boxes) must respect
581
+ * the loop's concurrency bound instead of firing all N at once.
582
+ */
583
+ async function mapWithConcurrency(items, limit, fn) {
584
+ const results = new Array(items.length);
585
+ let next = 0;
586
+ for await (const settled of runTaskQueue({
587
+ concurrency: Math.max(1, Math.min(Math.floor(limit), items.length)),
588
+ take: () => {
589
+ const index = next++;
590
+ return index < items.length ? {
591
+ id: String(index),
592
+ value: index
593
+ } : void 0;
594
+ },
595
+ execute: ({ value: index }) => fn(items[index], index)
596
+ })) {
597
+ if (settled.status === "rejected") throw settled.reason;
598
+ results[settled.task.value] = settled.value;
599
+ }
600
+ return results;
601
+ }
602
+ /** The message of a thrown value: an `Error`'s own message, anything else stringified. */
603
+ function errorMessage(error) {
604
+ return error instanceof Error ? error.message : String(error);
605
+ }
606
+ /** True for an object whose `Symbol.asyncIterator` is callable, so `for await` can consume it. */
607
+ function isAsyncIterable(value) {
608
+ return value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
609
+ }
610
+ /** 32-bit FNV-1a over a string's UTF-16 code units, as eight lowercase hex digits. */
611
+ function fnv1a32Hex(text) {
612
+ let h = 2166136261;
613
+ for (let i = 0; i < text.length; i += 1) {
614
+ h ^= text.charCodeAt(i);
615
+ h = Math.imul(h, 16777619);
616
+ }
617
+ return (h >>> 0).toString(16).padStart(8, "0");
618
+ }
619
+ /** Parent journals may already contain an interrupted driver's inference prefix. */
620
+ function unreportedSpend(total, prior) {
621
+ const tokens = { ...total.tokens };
622
+ for (const key of [
623
+ "input",
624
+ "output",
625
+ "freshInput",
626
+ "cacheRead",
627
+ "cacheWrite"
628
+ ]) {
629
+ const value = total.tokens[key];
630
+ if (value !== void 0) tokens[key] = Math.max(0, value - (prior.tokens[key] ?? 0));
631
+ }
632
+ return {
633
+ ...total,
634
+ ...addResourceSpend(total.resources === void 0 ? void 0 : Object.fromEntries(Object.entries(total.resources).map(([name, value]) => {
635
+ const previous = prior.resources?.[name];
636
+ if (previous && previous.unit !== value.unit) throw new ValidationError(`resource ${name}: unit mismatch`);
637
+ return [name, {
638
+ ...value,
639
+ amount: Math.max(0, value.amount - (previous?.amount ?? 0)),
640
+ known: value.known && (previous?.known ?? true)
641
+ }];
642
+ }))),
643
+ iterations: Math.max(0, total.iterations - prior.iterations),
644
+ tokens,
645
+ usd: Math.max(0, total.usd - prior.usd),
646
+ ms: Math.max(0, total.ms - prior.ms),
647
+ ...total.usdEstimated === void 0 ? {} : { usdEstimated: Math.max(0, total.usdEstimated - (prior.usdEstimated ?? 0)) },
648
+ ...total.boxMinutes === void 0 ? {} : { boxMinutes: Math.max(0, total.boxMinutes - (prior.boxMinutes ?? 0)) }
649
+ };
650
+ }
651
+ export { withBudgetResources as A, singleFlightTeardown as B, unreportedSpend as C, addResourceSpend as D, zeroTokenUsage as E, ROOT_DEADLINE_REASON as F, teardownSurfaces as H, armDeadlineTimer as I, boundedChildDeadlineAt as L, CHILD_DEADLINE_REASON as M, DEADLINE_CHECK_IN_MESSAGE as N, assertResources as O, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as P, checkInIdleMs as R, unmeteredSpend as S, zeroSpend as T, teardownExecutor as V, roundBoxMinutes as _, cloneSpend as a, throwAbort as b, errorMessage as c, isAbortError as d, isAsyncIterable as f, randomUuid as g, randomSuffix as h, chargedTokens as i, ACCEPTED_RESULT_GRACE_MS as j, resourceTelemetry as k, fnv1a32Hex as l, promptCacheTokenClasses as m, addSpend as n, cloneTokenUsage as o, mapWithConcurrency as p, addTokenUsage as r, deleteBoxSafe as s, abortError as t, hasCompleteCacheBreakdown as u, sleep as v, withTimeout as w, throwIfAborted as x, stringifySafe as y, isDeadlineAbortReason as z };
652
+
653
+ //# sourceMappingURL=util-C_cdPNC4.js.map