@tangle-network/agent-runtime 0.193.1 → 0.194.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/{activation-BismttgN.js → activation-BQFIiyUG.js} +3 -3
  2. package/dist/{activation-BismttgN.js.map → activation-BQFIiyUG.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/candidate-execution/index.js +4 -4
  6. package/dist/{candidate-execution-BSkZErxD.js → candidate-execution-B6CDW-fp.js} +4 -4
  7. package/dist/{candidate-execution-BSkZErxD.js.map → candidate-execution-B6CDW-fp.js.map} +1 -1
  8. package/dist/{conversation-DILnmy84.js → conversation-BXPWMOSd.js} +4 -5
  9. package/dist/{conversation-DILnmy84.js.map → conversation-BXPWMOSd.js.map} +1 -1
  10. package/dist/conversation.d.ts +1 -1
  11. package/dist/conversation.js +1 -1
  12. package/dist/{coordination-driver-DujHiIGa.js → coordination-driver-iSN-m3VX.js} +281 -244
  13. package/dist/coordination-driver-iSN-m3VX.js.map +1 -0
  14. package/dist/{authoring-DWiqKSDY.js → delegate-DCC2muUd.js} +56 -13
  15. package/dist/delegate-DCC2muUd.js.map +1 -0
  16. package/dist/delegation-status-BlsbSeOB.js +358 -0
  17. package/dist/delegation-status-BlsbSeOB.js.map +1 -0
  18. package/dist/durable.d.ts +2 -2
  19. package/dist/durable.js +3 -3
  20. package/dist/{environment-provider-DEwsolvi.js → environment-provider-Dr-wfnHg.js} +422 -8
  21. package/dist/environment-provider-Dr-wfnHg.js.map +1 -0
  22. package/dist/{environment-provider-DpPGJfK-.d.ts → environment-provider-adVa6X7a.d.ts} +2 -2
  23. package/dist/environment-provider.d.ts +1 -1
  24. package/dist/environment-provider.js +1 -1
  25. package/dist/{graph-DORfp9WX.js → graph-DghidDx5.js} +138 -5
  26. package/dist/graph-DghidDx5.js.map +1 -0
  27. package/dist/graph.d.ts +3 -3
  28. package/dist/graph.js +4 -5
  29. package/dist/graph.js.map +1 -1
  30. package/dist/{improve-Bn1zpWHF.d.ts → improve-COGzLCiY.d.ts} +3 -3
  31. package/dist/{improvement-cycle-BbsiYcpH.js → improvement-cycle-DeS1ZC5B.js} +6 -6
  32. package/dist/{improvement-cycle-BbsiYcpH.js.map → improvement-cycle-DeS1ZC5B.js.map} +1 -1
  33. package/dist/{index-DV1lzp9p.d.ts → index-BEPjOPwH.d.ts} +49 -50
  34. package/dist/{index-Vz-13VZq.d.ts → index-CrBgLCIf.d.ts} +4 -4
  35. package/dist/{index-RM2oRI9s.d.ts → index-DO6DHgRP.d.ts} +2 -2
  36. package/dist/index.d.ts +8 -8
  37. package/dist/index.js +13 -13
  38. package/dist/intelligence.d.ts +5 -5
  39. package/dist/intelligence.js +6 -6
  40. package/dist/{executable-spec-DxuiDFAU.js → jsonl-file-Bh1Q9nt0.js} +59 -3
  41. package/dist/jsonl-file-Bh1Q9nt0.js.map +1 -0
  42. package/dist/kernel.d.ts +6 -6
  43. package/dist/kernel.js +11 -12
  44. package/dist/{knowledge-RW1pbZCH.js → knowledge-B5okOzBQ.js} +6 -6
  45. package/dist/{knowledge-RW1pbZCH.js.map → knowledge-B5okOzBQ.js.map} +1 -1
  46. package/dist/knowledge.d.ts +1 -1
  47. package/dist/knowledge.js +1 -1
  48. package/dist/{loop-runner-bin-CGraqNiA.d.ts → loop-runner-bin-Clc5IAwu.d.ts} +3 -3
  49. package/dist/{loop-runner-bin-sBwcyQTc.js → loop-runner-bin-U1J6x_UF.js} +3 -3
  50. package/dist/{loop-runner-bin-sBwcyQTc.js.map → loop-runner-bin-U1J6x_UF.js.map} +1 -1
  51. package/dist/loop-runner-bin.d.ts +1 -1
  52. package/dist/loop-runner-bin.js +1 -1
  53. package/dist/{materialization-CekWK6OO.js → materialization-vZssF9Nx.js} +28 -3
  54. package/dist/materialization-vZssF9Nx.js.map +1 -0
  55. package/dist/mcp/bin.js +3 -3
  56. package/dist/mcp/index.d.ts +4 -4
  57. package/dist/mcp/index.js +8 -8
  58. package/dist/mcp/index.js.map +1 -1
  59. package/dist/{openai-tools-6jUqkGG7.js → openai-tools-DmvmaG0a.js} +2 -2
  60. package/dist/{openai-tools-6jUqkGG7.js.map → openai-tools-DmvmaG0a.js.map} +1 -1
  61. package/dist/{prepare-B5fJ7mLS.js → prepare-C29kNAon.js} +9 -14
  62. package/dist/prepare-C29kNAon.js.map +1 -0
  63. package/dist/primeintellect/index.d.ts +1 -1
  64. package/dist/profiles.js +1 -1
  65. package/dist/{protected-model-port-B0xFSAjt.js → protected-model-port-CKYND416.js} +2 -2
  66. package/dist/{protected-model-port-B0xFSAjt.js.map → protected-model-port-CKYND416.js.map} +1 -1
  67. package/dist/{provision-supervisor-CddfH9mg.js → provision-supervisor-CRPbnJiB.js} +6 -8
  68. package/dist/{provision-supervisor-CddfH9mg.js.map → provision-supervisor-CRPbnJiB.js.map} +1 -1
  69. package/dist/{redact-D0OzQsyt.js → redact-BOU77QfQ.js} +1013 -24
  70. package/dist/redact-BOU77QfQ.js.map +1 -0
  71. package/dist/{researcher-hgPa5p9i.js → researcher-Cp4JRbFp.js} +2 -2
  72. package/dist/researcher-Cp4JRbFp.js.map +1 -0
  73. package/dist/{runtime-V91N6sPc.d.ts → runtime-B8x43nGP.d.ts} +5 -4
  74. package/dist/{runtime-ZM4i-jEF.js → runtime-BVrqSu0-.js} +22 -21
  75. package/dist/{runtime-ZM4i-jEF.js.map → runtime-BVrqSu0-.js.map} +1 -1
  76. package/dist/server-D6XmE1Du.js +1311 -0
  77. package/dist/server-D6XmE1Du.js.map +1 -0
  78. package/dist/{stream-agent-turn-1ahpdeIo.d.ts → stream-agent-turn-B-gtBlOy.d.ts} +2 -2
  79. package/dist/{stream-agent-turn-DWWe_7bh.js → stream-agent-turn-DOtEsvCV.js} +3 -3
  80. package/dist/{stream-agent-turn-DWWe_7bh.js.map → stream-agent-turn-DOtEsvCV.js.map} +1 -1
  81. package/dist/{structural-rollout-CktnUTCC.js → structural-rollout-BcPXFzVb.js} +16 -43
  82. package/dist/structural-rollout-BcPXFzVb.js.map +1 -0
  83. package/dist/{supervise-Dj6zd2C7.js → supervise-C0V3pZXK.js} +154 -1961
  84. package/dist/supervise-C0V3pZXK.js.map +1 -0
  85. package/dist/testing.d.ts +2 -2
  86. package/dist/testing.js +13 -13
  87. package/dist/tui/index.d.ts +1 -1
  88. package/dist/tui/index.js +1 -1
  89. package/dist/{types-CGez_ZHQ.d.ts → types-B_pNTBjK.d.ts} +5 -2
  90. package/dist/{workspace-archive-yAPDklLV.js → workspace-archive-BCezkeIk.js} +2 -2
  91. package/dist/{workspace-archive-yAPDklLV.js.map → workspace-archive-BCezkeIk.js.map} +1 -1
  92. package/package.json +1 -1
  93. package/skills/codemode/SKILL.md +2 -2
  94. package/skills/supervise/SKILL.md +24 -6
  95. package/dist/authoring-DWiqKSDY.js.map +0 -1
  96. package/dist/coordination-driver-DujHiIGa.js.map +0 -1
  97. package/dist/environment-provider-DEwsolvi.js.map +0 -1
  98. package/dist/executable-spec-DxuiDFAU.js.map +0 -1
  99. package/dist/graph-DORfp9WX.js.map +0 -1
  100. package/dist/jsonl-file-CDfsCI5s.js +0 -59
  101. package/dist/jsonl-file-CDfsCI5s.js.map +0 -1
  102. package/dist/materialization-CekWK6OO.js.map +0 -1
  103. package/dist/prepare-B5fJ7mLS.js.map +0 -1
  104. package/dist/redact-D0OzQsyt.js.map +0 -1
  105. package/dist/researcher-hgPa5p9i.js.map +0 -1
  106. package/dist/snapshot-CTAf4uuA.js +0 -26
  107. package/dist/snapshot-CTAf4uuA.js.map +0 -1
  108. package/dist/spawn-journal-B9eTmVAn.js +0 -999
  109. package/dist/spawn-journal-B9eTmVAn.js.map +0 -1
  110. package/dist/structural-rollout-CktnUTCC.js.map +0 -1
  111. package/dist/supervise-Dj6zd2C7.js.map +0 -1
  112. package/dist/util-mCNUeboW.js +0 -419
  113. package/dist/util-mCNUeboW.js.map +0 -1
@@ -1,419 +0,0 @@
1
- //#region src/runtime/util.ts
2
- /**
3
- * Best-effort sandbox delete. Skips instances without a `delete` (test fakes);
4
- * swallows errors (the platform reaps on expiry). Returns `false` when delete
5
- * threw, `true` otherwise, so callers can surface a leak if they choose.
6
- */
7
- async function deleteBoxSafe(box) {
8
- if (!box || typeof box.delete !== "function") return true;
9
- try {
10
- await box.delete();
11
- return true;
12
- } catch {
13
- return false;
14
- }
15
- }
16
- /** Short base36 id for trace correlation. Not cryptographic, not collision-free. */
17
- function randomSuffix(len = 8) {
18
- return Math.random().toString(36).slice(2, 2 + len);
19
- }
20
- /** Collision-resistant id for sandbox naming (find-by-name recovery must be unique). */
21
- function randomUuid() {
22
- return crypto.randomUUID();
23
- }
24
- /** Construct an AbortError. Downstream code pattern-matches on `err.name`. */
25
- function abortError() {
26
- const err = /* @__PURE__ */ new Error("aborted");
27
- err.name = "AbortError";
28
- return err;
29
- }
30
- /** Throw an AbortError. */
31
- function throwAbort() {
32
- throw abortError();
33
- }
34
- /** Throw if the signal is already aborted; otherwise no-op. */
35
- function throwIfAborted(signal) {
36
- if (signal?.aborted) throw abortError();
37
- }
38
- /** True for any error whose `name` is `AbortError` (the cross-kernel abort contract). */
39
- function isAbortError(err) {
40
- return err instanceof Error && err.name === "AbortError";
41
- }
42
- /**
43
- * Sleep that resolves early on abort and always clears its timer so it never
44
- * keeps the event loop alive. Resolves (does not reject) on abort — callers
45
- * re-check the signal explicitly after the sleep.
46
- */
47
- function sleep(ms, signal) {
48
- return new Promise((resolve) => {
49
- if (signal?.aborted) {
50
- resolve();
51
- return;
52
- }
53
- let onAbort;
54
- const timer = setTimeout(() => {
55
- if (onAbort && signal) signal.removeEventListener("abort", onAbort);
56
- resolve();
57
- }, ms);
58
- if (signal) {
59
- onAbort = () => {
60
- clearTimeout(timer);
61
- resolve();
62
- };
63
- signal.addEventListener("abort", onAbort, { once: true });
64
- }
65
- });
66
- }
67
- /**
68
- * Race a promise against a timeout. Resolves with the value if it settles in
69
- * time, otherwise resolves with `undefined`. Always clears the timer.
70
- */
71
- function withTimeout(promise, ms) {
72
- return new Promise((resolve) => {
73
- const timer = setTimeout(() => resolve(void 0), ms);
74
- promise.then((value) => {
75
- clearTimeout(timer);
76
- resolve(value);
77
- }, () => {
78
- clearTimeout(timer);
79
- resolve(void 0);
80
- });
81
- });
82
- }
83
- /**
84
- * `JSON.stringify` with a `String()` fallback on throw (cyclic / non-JSON).
85
- * Strings pass through unstringified so a preview of a string output is the
86
- * string itself, not a quoted re-encoding.
87
- */
88
- function stringifySafe(value, opts = {}) {
89
- let s;
90
- try {
91
- if (typeof value === "string") s = value;
92
- else s = (opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value)) ?? String(value);
93
- } catch {
94
- s = String(value);
95
- }
96
- if (opts.max !== void 0 && s.length > opts.max) return `${s.slice(0, opts.max)}…`;
97
- return s;
98
- }
99
- /** A fresh zero token-usage accumulator. */
100
- function zeroTokenUsage() {
101
- return {
102
- input: 0,
103
- output: 0
104
- };
105
- }
106
- /**
107
- * Sum the catalog-priced part of a dollar total across spends, as a field to spread.
108
- *
109
- * Returns nothing when no input carried one. A fold of pure provider receipts must not gain a
110
- * `usdEstimated: 0`, which would read as "this runtime checked and priced none" on a path that
111
- * never prices at all.
112
- */
113
- function usdEstimatedOf(...spends) {
114
- let total = 0;
115
- let priced = false;
116
- for (const spend of spends) {
117
- if (spend.usdEstimated === void 0) continue;
118
- priced = true;
119
- total += spend.usdEstimated;
120
- }
121
- return priced ? { usdEstimated: total } : {};
122
- }
123
- /** A conserved spend with every channel at zero and no completeness claim on it. */
124
- function zeroSpend() {
125
- return {
126
- iterations: 0,
127
- tokens: zeroTokenUsage(),
128
- usd: 0,
129
- ms: 0
130
- };
131
- }
132
- /**
133
- * The spend of work that HAPPENED and reported no usage receipt.
134
- *
135
- * Not the same value as {@link zeroSpend} even though both carry `{0,0}` tokens and `$0`. A bare
136
- * zero asserts a MEASUREMENT — "this ran and cost nothing" — and every consumer downstream reads it
137
- * that way: the pool keeps reporting `readout().tokensKnown === true`, the journal totals stay
138
- * clean, the OTEL span records a priced zero, and a caller's token-denominated ceiling can never
139
- * fire no matter how much the work really burned. A ceiling that cannot fire is worse than no
140
- * ceiling, because it reads as protection.
141
- *
142
- * `tokensKnown` is the marker the substrate already threads end to end for exactly this case
143
- * (`budget.ts`, `otel-spans.ts`, `spawn-journal.ts`, `supervisor.ts`): the work is recorded, the
144
- * zero is labelled a floor rather than a total, and every rollup that touches it reports its
145
- * balance as a ceiling rather than a measurement. Use this — never a bare zero — whenever a runtime
146
- * cannot see what its worker spent.
147
- *
148
- * The same rule applies to dollars. A dollar-capped run must refuse an executor whose billed spend
149
- * is unknowable; `budgetExempt` does not authorize Runtime to relabel unknown spend as a measured
150
- * zero. Callers that require dollar accounting must use a backend with a trusted billing receipt.
151
- */
152
- function unmeteredSpend(ms) {
153
- return {
154
- iterations: 0,
155
- tokens: zeroTokenUsage(),
156
- tokensKnown: false,
157
- usd: 0,
158
- usdKnown: false,
159
- ms
160
- };
161
- }
162
- /** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */
163
- function cloneSpend(spend) {
164
- return {
165
- iterations: spend.iterations,
166
- tokens: cloneTokenUsage(spend.tokens),
167
- ...spend.tokensKnown === false ? { tokensKnown: false } : {},
168
- usd: spend.usd,
169
- ...spend.usdKnown === false ? { usdKnown: false } : {},
170
- ...spend.usdEstimated !== void 0 ? { usdEstimated: spend.usdEstimated } : {},
171
- ms: spend.ms,
172
- ...boxMinutesOf(spend)
173
- };
174
- }
175
- /**
176
- * Sum two conserved spends per channel. Tokens and dollars never fold into each other, an
177
- * incomplete input keeps the sum incomplete on that channel, and the catalog-priced part of the
178
- * dollar total is summed separately so `usd - usdEstimated` still names what a provider billed.
179
- */
180
- function addSpend(a, b) {
181
- const tokens = cloneTokenUsage(a.tokens);
182
- addTokenUsage(tokens, b.tokens);
183
- return {
184
- iterations: a.iterations + b.iterations,
185
- tokens,
186
- ...a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {},
187
- usd: a.usd + b.usd,
188
- ...a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {},
189
- ...usdEstimatedOf(a, b),
190
- ms: a.ms + b.ms,
191
- ...boxMinutesOf(a, b),
192
- ...tokensProvenanceOf(a, b)
193
- };
194
- }
195
- /**
196
- * Fold the token-provenance channel across spends, as a field to spread.
197
- *
198
- * Returns nothing when no contributor stated one, because ABSENT already means "the executor's own
199
- * live stream", which is what every path reported before a harness store was readable. A
200
- * contributor that stated one and a contributor that did not therefore disagree, and the sum is
201
- * `'mixed'` — the honest answer for a tree whose spend came from two kinds of receipt.
202
- */
203
- function tokensProvenanceOf(...spends) {
204
- let folded;
205
- let sawStated = false;
206
- for (const spend of spends) {
207
- const stated = spend.tokensProvenance ?? "stream-receipt";
208
- if (spend.tokensProvenance !== void 0) sawStated = true;
209
- folded = folded === void 0 || folded === stated ? stated : "mixed";
210
- }
211
- return !sawStated || folded === void 0 || folded === "stream-receipt" ? {} : { tokensProvenance: folded };
212
- }
213
- /**
214
- * Fold the platform box-time channel across spends, as a field to spread.
215
- *
216
- * Returns nothing when no input carried the channel, so a fold over router or cli-bridge work —
217
- * which runs no box at all — never gains a `boxMinutesProvenance: 'uncaptured'` that would claim
218
- * a box ran and went unmetered.
219
- *
220
- * Three rules, one per field:
221
- * - `boxMinutes` sums the numbers that are present, and stays ABSENT when none is. A missing
222
- * measurement never enters the sum as a zero.
223
- * - `boxMinutesKnown` is sticky-false, like `tokensKnown`: one contributor that could not state
224
- * its box time makes the whole sum a floor.
225
- * - `boxMinutesProvenance` degrades. `'observed'` survives only when every contributor that
226
- * carried a number was observed; one derived number makes the sum `'estimated'`; no number at
227
- * all is `'uncaptured'`.
228
- */
229
- function boxMinutesOf(...spends) {
230
- const present = spends.filter((spend) => spend.boxMinutesProvenance !== void 0);
231
- if (present.length === 0) return {};
232
- let minutes = 0;
233
- let sawNumber = false;
234
- let known = true;
235
- let observedOnly = true;
236
- for (const spend of present) {
237
- if (typeof spend.boxMinutes === "number" && Number.isFinite(spend.boxMinutes)) {
238
- minutes += spend.boxMinutes;
239
- sawNumber = true;
240
- if (spend.boxMinutesProvenance !== "observed") observedOnly = false;
241
- }
242
- if (spend.boxMinutesKnown !== true) known = false;
243
- }
244
- return {
245
- ...sawNumber ? { boxMinutes: roundBoxMinutes(minutes) } : {},
246
- boxMinutesKnown: known,
247
- boxMinutesProvenance: sawNumber ? observedOnly ? "observed" : "estimated" : "uncaptured"
248
- };
249
- }
250
- /**
251
- * Box minutes at four decimals — a tenth of a second.
252
- *
253
- * Fine enough that a box alive for two seconds reports `0.0333` instead of a zero that would read
254
- * as a measured free box, and coarse enough that summing floats does not print
255
- * `1.5000000000000002`.
256
- */
257
- function roundBoxMinutes(minutes) {
258
- return Number(minutes.toFixed(4));
259
- }
260
- /** Copy a token subtotal without dropping optional provider cache telemetry. */
261
- function cloneTokenUsage(usage) {
262
- const cacheBreakdownUnknown = usage.cacheBreakdownKnown === false || usage.input > 0 && !hasClassifiedCacheBreakdown(usage);
263
- return {
264
- input: usage.input,
265
- output: usage.output,
266
- ...usage.tokensKnown === false ? { tokensKnown: false } : {},
267
- ...usage.freshInput !== void 0 ? { freshInput: usage.freshInput } : {},
268
- ...usage.cacheRead !== void 0 ? { cacheRead: usage.cacheRead } : {},
269
- ...usage.cacheWrite !== void 0 ? { cacheWrite: usage.cacheWrite } : {},
270
- ...cacheBreakdownUnknown ? { cacheBreakdownKnown: false } : {}
271
- };
272
- }
273
- /** True only when every positive prompt token has a consistent cache classification. */
274
- function hasCompleteCacheBreakdown(usage) {
275
- if (usage.cacheBreakdownKnown === false) return false;
276
- return hasClassifiedCacheBreakdown(usage);
277
- }
278
- function hasClassifiedCacheBreakdown(usage) {
279
- if (usage.input === 0) return true;
280
- if (usage.freshInput === void 0 || usage.cacheRead === void 0 || usage.cacheWrite === void 0) return false;
281
- return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input;
282
- }
283
- /**
284
- * The token charge for one observation: every token counted ONCE, at the moment it first enters
285
- * the context — `input − cacheRead + output`.
286
- *
287
- * `input` is a rolled-up prompt total that re-counts a cached prefix on every turn that reads it,
288
- * so charging `input` makes a 100K prefix read 40 times cost 4.1M for content authored once. A
289
- * cache read is content that was already charged when it was written, so it is the one class the
290
- * charge subtracts. Under a complete split the result is exactly `freshInput + cacheWrite`. No
291
- * price weight is involved: this counts work, and money is a separate channel.
292
- *
293
- * The subtraction form is what makes the charge ADDITIVE. `input` and `cacheRead` both accumulate
294
- * through `addTokenUsage`, so the charge on an aggregate equals the sum of the charges on the
295
- * records that built it — including an aggregate that mixes classified and unclassified turns,
296
- * where the unclassified remainder is charged in full and only the reported cache reads are
297
- * credited. A form that read `freshInput + cacheWrite` directly loses that: one unclassified turn
298
- * would drop the whole aggregate to `input + output` and over-charge every classified turn with it.
299
- *
300
- * The one arithmetic guarantee: a set of classes that does not FIT inside the prompt total it
301
- * partitions credits nothing, so the charge is never below `output` and a class that overflows its
302
- * own total buys no tokens. It is not a guarantee against a provider that reports a cache read it
303
- * never served — that provider can under-report `input` just as easily, and the token channel is an
304
- * accounting unit, not a trust boundary. Prompt tokens the provider left unclassified are charged
305
- * in full, so a spend with no readable split charges an upper bound on newly-presented work rather
306
- * than a measurement, and every caller that enforces a ceiling must report the difference
307
- * (`BudgetPool` does it through `readout().cacheBreakdownKnown`).
308
- */
309
- function chargedTokens(usage) {
310
- return usage.input - creditedCacheRead(usage) + usage.output;
311
- }
312
- /** `cacheRead` if the reported classes fit inside `input`, else nothing. */
313
- function creditedCacheRead(usage) {
314
- const { cacheRead } = usage;
315
- if (cacheRead === void 0) return 0;
316
- return classifiedTotal(usage, cacheRead) > usage.input ? 0 : cacheRead;
317
- }
318
- function classifiedTotal(usage, cacheRead) {
319
- return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0);
320
- }
321
- /**
322
- * Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds
323
- * and `chargedTokens` credits.
324
- *
325
- * The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`
326
- * vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the
327
- * three outcomes are different facts that must not collapse into one another:
328
- *
329
- * - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,
330
- * because a provider that says nothing about caching has not said the split is unknowable.
331
- * - **Read and write both reported, and fitting inside `input`** — a complete partition, so
332
- * `freshInput` is the remainder and the split is known.
333
- * - **One counter reported, or classes that overflow `input`** — the counters that ARE measured
334
- * pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports
335
- * no write) still credits the read it measured, while declaring the rest unclassified so the
336
- * charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a
337
- * partition of a total it exceeds.
338
- *
339
- * A counter the provider did not report stays absent. A zero would claim the provider measured no
340
- * cache, which is a different fact from a provider that did not report.
341
- */
342
- function promptCacheTokenClasses(input, promptCache) {
343
- if (promptCache === void 0) return {};
344
- const read = tokenCount(promptCache.readTokens);
345
- const write = tokenCount(promptCache.writeTokens);
346
- if (read === void 0 && write === void 0) return {};
347
- if (input === void 0 || (read ?? 0) + (write ?? 0) > input) return { cacheBreakdownKnown: false };
348
- if (read !== void 0 && write !== void 0) return {
349
- freshInput: input - read - write,
350
- cacheRead: read,
351
- cacheWrite: write
352
- };
353
- return {
354
- ...read !== void 0 ? { cacheRead: read } : {},
355
- ...write !== void 0 ? { cacheWrite: write } : {},
356
- cacheBreakdownKnown: false
357
- };
358
- }
359
- function tokenCount(value) {
360
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
361
- }
362
- /**
363
- * Add the observed subtotal into `acc`; token and cache incompleteness are sticky.
364
- *
365
- * A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO
366
- * classes. Folding them in would hide the overflow: the accumulator's larger `input` can absorb a
367
- * class total that overflowed the one delta that reported it, and `chargedTokens` would then credit
368
- * at the aggregate a cache read it refuses at the record. That is the one way the charge could come
369
- * out below the sum of the charges on the records that built it.
370
- */
371
- function addTokenUsage(acc, delta) {
372
- acc.input += delta.input ?? 0;
373
- acc.output += delta.output ?? 0;
374
- if (delta.tokensKnown === false) acc.tokensKnown = false;
375
- const input = delta.input ?? 0;
376
- const fits = classifiedTotal(delta, delta.cacheRead ?? 0) <= input;
377
- if (fits) {
378
- if (delta.freshInput !== void 0) acc.freshInput = (acc.freshInput ?? 0) + delta.freshInput;
379
- if (delta.cacheRead !== void 0) acc.cacheRead = (acc.cacheRead ?? 0) + delta.cacheRead;
380
- if (delta.cacheWrite !== void 0) acc.cacheWrite = (acc.cacheWrite ?? 0) + delta.cacheWrite;
381
- }
382
- const classified = fits && delta.freshInput !== void 0 && delta.cacheRead !== void 0 && delta.cacheWrite !== void 0 && delta.freshInput + delta.cacheRead + delta.cacheWrite === input;
383
- if (delta.cacheBreakdownKnown === false || input > 0 && !classified) acc.cacheBreakdownKnown = false;
384
- }
385
- /**
386
- * Map `items` through `fn` with at most `limit` calls in flight at once,
387
- * preserving input order in the result. On the first `fn` rejection no NEW
388
- * items are picked up; already-in-flight calls are awaited, then the first
389
- * error is rethrown. `limit` is clamped to ≥ 1.
390
- *
391
- * Used where a burst of provisioning (e.g. forking N child boxes) must respect
392
- * the loop's concurrency bound instead of firing all N at once.
393
- */
394
- async function mapWithConcurrency(items, limit, fn) {
395
- const bound = Math.max(1, Math.floor(limit));
396
- const results = new Array(items.length);
397
- let next = 0;
398
- let failed = false;
399
- const worker = async () => {
400
- while (!failed) {
401
- const i = next;
402
- next += 1;
403
- if (i >= items.length) return;
404
- try {
405
- results[i] = await fn(items[i], i);
406
- } catch (err) {
407
- failed = true;
408
- throw err;
409
- }
410
- }
411
- };
412
- const workerCount = Math.min(bound, items.length);
413
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
414
- return results;
415
- }
416
- //#endregion
417
- export { throwIfAborted as _, cloneTokenUsage as a, zeroSpend as b, isAbortError as c, randomSuffix as d, randomUuid as f, throwAbort as g, stringifySafe as h, cloneSpend as i, mapWithConcurrency as l, sleep as m, addTokenUsage as n, deleteBoxSafe as o, roundBoxMinutes as p, chargedTokens as r, hasCompleteCacheBreakdown as s, addSpend as t, promptCacheTokenClasses as u, unmeteredSpend as v, zeroTokenUsage as x, withTimeout as y };
418
-
419
- //# sourceMappingURL=util-mCNUeboW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"util-mCNUeboW.js","names":[],"sources":["../src/runtime/util.ts"],"sourcesContent":["/**\n *\n * Internal loop-kernel utilities shared across the kernel, drivers, and the\n * sandbox-acquire layer. Not part of the public barrel surface.\n *\n * @experimental\n */\n\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { Spend, TokenUsageProvenance } from './supervise/types'\nimport type { LoopTokenUsage } from './types'\n\n/**\n * Best-effort sandbox delete. Skips instances without a `delete` (test fakes);\n * swallows errors (the platform reaps on expiry). Returns `false` when delete\n * threw, `true` otherwise, so callers can surface a leak if they choose.\n */\nexport async function deleteBoxSafe(box: SandboxInstance | undefined): Promise<boolean> {\n if (!box || typeof (box as { delete?: unknown }).delete !== 'function') return true\n try {\n await box.delete()\n return true\n } catch {\n return false\n }\n}\n\n/** Short base36 id for trace correlation. Not cryptographic, not collision-free. */\nexport function randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n\n/** Collision-resistant id for sandbox naming (find-by-name recovery must be unique). */\nexport function randomUuid(): string {\n return crypto.randomUUID()\n}\n\n/** Construct an AbortError. Downstream code pattern-matches on `err.name`. */\nexport function abortError(): Error {\n const err = new Error('aborted')\n err.name = 'AbortError'\n return err\n}\n\n/** Throw an AbortError. */\nexport function throwAbort(): never {\n throw abortError()\n}\n\n/** Throw if the signal is already aborted; otherwise no-op. */\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw abortError()\n}\n\n/** True for any error whose `name` is `AbortError` (the cross-kernel abort contract). */\nexport function isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\n/**\n * Sleep that resolves early on abort and always clears its timer so it never\n * keeps the event loop alive. Resolves (does not reject) on abort — callers\n * re-check the signal explicitly after the sleep.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n let onAbort: (() => void) | undefined\n const timer = setTimeout(() => {\n if (onAbort && signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n if (signal) {\n onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n\n/**\n * Race a promise against a timeout. Resolves with the value if it settles in\n * time, otherwise resolves with `undefined`. Always clears the timer.\n */\nexport function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n return new Promise<T | undefined>((resolve) => {\n const timer = setTimeout(() => resolve(undefined), ms)\n promise.then(\n (value) => {\n clearTimeout(timer)\n resolve(value)\n },\n () => {\n clearTimeout(timer)\n resolve(undefined)\n },\n )\n })\n}\n\ninterface StringifyOptions {\n /** Pretty-print with 2-space indent. Default false (compact). */\n pretty?: boolean\n /** Truncate to this many chars, appending `…`. Default unbounded. */\n max?: number\n}\n\n/**\n * `JSON.stringify` with a `String()` fallback on throw (cyclic / non-JSON).\n * Strings pass through unstringified so a preview of a string output is the\n * string itself, not a quoted re-encoding.\n */\nexport function stringifySafe(value: unknown, opts: StringifyOptions = {}): string {\n let s: string\n try {\n if (typeof value === 'string') {\n s = value\n } else {\n const json = opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value)\n s = json ?? String(value)\n }\n } catch {\n s = String(value)\n }\n if (opts.max !== undefined && s.length > opts.max) return `${s.slice(0, opts.max)}…`\n return s\n}\n\n/** A fresh zero token-usage accumulator. */\nexport function zeroTokenUsage(): LoopTokenUsage {\n return { input: 0, output: 0 }\n}\n\n/**\n * Sum the catalog-priced part of a dollar total across spends, as a field to spread.\n *\n * Returns nothing when no input carried one. A fold of pure provider receipts must not gain a\n * `usdEstimated: 0`, which would read as \"this runtime checked and priced none\" on a path that\n * never prices at all.\n */\nexport function usdEstimatedOf(...spends: ReadonlyArray<{ usdEstimated?: number }>): {\n usdEstimated?: number\n} {\n let total = 0\n let priced = false\n for (const spend of spends) {\n if (spend.usdEstimated === undefined) continue\n priced = true\n total += spend.usdEstimated\n }\n return priced ? { usdEstimated: total } : {}\n}\n\n/** A conserved spend with every channel at zero and no completeness claim on it. */\nexport function zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/**\n * The spend of work that HAPPENED and reported no usage receipt.\n *\n * Not the same value as {@link zeroSpend} even though both carry `{0,0}` tokens and `$0`. A bare\n * zero asserts a MEASUREMENT — \"this ran and cost nothing\" — and every consumer downstream reads it\n * that way: the pool keeps reporting `readout().tokensKnown === true`, the journal totals stay\n * clean, the OTEL span records a priced zero, and a caller's token-denominated ceiling can never\n * fire no matter how much the work really burned. A ceiling that cannot fire is worse than no\n * ceiling, because it reads as protection.\n *\n * `tokensKnown` is the marker the substrate already threads end to end for exactly this case\n * (`budget.ts`, `otel-spans.ts`, `spawn-journal.ts`, `supervisor.ts`): the work is recorded, the\n * zero is labelled a floor rather than a total, and every rollup that touches it reports its\n * balance as a ceiling rather than a measurement. Use this — never a bare zero — whenever a runtime\n * cannot see what its worker spent.\n *\n * The same rule applies to dollars. A dollar-capped run must refuse an executor whose billed spend\n * is unknowable; `budgetExempt` does not authorize Runtime to relabel unknown spend as a measured\n * zero. Callers that require dollar accounting must use a backend with a trusted billing receipt.\n */\nexport function unmeteredSpend(ms: number): Spend {\n return {\n iterations: 0,\n tokens: zeroTokenUsage(),\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms,\n }\n}\n\n/** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */\nexport function cloneSpend(spend: Spend): Spend {\n return {\n iterations: spend.iterations,\n tokens: cloneTokenUsage(spend.tokens),\n ...(spend.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: spend.usd,\n ...(spend.usdKnown === false ? { usdKnown: false } : {}),\n ...(spend.usdEstimated !== undefined ? { usdEstimated: spend.usdEstimated } : {}),\n ms: spend.ms,\n ...boxMinutesOf(spend),\n }\n}\n\n/**\n * Sum two conserved spends per channel. Tokens and dollars never fold into each other, an\n * incomplete input keeps the sum incomplete on that channel, and the catalog-priced part of the\n * dollar total is summed separately so `usd - usdEstimated` still names what a provider billed.\n */\nexport function addSpend(a: Spend, b: Spend): Spend {\n const tokens = cloneTokenUsage(a.tokens)\n addTokenUsage(tokens, b.tokens)\n return {\n iterations: a.iterations + b.iterations,\n tokens,\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ...usdEstimatedOf(a, b),\n ms: a.ms + b.ms,\n ...boxMinutesOf(a, b),\n ...tokensProvenanceOf(a, b),\n }\n}\n\n/**\n * Fold the token-provenance channel across spends, as a field to spread.\n *\n * Returns nothing when no contributor stated one, because ABSENT already means \"the executor's own\n * live stream\", which is what every path reported before a harness store was readable. A\n * contributor that stated one and a contributor that did not therefore disagree, and the sum is\n * `'mixed'` — the honest answer for a tree whose spend came from two kinds of receipt.\n */\nfunction tokensProvenanceOf(...spends: ReadonlyArray<Spend>): {\n tokensProvenance?: TokenUsageProvenance\n} {\n let folded: TokenUsageProvenance | undefined\n let sawStated = false\n for (const spend of spends) {\n const stated = spend.tokensProvenance ?? 'stream-receipt'\n if (spend.tokensProvenance !== undefined) sawStated = true\n folded = folded === undefined || folded === stated ? stated : 'mixed'\n }\n return !sawStated || folded === undefined || folded === 'stream-receipt'\n ? {}\n : { tokensProvenance: folded }\n}\n\n/**\n * Fold the platform box-time channel across spends, as a field to spread.\n *\n * Returns nothing when no input carried the channel, so a fold over router or cli-bridge work —\n * which runs no box at all — never gains a `boxMinutesProvenance: 'uncaptured'` that would claim\n * a box ran and went unmetered.\n *\n * Three rules, one per field:\n * - `boxMinutes` sums the numbers that are present, and stays ABSENT when none is. A missing\n * measurement never enters the sum as a zero.\n * - `boxMinutesKnown` is sticky-false, like `tokensKnown`: one contributor that could not state\n * its box time makes the whole sum a floor.\n * - `boxMinutesProvenance` degrades. `'observed'` survives only when every contributor that\n * carried a number was observed; one derived number makes the sum `'estimated'`; no number at\n * all is `'uncaptured'`.\n */\nfunction boxMinutesOf(...spends: ReadonlyArray<Spend>): {\n boxMinutes?: number\n boxMinutesKnown?: boolean\n boxMinutesProvenance?: 'observed' | 'estimated' | 'uncaptured'\n} {\n const present = spends.filter((spend) => spend.boxMinutesProvenance !== undefined)\n if (present.length === 0) return {}\n let minutes = 0\n let sawNumber = false\n let known = true\n let observedOnly = true\n for (const spend of present) {\n if (typeof spend.boxMinutes === 'number' && Number.isFinite(spend.boxMinutes)) {\n minutes += spend.boxMinutes\n sawNumber = true\n if (spend.boxMinutesProvenance !== 'observed') observedOnly = false\n }\n if (spend.boxMinutesKnown !== true) known = false\n }\n return {\n ...(sawNumber ? { boxMinutes: roundBoxMinutes(minutes) } : {}),\n boxMinutesKnown: known,\n boxMinutesProvenance: sawNumber ? (observedOnly ? 'observed' : 'estimated') : 'uncaptured',\n }\n}\n\n/**\n * Box minutes at four decimals — a tenth of a second.\n *\n * Fine enough that a box alive for two seconds reports `0.0333` instead of a zero that would read\n * as a measured free box, and coarse enough that summing floats does not print\n * `1.5000000000000002`.\n */\nexport function roundBoxMinutes(minutes: number): number {\n return Number(minutes.toFixed(4))\n}\n\n/** Copy a token subtotal without dropping optional provider cache telemetry. */\nexport function cloneTokenUsage(usage: LoopTokenUsage): LoopTokenUsage {\n const cacheBreakdownUnknown =\n usage.cacheBreakdownKnown === false || (usage.input > 0 && !hasClassifiedCacheBreakdown(usage))\n return {\n input: usage.input,\n output: usage.output,\n ...(usage.tokensKnown === false ? { tokensKnown: false as const } : {}),\n ...(usage.freshInput !== undefined ? { freshInput: usage.freshInput } : {}),\n ...(usage.cacheRead !== undefined ? { cacheRead: usage.cacheRead } : {}),\n ...(usage.cacheWrite !== undefined ? { cacheWrite: usage.cacheWrite } : {}),\n ...(cacheBreakdownUnknown ? { cacheBreakdownKnown: false as const } : {}),\n }\n}\n\n/** True only when every positive prompt token has a consistent cache classification. */\nexport function hasCompleteCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.cacheBreakdownKnown === false) return false\n return hasClassifiedCacheBreakdown(usage)\n}\n\nfunction hasClassifiedCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.input === 0) return true\n if (\n usage.freshInput === undefined ||\n usage.cacheRead === undefined ||\n usage.cacheWrite === undefined\n ) {\n return false\n }\n return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input\n}\n\n/**\n * The token charge for one observation: every token counted ONCE, at the moment it first enters\n * the context — `input − cacheRead + output`.\n *\n * `input` is a rolled-up prompt total that re-counts a cached prefix on every turn that reads it,\n * so charging `input` makes a 100K prefix read 40 times cost 4.1M for content authored once. A\n * cache read is content that was already charged when it was written, so it is the one class the\n * charge subtracts. Under a complete split the result is exactly `freshInput + cacheWrite`. No\n * price weight is involved: this counts work, and money is a separate channel.\n *\n * The subtraction form is what makes the charge ADDITIVE. `input` and `cacheRead` both accumulate\n * through `addTokenUsage`, so the charge on an aggregate equals the sum of the charges on the\n * records that built it — including an aggregate that mixes classified and unclassified turns,\n * where the unclassified remainder is charged in full and only the reported cache reads are\n * credited. A form that read `freshInput + cacheWrite` directly loses that: one unclassified turn\n * would drop the whole aggregate to `input + output` and over-charge every classified turn with it.\n *\n * The one arithmetic guarantee: a set of classes that does not FIT inside the prompt total it\n * partitions credits nothing, so the charge is never below `output` and a class that overflows its\n * own total buys no tokens. It is not a guarantee against a provider that reports a cache read it\n * never served — that provider can under-report `input` just as easily, and the token channel is an\n * accounting unit, not a trust boundary. Prompt tokens the provider left unclassified are charged\n * in full, so a spend with no readable split charges an upper bound on newly-presented work rather\n * than a measurement, and every caller that enforces a ceiling must report the difference\n * (`BudgetPool` does it through `readout().cacheBreakdownKnown`).\n */\nexport function chargedTokens(usage: LoopTokenUsage): number {\n return usage.input - creditedCacheRead(usage) + usage.output\n}\n\n/** `cacheRead` if the reported classes fit inside `input`, else nothing. */\nfunction creditedCacheRead(usage: LoopTokenUsage): number {\n const { cacheRead } = usage\n if (cacheRead === undefined) return 0\n return classifiedTotal(usage, cacheRead) > usage.input ? 0 : cacheRead\n}\n\nfunction classifiedTotal(usage: Partial<LoopTokenUsage>, cacheRead: number): number {\n return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0)\n}\n\n/**\n * The only two members this reads out of a provider prompt-cache report, named rather than taken as\n * an open record: both the typed `PromptCacheUsage` and the open `promptCache` an `llm_call` carries\n * satisfy it, and each value is validated before it is credited.\n */\nexport interface PromptCacheCounters {\n readonly readTokens?: unknown\n readonly writeTokens?: unknown\n}\n\n/** The prompt-cache token classes of one observation, as `LoopTokenUsage` members. */\nexport type PromptCacheTokenClasses = Pick<\n LoopTokenUsage,\n 'freshInput' | 'cacheRead' | 'cacheWrite' | 'cacheBreakdownKnown'\n>\n\n/**\n * Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds\n * and `chargedTokens` credits.\n *\n * The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`\n * vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the\n * three outcomes are different facts that must not collapse into one another:\n *\n * - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,\n * because a provider that says nothing about caching has not said the split is unknowable.\n * - **Read and write both reported, and fitting inside `input`** — a complete partition, so\n * `freshInput` is the remainder and the split is known.\n * - **One counter reported, or classes that overflow `input`** — the counters that ARE measured\n * pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports\n * no write) still credits the read it measured, while declaring the rest unclassified so the\n * charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a\n * partition of a total it exceeds.\n *\n * A counter the provider did not report stays absent. A zero would claim the provider measured no\n * cache, which is a different fact from a provider that did not report.\n */\nexport function promptCacheTokenClasses(\n input: number | undefined,\n promptCache: PromptCacheCounters | undefined,\n): PromptCacheTokenClasses {\n if (promptCache === undefined) return {}\n const read = tokenCount(promptCache.readTokens)\n const write = tokenCount(promptCache.writeTokens)\n if (read === undefined && write === undefined) return {}\n if (input === undefined || (read ?? 0) + (write ?? 0) > input) {\n return { cacheBreakdownKnown: false }\n }\n if (read !== undefined && write !== undefined) {\n return { freshInput: input - read - write, cacheRead: read, cacheWrite: write }\n }\n return {\n ...(read !== undefined ? { cacheRead: read } : {}),\n ...(write !== undefined ? { cacheWrite: write } : {}),\n cacheBreakdownKnown: false,\n }\n}\n\nfunction tokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\n/**\n * Add the observed subtotal into `acc`; token and cache incompleteness are sticky.\n *\n * A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO\n * classes. Folding them in would hide the overflow: the accumulator's larger `input` can absorb a\n * class total that overflowed the one delta that reported it, and `chargedTokens` would then credit\n * at the aggregate a cache read it refuses at the record. That is the one way the charge could come\n * out below the sum of the charges on the records that built it.\n */\nexport function addTokenUsage(acc: LoopTokenUsage, delta: Partial<LoopTokenUsage>): void {\n acc.input += delta.input ?? 0\n acc.output += delta.output ?? 0\n if (delta.tokensKnown === false) acc.tokensKnown = false\n\n const input = delta.input ?? 0\n const fits = classifiedTotal(delta, delta.cacheRead ?? 0) <= input\n if (fits) {\n if (delta.freshInput !== undefined) acc.freshInput = (acc.freshInput ?? 0) + delta.freshInput\n if (delta.cacheRead !== undefined) acc.cacheRead = (acc.cacheRead ?? 0) + delta.cacheRead\n if (delta.cacheWrite !== undefined) acc.cacheWrite = (acc.cacheWrite ?? 0) + delta.cacheWrite\n }\n\n const classified =\n fits &&\n delta.freshInput !== undefined &&\n delta.cacheRead !== undefined &&\n delta.cacheWrite !== undefined &&\n delta.freshInput + delta.cacheRead + delta.cacheWrite === input\n // A provider that reports prompt input without all three classes leaves the\n // split unknown. Do not let an earlier complete turn make the aggregate look\n // complete after a later unclassified positive-input turn.\n if (delta.cacheBreakdownKnown === false || (input > 0 && !classified)) {\n acc.cacheBreakdownKnown = false\n }\n}\n\n/**\n * Map `items` through `fn` with at most `limit` calls in flight at once,\n * preserving input order in the result. On the first `fn` rejection no NEW\n * items are picked up; already-in-flight calls are awaited, then the first\n * error is rethrown. `limit` is clamped to ≥ 1.\n *\n * Used where a burst of provisioning (e.g. forking N child boxes) must respect\n * the loop's concurrency bound instead of firing all N at once.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const bound = Math.max(1, Math.floor(limit))\n const results = new Array<R>(items.length)\n let next = 0\n let failed = false\n const worker = async (): Promise<void> => {\n while (!failed) {\n const i = next\n next += 1\n if (i >= items.length) return\n try {\n results[i] = await fn(items[i] as T, i)\n } catch (err) {\n failed = true\n throw err\n }\n }\n }\n const workerCount = Math.min(bound, items.length)\n await Promise.all(Array.from({ length: workerCount }, () => worker()))\n return results\n}\n"],"mappings":";;;;;;AAiBA,eAAsB,cAAc,KAAoD;CACtF,IAAI,CAAC,OAAO,OAAQ,IAA6B,WAAW,YAAY,OAAO;CAC/E,IAAI;EACF,MAAM,IAAI,OAAO;EACjB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,SAAgB,aAAa,MAAM,GAAW;CAC5C,OAAO,KAAK,OAAO,CAAC,CACjB,SAAS,EAAE,CAAC,CACZ,MAAM,GAAG,IAAI,GAAG;AACrB;;AAGA,SAAgB,aAAqB;CACnC,OAAO,OAAO,WAAW;AAC3B;;AAGA,SAAgB,aAAoB;CAClC,MAAM,sBAAM,IAAI,MAAM,SAAS;CAC/B,IAAI,OAAO;CACX,OAAO;AACT;;AAGA,SAAgB,aAAoB;CAClC,MAAM,WAAW;AACnB;;AAGA,SAAgB,eAAe,QAAuC;CACpE,IAAI,QAAQ,SA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