@tangle-network/agent-runtime 7.0.0 → 8.0.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.
- package/CHANGELOG.md +68 -0
- package/README.md +0 -3
- package/dist/{activation-Ba9IAgQ3.js → activation-Ce4zUcu8.js} +4 -4
- package/dist/{activation-Ba9IAgQ3.js.map → activation-Ce4zUcu8.js.map} +1 -1
- package/dist/{activation-DIkTEBWF.d.ts → activation-xxvLF1-1.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{bundle-Cy5igJdv.js → bundle-CcpL2lfr.js} +2 -2
- package/dist/{bundle-Cy5igJdv.js.map → bundle-CcpL2lfr.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/continuation-CIyKnS1Q.js +451 -0
- package/dist/continuation-CIyKnS1Q.js.map +1 -0
- package/dist/{coordination-manager-DQZ2u6L-.js → coordination-manager-sa_PkISw.js} +194 -148
- package/dist/coordination-manager-sa_PkISw.js.map +1 -0
- package/dist/{coordination-map-routing-CKRNZSaV.js → coordination-map-routing-XZXTlCmn.js} +2 -4
- package/dist/coordination-map-routing-XZXTlCmn.js.map +1 -0
- package/dist/{delegate-DFLSVjFG.js → delegate-DhTkJIta.js} +3 -3
- package/dist/{delegate-DFLSVjFG.js.map → delegate-DhTkJIta.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +13 -12
- package/dist/durable.js.map +1 -1
- package/dist/{errors-AzSuGI23.js → errors-DG8yufqX.js} +8 -1
- package/dist/errors-DG8yufqX.js.map +1 -0
- package/dist/{failure-cause-rJTm_Tx8.js → failure-cause-CVB-YE88.js} +12 -8
- package/dist/{failure-cause-rJTm_Tx8.js.map → failure-cause-CVB-YE88.js.map} +1 -1
- package/dist/{graph-registry-7X2nrreR.js → graph-registry-czAwYwNj.js} +133 -9
- package/dist/graph-registry-czAwYwNj.js.map +1 -0
- package/dist/{graph-registry-gYbq4L5Z.js → graph-registry-uTIyyy7A.js} +1 -1
- package/dist/graph-tSIT_eWK.js +1793 -0
- package/dist/graph-tSIT_eWK.js.map +1 -0
- package/dist/{improve-BolbYegO.js → improve-H08hiIw9.js} +19 -48
- package/dist/improve-H08hiIw9.js.map +1 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +16 -16
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +8 -8
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +16 -15
- package/dist/{loop-runner-Cs9IJ6Nk.d.ts → loop-runner-BGwhcn1p.d.ts} +2 -2
- package/dist/{loop-runner-C9W3T_3T.js → loop-runner-ChqK8kSz.js} +3 -3
- package/dist/{loop-runner-C9W3T_3T.js.map → loop-runner-ChqK8kSz.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +7 -5
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +9 -9
- package/dist/mcp/memory-bin.js +2 -2
- package/dist/{model-policy-JOcg3NRs.js → model-policy-yxOrDTTj.js} +9 -9
- package/dist/model-policy-yxOrDTTj.js.map +1 -0
- package/dist/{prepare-Dtfk_Wi_.js → prepare-BnF8nGIg.js} +4 -4
- package/dist/{prepare-Dtfk_Wi_.js.map → prepare-BnF8nGIg.js.map} +1 -1
- package/dist/{profile-CNSQjOes.js → profile-CD25rTJF.js} +4 -4
- package/dist/{profile-CNSQjOes.js.map → profile-CD25rTJF.js.map} +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.js +2 -2
- package/dist/{provision-supervisor-BQFHjCtN.js → provision-supervisor-Dx4TXTMM.js} +8 -8
- package/dist/{provision-supervisor-BQFHjCtN.js.map → provision-supervisor-Dx4TXTMM.js.map} +1 -1
- package/dist/{run-cancellation-B84X8ZAP.js → run-cancellation-DYszFJtQ.js} +4 -4
- package/dist/{run-cancellation-B84X8ZAP.js.map → run-cancellation-DYszFJtQ.js.map} +1 -1
- package/dist/{run-state-Dh1bGERI.js → run-state-DHBoJjaF.js} +5 -5
- package/dist/{run-state-Dh1bGERI.js.map → run-state-DHBoJjaF.js.map} +1 -1
- package/dist/{runtime-C9F1PG2A.js → runtime-CaM5Gbbv.js} +76 -987
- package/dist/runtime-CaM5Gbbv.js.map +1 -0
- package/dist/{sandbox-profile-compat-oFGWESLn.js → sandbox-profile-compat-l-SLQnGb.js} +2 -2
- package/dist/{sandbox-profile-compat-oFGWESLn.js.map → sandbox-profile-compat-l-SLQnGb.js.map} +1 -1
- package/dist/{search-executor-CKR9_6NR.js → search-executor-B9L8W_1O.js} +17 -46
- package/dist/search-executor-B9L8W_1O.js.map +1 -0
- package/dist/{server-Dh3SQGQT.js → server-BlDV8sj_.js} +32 -8
- package/dist/{server-Dh3SQGQT.js.map → server-BlDV8sj_.js.map} +1 -1
- package/dist/{settle-record-C6LdVvok.js → settle-record-WWQasnDq.js} +2 -2
- package/dist/{settle-record-C6LdVvok.js.map → settle-record-WWQasnDq.js.map} +1 -1
- package/dist/{snapshot-Cgj2Wzi6.js → snapshot-BKI_w3JD.js} +19 -5
- package/dist/snapshot-BKI_w3JD.js.map +1 -0
- package/dist/{structural-rollout-Dapf2aZY.js → structural-rollout-C1xxoWcN.js} +18 -54
- package/dist/structural-rollout-C1xxoWcN.js.map +1 -0
- package/dist/{supervise-xwl2D6q3.js → supervise-DWiSgPLB.js} +101 -111
- package/dist/supervise-DWiSgPLB.js.map +1 -0
- package/dist/{supervision-discovery-B47U8TH5.js → supervision-discovery-C9kfBLKy.js} +4 -4
- package/dist/{supervision-discovery-B47U8TH5.js.map → supervision-discovery-C9kfBLKy.js.map} +1 -1
- package/dist/{supervisor-gC-u_PRk.js → supervisor-Dpeu7rnZ.js} +206 -693
- package/dist/supervisor-Dpeu7rnZ.js.map +1 -0
- package/dist/{supervisor-accounting-DxLQ_TQe.js → supervisor-accounting-Bw4MJk-b.js} +434 -423
- package/dist/supervisor-accounting-Bw4MJk-b.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +13 -13
- package/dist/{tool-server-Dg350Bgz.js → tool-server-DYwRbi0I.js} +3 -3
- package/dist/{tool-server-Dg350Bgz.js.map → tool-server-DYwRbi0I.js.map} +1 -1
- package/dist/{top-web-BJLnFQdr.js → top-web-B3HOAtrZ.js} +9 -7
- package/dist/{top-web-BJLnFQdr.js.map → top-web-B3HOAtrZ.js.map} +1 -1
- package/dist/tui/bin.js +3 -3
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +2 -2
- package/dist/{types-Jg274chm.d.ts → types-C_qbnw9N.d.ts} +1335 -1413
- package/dist/{util-C_cdPNC4.js → util-fcckrkKp.js} +39 -113
- package/dist/util-fcckrkKp.js.map +1 -0
- package/dist/{workspace-streams-B7yNMahl.js → workspace-streams-DA9R3j-p.js} +2 -2
- package/dist/{workspace-streams-B7yNMahl.js.map → workspace-streams-DA9R3j-p.js.map} +1 -1
- package/package.json +1 -1
- package/dist/coordination-manager-DQZ2u6L-.js.map +0 -1
- package/dist/coordination-map-routing-CKRNZSaV.js.map +0 -1
- package/dist/errors-AzSuGI23.js.map +0 -1
- package/dist/graph-BjQF2syl.js +0 -579
- package/dist/graph-BjQF2syl.js.map +0 -1
- package/dist/graph-registry-7X2nrreR.js.map +0 -1
- package/dist/improve-BolbYegO.js.map +0 -1
- package/dist/model-policy-JOcg3NRs.js.map +0 -1
- package/dist/runtime-C9F1PG2A.js.map +0 -1
- package/dist/search-executor-CKR9_6NR.js.map +0 -1
- package/dist/snapshot-Cgj2Wzi6.js.map +0 -1
- package/dist/structural-rollout-Dapf2aZY.js.map +0 -1
- package/dist/supervise-xwl2D6q3.js.map +0 -1
- package/dist/supervisor-accounting-DxLQ_TQe.js.map +0 -1
- package/dist/supervisor-gC-u_PRk.js.map +0 -1
- package/dist/util-C_cdPNC4.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { m as ValidationError } from "./errors-
|
|
1
|
+
import { m as ValidationError } from "./errors-DG8yufqX.js";
|
|
2
2
|
import { t as runTaskQueue } from "./task-queue-DbpZAp6C.js";
|
|
3
3
|
// src/runtime/supervise/deadline.ts
|
|
4
4
|
const MAX_TIMER_DELAY_MS = 2147483647;
|
|
@@ -315,26 +315,8 @@ function zeroSpend() {
|
|
|
315
315
|
ms: 0
|
|
316
316
|
};
|
|
317
317
|
}
|
|
318
|
-
/**
|
|
319
|
-
*
|
|
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
|
-
*/
|
|
318
|
+
/** Work that happened and reported no receipt. Unlike {@link zeroSpend}, `tokensKnown: false` makes
|
|
319
|
+
* the zero a floor, so a token or dollar ceiling still fires. Never relabel that as a measurement. */
|
|
338
320
|
function unmeteredSpend(ms) {
|
|
339
321
|
return {
|
|
340
322
|
iterations: 0,
|
|
@@ -357,7 +339,8 @@ function cloneSpend(spend) {
|
|
|
357
339
|
...spend.usdEstimated !== void 0 ? { usdEstimated: spend.usdEstimated } : {},
|
|
358
340
|
ms: spend.ms,
|
|
359
341
|
...boxMinutesOf(spend),
|
|
360
|
-
...spend.tokensProvenance === void 0 ? {} : { tokensProvenance: spend.tokensProvenance }
|
|
342
|
+
...spend.tokensProvenance === void 0 ? {} : { tokensProvenance: spend.tokensProvenance },
|
|
343
|
+
...streamBreakOf(spend)
|
|
361
344
|
};
|
|
362
345
|
}
|
|
363
346
|
/**
|
|
@@ -378,17 +361,11 @@ function addSpend(a, b) {
|
|
|
378
361
|
...usdEstimatedOf(a, b),
|
|
379
362
|
ms: a.ms + b.ms,
|
|
380
363
|
...boxMinutesOf(a, b),
|
|
381
|
-
...tokensProvenanceOf(a, b)
|
|
364
|
+
...tokensProvenanceOf(a, b),
|
|
365
|
+
...streamBreakOf(a, b)
|
|
382
366
|
};
|
|
383
367
|
}
|
|
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
|
-
*/
|
|
368
|
+
/** Absent provenance is the live stream. A stated source beside an absent one folds to `mixed`. */
|
|
392
369
|
function tokensProvenanceOf(...spends) {
|
|
393
370
|
let folded;
|
|
394
371
|
let sawStated = false;
|
|
@@ -399,22 +376,27 @@ function tokensProvenanceOf(...spends) {
|
|
|
399
376
|
}
|
|
400
377
|
return !sawStated || folded === void 0 || folded === "stream-receipt" ? {} : { tokensProvenance: folded };
|
|
401
378
|
}
|
|
402
|
-
/**
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
379
|
+
/** Fold a broken stream's split. A spend that never broke contributes nothing, not a zero. */
|
|
380
|
+
function streamBreakOf(...spends) {
|
|
381
|
+
const streamedTokens = foldTokenSplit(spends.map((spend) => spend.streamedTokens));
|
|
382
|
+
const unobservedTokens = foldTokenSplit(spends.map((spend) => spend.unobservedTokens));
|
|
383
|
+
const iterationsKnown = spends.some((spend) => spend.iterationsKnown === false) ? false : void 0;
|
|
384
|
+
return {
|
|
385
|
+
...streamedTokens === void 0 ? {} : { streamedTokens },
|
|
386
|
+
...unobservedTokens === void 0 ? {} : { unobservedTokens },
|
|
387
|
+
...iterationsKnown === void 0 ? {} : { iterationsKnown }
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
function foldTokenSplit(parts) {
|
|
391
|
+
const present = parts.filter((part) => part !== void 0);
|
|
392
|
+
const first = present[0];
|
|
393
|
+
if (first === void 0) return void 0;
|
|
394
|
+
const total = cloneTokenUsage(first);
|
|
395
|
+
for (const part of present.slice(1)) addTokenUsage(total, part);
|
|
396
|
+
return total;
|
|
397
|
+
}
|
|
398
|
+
/** Sum present box minutes. Absence is not zero, so a path with no box stays unmarked.
|
|
399
|
+
* `boxMinutesKnown` is sticky-false. Provenance degrades from observed to estimated to uncaptured. */
|
|
418
400
|
function boxMinutesOf(...spends) {
|
|
419
401
|
const present = spends.filter((spend) => spend.boxMinutesProvenance !== void 0);
|
|
420
402
|
if (present.length === 0) return {};
|
|
@@ -469,32 +451,9 @@ function hasClassifiedCacheBreakdown(usage) {
|
|
|
469
451
|
if (usage.freshInput === void 0 || usage.cacheRead === void 0 || usage.cacheWrite === void 0) return false;
|
|
470
452
|
return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input;
|
|
471
453
|
}
|
|
472
|
-
/**
|
|
473
|
-
*
|
|
474
|
-
*
|
|
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
|
-
*/
|
|
454
|
+
/** Charge `input - cacheRead + output`. A cache read was charged when written. Classes that do not
|
|
455
|
+
* fit `input` credit nothing. Unclassified prompt tokens charge in full. Do not charge
|
|
456
|
+
* `freshInput + cacheWrite`: one unclassified turn would then over-charge the classified ones. */
|
|
498
457
|
function chargedTokens(usage) {
|
|
499
458
|
return usage.input - creditedCacheRead(usage) + usage.output;
|
|
500
459
|
}
|
|
@@ -507,27 +466,9 @@ function creditedCacheRead(usage) {
|
|
|
507
466
|
function classifiedTotal(usage, cacheRead) {
|
|
508
467
|
return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0);
|
|
509
468
|
}
|
|
510
|
-
/**
|
|
511
|
-
*
|
|
512
|
-
*
|
|
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
|
-
*/
|
|
469
|
+
/** Nothing reported stays unmarked. A read and a write that fit `input` are a complete split.
|
|
470
|
+
* One counter, or classes past `input`, pass through with `cacheBreakdownKnown: false`.
|
|
471
|
+
* An unreported counter stays absent, never zero. */
|
|
531
472
|
function promptCacheTokenClasses(input, promptCache) {
|
|
532
473
|
if (promptCache === void 0) return {};
|
|
533
474
|
const read = tokenCount(promptCache.readTokens);
|
|
@@ -548,15 +489,8 @@ function promptCacheTokenClasses(input, promptCache) {
|
|
|
548
489
|
function tokenCount(value) {
|
|
549
490
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
550
491
|
}
|
|
551
|
-
/**
|
|
552
|
-
*
|
|
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
|
-
*/
|
|
492
|
+
/** Add a subtotal. Classes that overflow their own `input` are dropped, so a later fold cannot
|
|
493
|
+
* credit a cache read this record refused. An unclassified positive input makes the sum unknown. */
|
|
560
494
|
function addTokenUsage(acc, delta) {
|
|
561
495
|
acc.input += delta.input ?? 0;
|
|
562
496
|
acc.output += delta.output ?? 0;
|
|
@@ -571,15 +505,7 @@ function addTokenUsage(acc, delta) {
|
|
|
571
505
|
const classified = fits && delta.freshInput !== void 0 && delta.cacheRead !== void 0 && delta.cacheWrite !== void 0 && delta.freshInput + delta.cacheRead + delta.cacheWrite === input;
|
|
572
506
|
if (delta.cacheBreakdownKnown === false || input > 0 && !classified) acc.cacheBreakdownKnown = false;
|
|
573
507
|
}
|
|
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
|
-
*/
|
|
508
|
+
/** Run `fn` with at most `limit` calls in flight, preserving input order. The first rejection wins. */
|
|
583
509
|
async function mapWithConcurrency(items, limit, fn) {
|
|
584
510
|
const results = new Array(items.length);
|
|
585
511
|
let next = 0;
|
|
@@ -650,4 +576,4 @@ function unreportedSpend(total, prior) {
|
|
|
650
576
|
}
|
|
651
577
|
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
578
|
|
|
653
|
-
//# sourceMappingURL=util-
|
|
579
|
+
//# sourceMappingURL=util-fcckrkKp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util-fcckrkKp.js","names":[],"sources":["../src/runtime/supervise/deadline.ts","../src/runtime/supervise/resources.ts","../src/runtime/util.ts"],"sourcesContent":["import { ValidationError } from '../../errors'\nimport type { Executor } from './types'\n\n// Node clamps larger delays to 1 ms instead of waiting, so long budgets must be armed in chunks.\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\n\nexport const DEFAULT_SUCCESSFUL_SHUTDOWN_MS = 5_000\n\n/** The abort reason a child's own deadline carries. */\nexport const CHILD_DEADLINE_REASON = 'child deadline exceeded'\n/** The abort reason the root's budget deadline cascades to every node. */\nexport const ROOT_DEADLINE_REASON = 'root budget deadline exceeded'\n\n/**\n * What a steerable child's own time box does: a check-in, not a kill. At the child's deadline its\n * lead's scope delivers `DEADLINE_CHECK_IN_MESSAGE` to the child's inbox and keeps it\n * running; the child is stopped (reason `child deadline exceeded`) only once it then makes no\n * progress for `idleMs`. The run's own deadline, the budgets and cancellation still stop it at once.\n * `false` restores the hard kill at the time box. A child that exposes no inbox cannot be told,\n * so it is stopped at its time box as before.\n *\n * Four of 42 directors\n * were killed at the 90-minute boxes their root set, three of them mid-turn, losing 27, 6 and 91\n * minutes since their last recorded page, and each successor spent 12 to 19 minutes re-reading\n * before its first page.\n */\nexport type DeadlineCheckIn = false | { readonly idleMs?: number }\n\n/** How long a checked-in child may go without progress before it is stopped: 30 min. */\nexport const DEFAULT_CHECK_IN_IDLE_MS = 30 * 60_000\n\n/** The check-in a child receives at its own time box. */\nexport const DEADLINE_CHECK_IN_MESSAGE =\n 'Check-in: your time box has ended. This is not a stop. Finish the step you are on and start ' +\n 'nothing new. Record your current state and every result you have not recorded yet, then call ' +\n 'submit_result with what you have now; if the work is not done, mark it incomplete and name ' +\n 'what remains. Your lead decides whether to continue you or hand the work on. You keep running ' +\n 'while you make progress.'\n\n/** The idle bound a check-in policy sets, or undefined when time boxes are hard kills. */\nexport function checkInIdleMs(policy: DeadlineCheckIn | undefined): number | undefined {\n if (policy === false) return undefined\n const idleMs = policy?.idleMs ?? DEFAULT_CHECK_IN_IDLE_MS\n if (!Number.isSafeInteger(idleMs) || idleMs <= 0) {\n throw new ValidationError(\n 'deadlineCheckIn.idleMs must be a positive safe integer of milliseconds',\n )\n }\n return idleMs\n}\n\n/** How long a manager whose result was accepted has to end the turn that submitted it before an\n * abort, or Runtime's cancel of its retained run, stops its harness: the turn's end meters its\n * usage and commits its result; its workspace capture runs after, in the manager's owner. */\nexport const ACCEPTED_RESULT_GRACE_MS = 5 * 60_000\n\n/** Whether an abort reason is a deadline: the child's own or the root budget's. */\nexport function isDeadlineAbortReason(reason: unknown): boolean {\n return reason === CHILD_DEADLINE_REASON || reason === ROOT_DEADLINE_REASON\n}\nconst TEARDOWN_ACKNOWLEDGEMENT_MS = 250\n\n/** Arm a finite wall-clock deadline in safe chunks. Resource deadlines unref by default;\n * a standalone wait opts into keeping the process alive until it settles or is cancelled. */\nexport function armDeadlineTimer(\n delayMs: number,\n onDeadline: () => void,\n keepAlive = false,\n): () => void {\n const deadlineAtMs = Date.now() + Math.max(0, delayMs)\n if (!Number.isFinite(delayMs) || !Number.isSafeInteger(Math.ceil(deadlineAtMs))) {\n throw new ValidationError('timer delay must produce a finite safe deadline')\n }\n let cleared = false\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const arm = (): void => {\n if (cleared) return\n const remainingMs = Math.max(0, deadlineAtMs - Date.now())\n timer = setTimeout(\n () => {\n if (cleared) return\n if (Date.now() >= deadlineAtMs) onDeadline()\n else arm()\n },\n Math.min(remainingMs, MAX_TIMER_DELAY_MS),\n )\n if (!keepAlive && typeof timer.unref === 'function') timer.unref()\n }\n\n arm()\n return () => {\n cleared = true\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n\n/**\n * Resolve a spawned child's duration into one absolute cutoff. An omitted child deadline inherits\n * the parent cutoff; an explicit child duration may shorten, but never extend, that cutoff.\n */\nexport function boundedChildDeadlineAt(\n parentDeadlineAtMs: number,\n childDeadlineMs: number | undefined,\n nowMs: number,\n): number | undefined {\n const parent = parentDeadlineAtMs > 0 ? parentDeadlineAtMs : undefined\n const child = childDeadlineMs === undefined ? undefined : nowMs + childDeadlineMs\n if (parent === undefined) return child\n if (child === undefined) return parent\n return Math.min(parent, child)\n}\n\n/** One answer from `Executor.teardown`. */\nexport type TeardownAnswer = Awaited<ReturnType<Executor<unknown>['teardown']>>\n\n/** Invoke teardown once and bound how long the runtime waits for its acknowledgement. A hard\n * execution deadline always wins; without one, numeric grace gets a short acknowledgement\n * allowance and a brutal kill gets only that allowance. Explicit `infinity` remains unbounded\n * only when no execution deadline exists. The losing promise stays observed. `ask` issues the\n * request; a scope passes its per-child single-flight asker (see `singleFlightTeardown`). */\nexport async function teardownExecutor<Out>(\n executor: Executor<Out>,\n grace: number | 'brutalKill' | 'infinity',\n deadlineAtMs: number | undefined,\n now: () => number,\n ask: (grace: number | 'brutalKill' | 'infinity') => Promise<TeardownAnswer> = (requested) =>\n Promise.resolve(executor.teardown(requested)),\n): Promise<void> {\n const work = Promise.resolve(ask(grace))\n\n const requestedWaitMs =\n grace === 'infinity'\n ? undefined\n : grace === 'brutalKill'\n ? (executor.teardownTimeoutMs ?? TEARDOWN_ACKNOWLEDGEMENT_MS)\n : grace + TEARDOWN_ACKNOWLEDGEMENT_MS\n // The execution cutoff stops new work; cleanup still gets a small, bounded acknowledgement\n // window after that cutoff. Otherwise an already-resolved brutal kill invoked exactly at the\n // deadline would be mislabeled as a cleanup failure without receiving one microtask.\n const deadlineWaitMs =\n deadlineAtMs === undefined\n ? undefined\n : Math.max(0, deadlineAtMs - now()) + TEARDOWN_ACKNOWLEDGEMENT_MS\n const waitMs =\n requestedWaitMs === undefined\n ? deadlineWaitMs\n : deadlineWaitMs === undefined\n ? requestedWaitMs\n : Math.min(requestedWaitMs, deadlineWaitMs)\n\n let receipt: TeardownAnswer\n if (waitMs === undefined) {\n receipt = await work\n } else if (waitMs <= 0) {\n void work.catch(() => undefined)\n throw new ValidationError('executor teardown did not acknowledge before its deadline')\n } else {\n let clearTimer: (() => void) | undefined\n const timedOut = new Promise<never>((_resolve, reject) => {\n clearTimer = armDeadlineTimer(\n waitMs,\n () =>\n reject(new ValidationError(`executor teardown did not acknowledge within ${waitMs}ms`)),\n true,\n )\n })\n try {\n receipt = await Promise.race([work, timedOut])\n } finally {\n clearTimer?.()\n }\n }\n\n if (!receipt.destroyed) {\n throw new ValidationError(\n `executor teardown reported destroyed=false${receipt.detail ? `: ${receipt.detail}` : ''}`,\n )\n }\n}\n\n/**\n * The optional teardown surfaces a wrapping executor forwards, so wrapping never changes how a\n * child is released: the acknowledgement window a remote teardown needs, the release of a\n * retained execution at root settlement, and the environments an unconfirmed teardown names for\n * a sweeper. A wrapper that dropped `releaseRetained` left every retained child it wrapped\n * running after settlement. Each surface is present only when the inner executor implements it.\n */\nexport function teardownSurfaces(\n inner: Executor<unknown>,\n): Pick<\n Executor<unknown>,\n 'teardownTimeoutMs' | 'releaseRetained' | 'heldEnvironments' | 'heldForContinuation'\n> {\n return {\n ...(inner.teardownTimeoutMs === undefined\n ? {}\n : { teardownTimeoutMs: inner.teardownTimeoutMs }),\n ...(inner.releaseRetained === undefined\n ? {}\n : { releaseRetained: (signal: AbortSignal) => inner.releaseRetained!(signal) }),\n ...(inner.heldEnvironments === undefined\n ? {}\n : { heldEnvironments: () => inner.heldEnvironments!() }),\n ...(inner.heldForContinuation === undefined\n ? {}\n : { heldForContinuation: () => inner.heldForContinuation!() }),\n }\n}\n\n/**\n * An asker that sends an executor at most one teardown at a time. While a request is still\n * running, every later ask returns that same request instead of sending another beside it.\n *\n * A settlement's own teardown has a short acknowledgement window, and a request that misses it\n * keeps running. Without this, the first settlement retry sent a second teardown next to the\n * first. An executor that does not deduplicate internally, such as one that re-issues its\n * cancels, then ran two teardowns at once. `onRequest` runs once for each request actually sent.\n */\nexport function singleFlightTeardown<Out>(\n executor: Executor<Out>,\n onRequest: () => void,\n): (grace: number | 'brutalKill' | 'infinity') => Promise<TeardownAnswer> {\n let inFlight: Promise<TeardownAnswer> | undefined\n return (grace) => {\n if (inFlight !== undefined) return inFlight\n onRequest()\n let request: Promise<TeardownAnswer>\n try {\n request = Promise.resolve(executor.teardown(grace))\n } catch (error) {\n request = Promise.reject(error)\n }\n inFlight = request\n const settle = (): void => {\n if (inFlight === request) inFlight = undefined\n }\n request.then(settle, settle)\n return request\n }\n}\n","import type { Budget, ResourceSpend, Spend } from './types'\n\n/** Validate caller-owned names and units without assigning domain meaning to them. */\nexport function assertResources(\n resources: Budget['resources'] | Spend['resources'],\n kind: 'limit' | 'amount',\n label: string,\n): void {\n if (resources === undefined) return\n if (resources === null || typeof resources !== 'object' || Array.isArray(resources)) {\n throw new Error(`${label} must be a resource map`)\n }\n for (const [name, resource] of Object.entries(resources)) {\n if (\n !name.trim() ||\n !resource ||\n typeof resource !== 'object' ||\n typeof resource.unit !== 'string' ||\n !resource.unit.trim()\n ) {\n throw new Error(`${label}: resource names and units must be non-empty strings`)\n }\n const value =\n kind === 'limit'\n ? 'limit' in resource\n ? resource.limit\n : undefined\n : 'amount' in resource\n ? resource.amount\n : undefined\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label}.${name}.${kind} must be a non-negative safe integer`)\n }\n if (kind === 'amount' && (!('known' in resource) || typeof resource.known !== 'boolean')) {\n throw new Error(`${label}.${name}.known must be a boolean`)\n }\n }\n}\n\n/** Missing contributors are not usage claims; enforced omissions are marked before aggregation.\n * Overflow retains a safe lower bound and marks it unknown, preserving readable component receipts. */\nexport function addResourceSpend(...maps: ReadonlyArray<Spend['resources']>): {\n resources?: Record<string, ResourceSpend>\n} {\n const totals = new Map<string, ResourceSpend>()\n for (const resources of maps) {\n assertResources(resources, 'amount', 'resource spend')\n for (const [name, resource] of Object.entries(resources ?? {})) {\n const prior = totals.get(name)\n if (prior && prior.unit !== resource.unit) throw new Error(`resource ${name}: unit mismatch`)\n const amount = (prior?.amount ?? 0) + resource.amount\n totals.set(name, {\n unit: resource.unit,\n amount: Math.min(amount, Number.MAX_SAFE_INTEGER),\n known: (prior?.known ?? true) && resource.known && Number.isSafeInteger(amount),\n })\n }\n }\n return totals.size ? { resources: Object.fromEntries(totals) } : {}\n}\n\n/** A terminal omission under an enforced ceiling is unknown, never measured zero. */\nexport function withBudgetResources(\n spend: Spend,\n budget: Pick<Budget, 'resources'>,\n notStarted = false,\n): Spend {\n const resources = new Map(Object.entries(addResourceSpend(spend.resources).resources ?? {}))\n for (const [name, limit] of Object.entries(budget.resources ?? {})) {\n const observed = resources.get(name)\n if (observed && observed.unit !== limit.unit) throw new Error(`resource ${name}: unit mismatch`)\n if (!observed) resources.set(name, { unit: limit.unit, amount: 0, known: notStarted })\n }\n return resources.size ? { ...spend, resources: Object.fromEntries(resources) } : spend\n}\n\n/** Stream increments and a terminal total describe the same work; never sum them twice. */\nexport function resourceTelemetry(streamed: Spend, terminal: Spend): Pick<Spend, 'resources'> {\n const resources = new Map(Object.entries(addResourceSpend(terminal.resources).resources ?? {}))\n for (const [name, value] of Object.entries(streamed.resources ?? {})) {\n const other = resources.get(name)\n if (other && other.unit !== value.unit) throw new Error(`resource ${name}: unit mismatch`)\n resources.set(name, {\n ...value,\n amount: Math.max(value.amount, other?.amount ?? 0),\n known:\n value.known &&\n (other?.known ?? true) &&\n (other === undefined || other.amount === value.amount),\n })\n }\n return addResourceSpend(Object.fromEntries(resources))\n}\n","/**\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 { ValidationError } from '../errors'\nimport { armDeadlineTimer } from './supervise/deadline'\nimport { addResourceSpend } from './supervise/resources'\nimport type { Spend, TokenUsageProvenance } from './supervise/types'\nimport { runTaskQueue } from './task-queue'\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 carrying the abort reason's message. Downstream code pattern-matches on `err.name`. */\nexport function abortError(reason?: unknown): Error {\n const err = new Error(\n reason instanceof Error ? reason.message : reason === undefined ? 'aborted' : String(reason),\n )\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, keepAlive = true): Promise<void> {\n if (signal?.aborted) return Promise.resolve()\n return new Promise((resolve) => {\n const done = () => {\n clearTimer()\n signal?.removeEventListener('abort', done)\n resolve()\n }\n const clearTimer = armDeadlineTimer(ms, done, keepAlive)\n signal?.addEventListener('abort', done, { once: true })\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 clearTimer = armDeadlineTimer(ms, () => resolve(undefined), true)\n promise.then(\n (value) => {\n clearTimer()\n resolve(value)\n },\n () => {\n clearTimer()\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 */\nfunction 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/** Work that happened and reported no receipt. Unlike {@link zeroSpend}, `tokensKnown: false` makes\n * the zero a floor, so a token or dollar ceiling still fires. Never relabel that as a measurement. */\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 ...addResourceSpend(spend.resources),\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 ...(spend.tokensProvenance === undefined ? {} : { tokensProvenance: spend.tokensProvenance }),\n ...streamBreakOf(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 ...addResourceSpend(a.resources, b.resources),\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 ...streamBreakOf(a, b),\n }\n}\n\n/** Absent provenance is the live stream. A stated source beside an absent one folds to `mixed`. */\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/** Fold a broken stream's split. A spend that never broke contributes nothing, not a zero. */\nfunction streamBreakOf(\n ...spends: ReadonlyArray<Spend>\n): Pick<Spend, 'streamedTokens' | 'unobservedTokens' | 'iterationsKnown'> {\n const streamedTokens = foldTokenSplit(spends.map((spend) => spend.streamedTokens))\n const unobservedTokens = foldTokenSplit(spends.map((spend) => spend.unobservedTokens))\n const iterationsKnown = spends.some((spend) => spend.iterationsKnown === false)\n ? (false as const)\n : undefined\n return {\n ...(streamedTokens === undefined ? {} : { streamedTokens }),\n ...(unobservedTokens === undefined ? {} : { unobservedTokens }),\n ...(iterationsKnown === undefined ? {} : { iterationsKnown }),\n }\n}\n\nfunction foldTokenSplit(\n parts: ReadonlyArray<LoopTokenUsage | undefined>,\n): LoopTokenUsage | undefined {\n const present = parts.filter((part): part is LoopTokenUsage => part !== undefined)\n const first = present[0]\n if (first === undefined) return undefined\n const total = cloneTokenUsage(first)\n for (const part of present.slice(1)) addTokenUsage(total, part)\n return total\n}\n\n/** Sum present box minutes. Absence is not zero, so a path with no box stays unmarked.\n * `boxMinutesKnown` is sticky-false. Provenance degrades from observed to estimated to uncaptured. */\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/** Charge `input - cacheRead + output`. A cache read was charged when written. Classes that do not\n * fit `input` credit nothing. Unclassified prompt tokens charge in full. Do not charge\n * `freshInput + cacheWrite`: one unclassified turn would then over-charge the classified ones. */\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 */\ninterface PromptCacheCounters {\n readonly readTokens?: unknown\n readonly writeTokens?: unknown\n}\n\n/** The prompt-cache token classes of one observation, as `LoopTokenUsage` members. */\ntype PromptCacheTokenClasses = Pick<\n LoopTokenUsage,\n 'freshInput' | 'cacheRead' | 'cacheWrite' | 'cacheBreakdownKnown'\n>\n\n/** Nothing reported stays unmarked. A read and a write that fit `input` are a complete split.\n * One counter, or classes past `input`, pass through with `cacheBreakdownKnown: false`.\n * An unreported counter stays absent, never zero. */\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/** Add a subtotal. Classes that overflow their own `input` are dropped, so a later fold cannot\n * credit a cache read this record refused. An unclassified positive input makes the sum unknown. */\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/** Run `fn` with at most `limit` calls in flight, preserving input order. The first rejection wins. */\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 results = new Array<R>(items.length)\n let next = 0\n for await (const settled of runTaskQueue({\n concurrency: Math.max(1, Math.min(Math.floor(limit), items.length)),\n take: () => {\n const index = next++\n return index < items.length ? { id: String(index), value: index } : undefined\n },\n execute: ({ value: index }) => fn(items[index] as T, index),\n })) {\n if (settled.status === 'rejected') throw settled.reason\n results[settled.task.value] = settled.value\n }\n return results\n}\n\n/** The message of a thrown value: an `Error`'s own message, anything else stringified. */\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** True for an object whose `Symbol.asyncIterator` is callable, so `for await` can consume it. */\nexport function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'\n )\n}\n\n/** 32-bit FNV-1a over a string's UTF-16 code units, as eight lowercase hex digits. */\nexport function fnv1a32Hex(text: string): string {\n let h = 0x811c9dc5\n for (let i = 0; i < text.length; i += 1) {\n h ^= text.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return (h >>> 0).toString(16).padStart(8, '0')\n}\n\n/** Parent journals may already contain an interrupted driver's inference prefix. */\nexport function unreportedSpend(total: Spend, prior: Spend): Spend {\n const tokens = { ...total.tokens }\n for (const key of ['input', 'output', 'freshInput', 'cacheRead', 'cacheWrite'] as const) {\n const value = total.tokens[key]\n if (value !== undefined) tokens[key] = Math.max(0, value - (prior.tokens[key] ?? 0))\n }\n return {\n ...total,\n ...addResourceSpend(\n total.resources === undefined\n ? undefined\n : Object.fromEntries(\n Object.entries(total.resources).map(([name, value]) => {\n const previous = prior.resources?.[name]\n if (previous && previous.unit !== value.unit)\n throw new ValidationError(`resource ${name}: unit mismatch`)\n return [\n name,\n {\n ...value,\n amount: Math.max(0, value.amount - (previous?.amount ?? 0)),\n known: value.known && (previous?.known ?? true),\n },\n ]\n }),\n ),\n ),\n iterations: Math.max(0, total.iterations - prior.iterations),\n tokens,\n usd: Math.max(0, total.usd - prior.usd),\n ms: Math.max(0, total.ms - prior.ms),\n ...(total.usdEstimated === undefined\n ? {}\n : { usdEstimated: Math.max(0, total.usdEstimated - (prior.usdEstimated ?? 0)) }),\n ...(total.boxMinutes === undefined\n ? {}\n : { boxMinutes: Math.max(0, total.boxMinutes - (prior.boxMinutes ?? 0)) }),\n }\n}\n"],"mappings":";;;AAIA,MAAM,qBAAqB;AAE3B,MAAa,iCAAiC;;AAG9C,MAAa,wBAAwB;;AAErC,MAAa,uBAAuB;;AAqBpC,MAAa,4BACX;;AAOF,SAAgB,cAAc,QAAyD;CACrF,IAAI,WAAW,OAAO,OAAO,KAAA;CAC7B,MAAM,SAAS,QAAQ,UAAA;CACvB,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,UAAU,GAC7C,MAAM,IAAI,gBACR,wEACF;CAEF,OAAO;AACT;;;;AAKA,MAAa,2BAA2B;;AAGxC,SAAgB,sBAAsB,QAA0B;CAC9D,OAAO,WAAA,6BAAoC,WAAA;AAC7C;AACA,MAAM,8BAA8B;;;AAIpC,SAAgB,iBACd,SACA,YACA,YAAY,OACA;CACZ,MAAM,eAAe,KAAK,IAAI,IAAI,KAAK,IAAI,GAAG,OAAO;CACrD,IAAI,CAAC,OAAO,SAAS,OAAO,KAAK,CAAC,OAAO,cAAc,KAAK,KAAK,YAAY,CAAC,GAC5E,MAAM,IAAI,gBAAgB,iDAAiD;C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AG,iBACD,MAAM,cAAc,KAAA,IAChB,KAAA,IACA,OAAO,YACL,OAAO,QAAQ,MAAM,SAAS,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW;GACrD,MAAM,WAAW,MAAM,YAAY;GACnC,IAAI,YAAY,SAAS,SAAS,MAAM,MACtC,MAAM,IAAI,gBAAgB,YAAY,KAAK,gBAAgB;GAC7D,OAAO,CACL,MACA;IACE,GAAG;IACH,QAAQ,KAAK,IAAI,GAAG,MAAM,UAAU,UAAU,UAAU,EAAE;IAC1D,OAAO,MAAM,UAAU,UAAU,SAAS;GAC5C,CACF;EACF,CAAC,CACH,CACN;EACA,YAAY,KAAK,IAAI,GAAG,MAAM,aAAa,MAAM,UAAU;EAC3D;EACA,KAAK,KAAK,IAAI,GAAG,MAAM,MAAM,MAAM,GAAG;EACtC,IAAI,KAAK,IAAI,GAAG,MAAM,KAAK,MAAM,EAAE;EACnC,GAAI,MAAM,iBAAiB,KAAA,IACvB,CAAC,IACD,EAAE,cAAc,KAAK,IAAI,GAAG,MAAM,gBAAgB,MAAM,gBAAgB,EAAE,EAAE;EAChF,GAAI,MAAM,eAAe,KAAA,IACrB,CAAC,IACD,EAAE,YAAY,KAAK,IAAI,GAAG,MAAM,cAAc,MAAM,cAAc,EAAE,EAAE;CAC5E;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { p as mapWithConcurrency } from "./util-
|
|
1
|
+
import { p as mapWithConcurrency } from "./util-fcckrkKp.js";
|
|
2
2
|
import { agentCandidateArtifactRefSchema, canonicalCandidateBytes as canonicalCandidateBytes$1 } from "@tangle-network/agent-interface";
|
|
3
3
|
import { isRecord } from "@tangle-network/agent-core";
|
|
4
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
@@ -1859,4 +1859,4 @@ function asError(error) {
|
|
|
1859
1859
|
}
|
|
1860
1860
|
export { markPutStreamVerified as A, verifyCanonicalCandidateDocument as B, readMaterializedWorkspaceFiles as C, verifyMaterializedProfileWorkspace as D, verifyBytes as E, deepFreezeCandidate as F, embeddedCandidateArtifact as I, immutableCandidateValue as L, canonicalCandidateBytes$1 as M, canonicalCandidateDigest$1 as N, verifyMaterializedWorkspace as O, canonicalCandidateDocument as P, omitTopLevelDigest as R, captureMaterializedWorkspace as S, scanMaterializedWorkspaceManifest as T, hasControlCharacter as V, assertExactObjectKeys as _, verifyAgentCandidateWorkspaceArtifacts as a, artifactCacheKey as b, createAgentCandidateWorkspacePort as c, verifyTaskCheckout as d, verifyTaskOutcomePatch as f, persistCandidateOutputArtifact as g, workspaceLimits as h, readAgentCandidateWorkspaceArtifactFiles as i, verifiedArtifactChunks as j, verifyWorkspaceSnapshotArtifacts as k, readCandidateGitHubResource as l, safeArchivePath as m, captureAgentCandidateWorkspaceTreeToArtifacts as n, verifyAgentCandidateWorkspaceTree as o, captureAgentCandidateWorkspaceFiles as p, materializeAgentCandidateWorkspaceFromArtifacts as r, captureAgentCandidateWorkspace as s, captureAgentCandidateWorkspaceToArtifacts as t, verifyCandidateCode as u, isWellFormedUnicode as v, readVerifiedArtifact as w, candidateWorkspaceManifest as x, WorkspaceScanLimitError as y, sha256Bytes$1 as z };
|
|
1861
1861
|
|
|
1862
|
-
//# sourceMappingURL=workspace-streams-
|
|
1862
|
+
//# sourceMappingURL=workspace-streams-DA9R3j-p.js.map
|