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