@tangle-network/agent-runtime 0.134.1 → 0.134.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/{activation-BaxUkhEf.js → activation-BJS5eud7.js} +3 -3
  2. package/dist/{activation-BaxUkhEf.js.map → activation-BJS5eud7.js.map} +1 -1
  3. package/dist/agent.d.ts +2 -2
  4. package/dist/agent.js +3 -3
  5. package/dist/{analyst-loop-BKWqQhVI.js → analyst-loop-Dk6_xfhI.js} +2 -2
  6. package/dist/{analyst-loop-BKWqQhVI.js.map → analyst-loop-Dk6_xfhI.js.map} +1 -1
  7. package/dist/analyst-loop.d.ts +1 -1
  8. package/dist/analyst-loop.js +1 -1
  9. package/dist/{authoring-BlbRLEOS.js → authoring-zj6jq4HE.js} +2 -2
  10. package/dist/{authoring-BlbRLEOS.js.map → authoring-zj6jq4HE.js.map} +1 -1
  11. package/dist/candidate-execution/index.js +4 -4
  12. package/dist/{candidate-execution-CJRP9CcZ.js → candidate-execution-DDOdYrRO.js} +4 -4
  13. package/dist/{candidate-execution-CJRP9CcZ.js.map → candidate-execution-DDOdYrRO.js.map} +1 -1
  14. package/dist/{conversation-CrWcNPQg.js → conversation-DYVSghi8.js} +2 -2
  15. package/dist/{conversation-CrWcNPQg.js.map → conversation-DYVSghi8.js.map} +1 -1
  16. package/dist/conversation.d.ts +1 -1
  17. package/dist/conversation.js +1 -1
  18. package/dist/{environment-provider-qDOhdE9M.d.ts → environment-provider-CCASQ5FA.d.ts} +3 -3
  19. package/dist/{environment-provider-CwvY-Zeq.js → environment-provider-CLNVqp6H.js} +2 -2
  20. package/dist/{environment-provider-CwvY-Zeq.js.map → environment-provider-CLNVqp6H.js.map} +1 -1
  21. package/dist/environment-provider.d.ts +1 -1
  22. package/dist/environment-provider.js +1 -1
  23. package/dist/{graph-CKNenH2a.js → graph-D0bln4rR.js} +3 -3
  24. package/dist/{graph-CKNenH2a.js.map → graph-D0bln4rR.js.map} +1 -1
  25. package/dist/{improvement-cycle-CSBantKB.js → improvement-cycle-fezPL8Th.js} +6 -6
  26. package/dist/{improvement-cycle-CSBantKB.js.map → improvement-cycle-fezPL8Th.js.map} +1 -1
  27. package/dist/{index-Cz4qKBxm.d.ts → index-BDPN51IH.d.ts} +4 -4
  28. package/dist/{index-CgBJtAzI.d.ts → index-Dg4MfLHq.d.ts} +3 -3
  29. package/dist/{index-De10l_EU.d.ts → index-gevMEHnE.d.ts} +13 -11
  30. package/dist/index.d.ts +9 -9
  31. package/dist/index.js +13 -13
  32. package/dist/intelligence.d.ts +5 -5
  33. package/dist/intelligence.js +6 -6
  34. package/dist/kernel.d.ts +6 -6
  35. package/dist/kernel.js +10 -10
  36. package/dist/{knowledge-B2C9t1Z4.js → knowledge-BXtZD-pC.js} +5 -5
  37. package/dist/{knowledge-B2C9t1Z4.js.map → knowledge-BXtZD-pC.js.map} +1 -1
  38. package/dist/knowledge.d.ts +1 -1
  39. package/dist/knowledge.js +1 -1
  40. package/dist/{loop-runner-bin-C0ymKYU7.js → loop-runner-bin-CjDcX5ua.js} +4 -4
  41. package/dist/{loop-runner-bin-C0ymKYU7.js.map → loop-runner-bin-CjDcX5ua.js.map} +1 -1
  42. package/dist/{loop-runner-bin-D-tgbSPx.d.ts → loop-runner-bin-DvaXefJJ.d.ts} +3 -3
  43. package/dist/loop-runner-bin.d.ts +1 -1
  44. package/dist/loop-runner-bin.js +1 -1
  45. package/dist/mcp/bin.js +3 -3
  46. package/dist/mcp/index.d.ts +5 -5
  47. package/dist/mcp/index.js +5 -5
  48. package/dist/{openai-tools-CzEiSbPW.d.ts → openai-tools-CF2RMD7_.d.ts} +2 -2
  49. package/dist/{openai-tools-ClOkPIi0.js → openai-tools-CycyI0v2.js} +2 -2
  50. package/dist/{openai-tools-ClOkPIi0.js.map → openai-tools-CycyI0v2.js.map} +1 -1
  51. package/dist/{prepare-BXEtLOj9.js → prepare-Cv7NzRZl.js} +2 -2
  52. package/dist/{prepare-BXEtLOj9.js.map → prepare-Cv7NzRZl.js.map} +1 -1
  53. package/dist/primeintellect/index.d.ts +1 -1
  54. package/dist/profiles.d.ts +1 -1
  55. package/dist/{protected-model-port-B7PAmTGi.js → protected-model-port-RnAK2ZrP.js} +2 -2
  56. package/dist/{protected-model-port-B7PAmTGi.js.map → protected-model-port-RnAK2ZrP.js.map} +1 -1
  57. package/dist/{redact-6UE6pdNi.d.ts → redact-8ssmxJ0J.d.ts} +3 -3
  58. package/dist/{runtime-Bisfbn3_.js → runtime-Btwztu5V.js} +14 -11
  59. package/dist/runtime-Btwztu5V.js.map +1 -0
  60. package/dist/{runtime-DlxoqEj2.d.ts → runtime-CFD7S185.d.ts} +4 -4
  61. package/dist/{sandbox-events-vIwmuPdl.js → sandbox-events-CA2amHoA.js} +98 -3
  62. package/dist/sandbox-events-CA2amHoA.js.map +1 -0
  63. package/dist/{spawn-journal-B856eA8e.js → spawn-journal-ZKEKel8N.js} +10 -4
  64. package/dist/spawn-journal-ZKEKel8N.js.map +1 -0
  65. package/dist/{stream-agent-turn-CJog3ebs.d.ts → stream-agent-turn-8rmaOWtn.d.ts} +3 -3
  66. package/dist/{stream-agent-turn-CdIcf-bn.js → stream-agent-turn-DYBpzMmq.js} +2 -2
  67. package/dist/{stream-agent-turn-CdIcf-bn.js.map → stream-agent-turn-DYBpzMmq.js.map} +1 -1
  68. package/dist/{structural-rollout-DKEP5i__.js → structural-rollout-BHluS9JC.js} +4 -4
  69. package/dist/{structural-rollout-DKEP5i__.js.map → structural-rollout-BHluS9JC.js.map} +1 -1
  70. package/dist/{supervise-DhghNvl6.js → supervise-BvjQqKsp.js} +17 -6
  71. package/dist/{supervise-DhghNvl6.js.map → supervise-BvjQqKsp.js.map} +1 -1
  72. package/dist/{supervisor-CMlIOkJP.js → supervisor-BsniJxSa.js} +113 -29
  73. package/dist/supervisor-BsniJxSa.js.map +1 -0
  74. package/dist/testing.d.ts +2 -2
  75. package/dist/testing.js +12 -12
  76. package/dist/{types-6zHo67jn.d.ts → types-Cz4m4Iv6.d.ts} +3 -3
  77. package/dist/{types-D4BfurNs.d.ts → types-XtB9WZzr.d.ts} +26 -5
  78. package/dist/util-C1bv6yog.js +282 -0
  79. package/dist/util-C1bv6yog.js.map +1 -0
  80. package/dist/{workspace-archive-B5oJu5mZ.js → workspace-archive-DFwzVhbk.js} +2 -2
  81. package/dist/{workspace-archive-B5oJu5mZ.js.map → workspace-archive-DFwzVhbk.js.map} +1 -1
  82. package/package.json +1 -1
  83. package/dist/runtime-Bisfbn3_.js.map +0 -1
  84. package/dist/sandbox-events-vIwmuPdl.js.map +0 -1
  85. package/dist/spawn-journal-B856eA8e.js.map +0 -1
  86. package/dist/supervisor-CMlIOkJP.js.map +0 -1
  87. package/dist/util-DD8bRWPL.js +0 -194
  88. package/dist/util-DD8bRWPL.js.map +0 -1
package/dist/testing.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Ja as superviseWithTestBrain, Ka as SuperviseTestOptions, Lt as RunGraphTestOptions, Vt as runGraphWithTestBrain, gn as driverAgent, hn as DriverAgentOptions, io as SupervisorAgentTestDeps, po as supervisorAgentWithTestBrain } from "./index-De10l_EU.js";
2
- import { it as ToolLoopChat, rt as ToolLoopCallContext } from "./runtime-DlxoqEj2.js";
1
+ import { Ja as superviseWithTestBrain, Ka as SuperviseTestOptions, Lt as RunGraphTestOptions, Vt as runGraphWithTestBrain, gn as driverAgent, hn as DriverAgentOptions, io as SupervisorAgentTestDeps, po as supervisorAgentWithTestBrain } from "./index-gevMEHnE.js";
2
+ import { it as ToolLoopChat, rt as ToolLoopCallContext } from "./runtime-CFD7S185.js";
3
3
  import { AgentImprovementProposal, AgentProfile, AgentProfileImprovementMeasuredComparison, SandboxSizePreset } from "@tangle-network/agent-interface";
4
4
  //#region src/testing/index.d.ts
5
5
  /** A proposal produced by Runtime's opaque profile-improvement path. */
package/dist/testing.js CHANGED
@@ -1,12 +1,12 @@
1
- import { $ as parseExactAgentProfile, K as applyExactAgentProfileDiff, rt as canonicalCandidateDigest$1, st as immutableCandidateValue } from "./prepare-BXEtLOj9.js";
2
- import { f as verifyAgentImprovementProposal } from "./improvement-cycle-CSBantKB.js";
3
- import { c as supervisorAgentWithTestBrain, dt as driverAgent, r as superviseWithTestBrain } from "./supervise-DhghNvl6.js";
4
- import { i as runGraphWithTestBrain } from "./graph-CKNenH2a.js";
1
+ import { $ as parseExactAgentProfile, K as applyExactAgentProfileDiff, rt as canonicalCandidateDigest$1, st as immutableCandidateValue } from "./prepare-Cv7NzRZl.js";
2
+ import { f as verifyAgentImprovementProposal } from "./improvement-cycle-fezPL8Th.js";
3
+ import { c as supervisorAgentWithTestBrain, dt as driverAgent, r as superviseWithTestBrain } from "./supervise-BvjQqKsp.js";
4
+ import { i as runGraphWithTestBrain } from "./graph-D0bln4rR.js";
5
5
  import { SANDBOX_SIZE_PRESET_NAMES } from "@tangle-network/agent-interface";
6
6
  //#region src/testing/fixtures/agent-improvement-proposal.json
7
7
  var agent_improvement_proposal_default = {
8
8
  changedSurfaces: ["prompt"],
9
- digest: "sha256:1f060b6f2e36df287e9eb377763752983d558b17087e842675656bbac2225153",
9
+ digest: "sha256:416095697d67b527763d3872ea497de9e90f21f0f06cb4ea001b8b72b2c84573",
10
10
  evaluation: {
11
11
  "decision": {
12
12
  "contributingChecks": [
@@ -4565,7 +4565,7 @@ var agent_improvement_proposal_default = {
4565
4565
  ],
4566
4566
  "metadata": {
4567
4567
  "fixture": "agent-improvement-proposal",
4568
- "runtimeVersion": "0.134.1"
4568
+ "runtimeVersion": "0.134.3"
4569
4569
  },
4570
4570
  "objectives": [
4571
4571
  {
@@ -4676,8 +4676,8 @@ var agent_improvement_proposal_default = {
4676
4676
  "baselineContentHash": "sha256:5c21ee53e513fc604cb09754e21c392b24a424da0ef37dbf8f1ee4a8a0b08f09",
4677
4677
  "candidateContentHash": "sha256:60fcbb1c728194bd51d7d19cb732d1c3f1881dce7e0a6266b41c8b98cfd65693",
4678
4678
  "kind": "agent-eval-loop",
4679
- "recordDigest": "sha256:6df4c838fd55296f7d6574171c1a3ad91ae43879869d8ba7f16b84605d379604",
4680
- "runId": "agent-runtime-0.134.1-proposal-fixture",
4679
+ "recordDigest": "sha256:06a9df142cbdf228134e7548e97ec088d6f838dc9ce33648fe50694dbed642ea",
4680
+ "runId": "agent-runtime-0.134.3-proposal-fixture",
4681
4681
  "schema": "agent-candidate-experiment"
4682
4682
  }
4683
4683
  },
@@ -4700,13 +4700,13 @@ var agent_improvement_proposal_default = {
4700
4700
  }],
4701
4701
  kind: "agent-improvement-proposal",
4702
4702
  proposedAt: "2026-07-10T01:00:00.000Z",
4703
- runId: "agent-runtime-0.134.1-proposal-fixture"
4703
+ runId: "agent-runtime-0.134.3-proposal-fixture"
4704
4704
  };
4705
4705
  //#endregion
4706
4706
  //#region src/testing/fixtures/agent-profile-improvement-proposal.json
4707
4707
  var agent_profile_improvement_proposal_default = {
4708
4708
  changedSurfaces: ["prompt", "skills"],
4709
- digest: "sha256:359e5a1f5192d915f2d24bc1fb3558c017881b59320c72d44c3c3d5f70ec0daa",
4709
+ digest: "sha256:cb9b48c6a1b9e4042f0e0d6d4789f5ed9fc6ef4e56f6c4a64610e80a07510cbb",
4710
4710
  evaluation: {
4711
4711
  "decision": {
4712
4712
  "contributingChecks": [
@@ -6340,7 +6340,7 @@ var agent_profile_improvement_proposal_default = {
6340
6340
  ],
6341
6341
  "metadata": {
6342
6342
  "fixture": "agent-profile-improvement-proposal",
6343
- "runtimeVersion": "0.134.1"
6343
+ "runtimeVersion": "0.134.3"
6344
6344
  },
6345
6345
  "objectives": [
6346
6346
  {
@@ -6451,7 +6451,7 @@ var agent_profile_improvement_proposal_default = {
6451
6451
  "baselineContentHash": "sha256:21c495a37c418c10bde64fbaa188beddeed31f1f051ea60a6a6582a9ee0db704",
6452
6452
  "candidateContentHash": "sha256:103f77bc8481601eef1ad5fe6ba84a40dffabc3a44f421f8c8559121edab84e9",
6453
6453
  "kind": "agent-eval-loop",
6454
- "recordDigest": "sha256:4d25ec3f7deecdb4f89bffaa39d4e757b26b790ed04c5c8ff9a822d46f89a25c",
6454
+ "recordDigest": "sha256:d759061e80f611f668b1c45bd074b2b5f106cf8892462b39ecca459ceafe5791",
6455
6455
  "runId": "profile-improvement-1",
6456
6456
  "schema": "agent-profile-improvement-experiment"
6457
6457
  }
@@ -714,9 +714,9 @@ interface LoopTokenUsage {
714
714
  tokensKnown?: false;
715
715
  /** Prompt tokens newly processed by the provider, when every prompt class is known. */
716
716
  freshInput?: number;
717
- /** Prompt tokens served from a provider cache, when every prompt class is known. */
717
+ /** Prompt tokens the provider reported serving from its cache. */
718
718
  cacheRead?: number;
719
- /** Prompt tokens written to a provider cache, when every prompt class is known. */
719
+ /** Prompt tokens the provider reported writing to its cache. */
720
720
  cacheWrite?: number;
721
721
  /**
722
722
  * False when any positive-input observation omitted or contradicted the prompt-cache split.
@@ -1215,4 +1215,4 @@ interface ExecCtx {
1215
1215
  }
1216
1216
  //#endregion
1217
1217
  export { OpenAIChatToolChoice as $, RuntimeRunCompleteInput as A, AgentBackendInput as B, MountRecorder as C, SelectionReceipt as D, SandboxClient as E, RuntimeRunRow as F, AgentTaskContext as G, AgentKnowledgeProvider as H, RuntimeRunStatus as I, AgentTaskStatus as J, AgentTaskRunResult as K, startRuntimeRun as L, RuntimeRunHandle as M, RuntimeRunOptions as N, ValidationCtx as O, RuntimeRunPersistenceAdapter as P, OpenAIChatTool as Q, AgentAdapter as R, MountManifestEntry as S, RunProvenance as T, AgentRuntimeEvent as U, AgentExecutionBackend as V, AgentRuntimeEventSink as W, KnowledgeReadinessDecision as X, BackendErrorDetail as Y, OpenAIChatResponseFormat as Z, LoopTeardownFailedPayload as _, Iteration as a, LoopTraceEvent as b, LoopIterationDispatchPayload as c, LoopLineageOptions as d, RunAgentTaskOptions as et, LoopPlanDescription as f, LoopStartedPayload as g, LoopSandboxPlacement as h, ExecCtx as i, RuntimeStreamEvent as it, RuntimeRunCost as j, Validator as k, LoopIterationEndedPayload as l, LoopResult as m, DefaultVerdict as n, RuntimeSession as nt, LoopDecisionPayload as o, LoopPlanPayload as p, AgentTaskSpec as q, Driver as r, RuntimeSessionStore as rt, LoopEndedPayload as s, AgentRunSpec as t, RunAgentTaskStreamOptions as tt, LoopIterationStartedPayload as u, LoopTokenUsage as v, OutputAdapter as w, LoopWinner as x, LoopTraceEmitter as y, AgentBackendContext as z };
1218
- //# sourceMappingURL=types-6zHo67jn.d.ts.map
1218
+ //# sourceMappingURL=types-Cz4m4Iv6.d.ts.map
@@ -1,4 +1,4 @@
1
- import { J as AgentTaskStatus, U as AgentRuntimeEvent, it as RuntimeStreamEvent, v as LoopTokenUsage, y as LoopTraceEmitter } from "./types-6zHo67jn.js";
1
+ import { J as AgentTaskStatus, U as AgentRuntimeEvent, it as RuntimeStreamEvent, v as LoopTokenUsage, y as LoopTraceEmitter } from "./types-Cz4m4Iv6.js";
2
2
  import { l as RuntimeHooks } from "./runtime-hooks-sbRpjStq.js";
3
3
  import { ControlEvalResult, DefaultVerdict, KnowledgeReadinessReport, KnowledgeRequirement, ToolSpan } from "@tangle-network/agent-eval";
4
4
  import { AgentProfile as AgentProfile$1, Sha256Digest } from "@tangle-network/agent-interface";
@@ -896,17 +896,31 @@ type UsageEvent = {
896
896
  output: number;
897
897
  /** Newly processed prompt tokens. Present only with a complete cache split. */
898
898
  freshInput?: number;
899
- /** Prompt tokens read from cache. Present only with a complete cache split. */
899
+ /** Prompt tokens the provider reported reading from cache. */
900
900
  cacheRead?: number;
901
- /** Prompt tokens written to cache. Present only with a complete cache split. */
901
+ /** Prompt tokens the provider reported writing to cache. */
902
902
  cacheWrite?: number;
903
- /** False when this observation cannot classify all positive prompt tokens. */
903
+ /**
904
+ * False when this observation cannot classify all positive prompt tokens — including a
905
+ * provider that reports a read with no write counter. The measured counters are still
906
+ * carried; the marker says the remaining prompt tokens are unclassified, so a charge over
907
+ * them is an upper bound. A counter the provider did not report is absent, never zero.
908
+ */
904
909
  cacheBreakdownKnown?: false;
905
910
  } | {
906
911
  kind: 'cost';
907
912
  /** Known dollar subtotal. When false, `usd` must not be treated as total cost. */
908
913
  usdKnown?: false;
909
914
  usd: number;
915
+ /**
916
+ * The part of `usd` this runtime priced from a model catalog because no provider receipt
917
+ * covered the work. Requires `usdKnown: false` — a catalog price approximates what a
918
+ * provider would bill and never measures what it did.
919
+ *
920
+ * Absence means this runtime priced nothing here, NOT that `usd` is a receipt. `usdKnown`
921
+ * is what says whether a dollar figure is measured.
922
+ */
923
+ usdEstimated?: number;
910
924
  } | {
911
925
  kind: 'iteration';
912
926
  };
@@ -1113,6 +1127,11 @@ interface Spend {
1113
1127
  * when enforcing a dollar-denominated comparison or limit. */
1114
1128
  usdKnown?: boolean;
1115
1129
  usd: number;
1130
+ /** The part of `usd` priced from a model catalog because no provider receipt covered the work.
1131
+ * `usd - usdEstimated` is what a provider is known to have billed. Present only with
1132
+ * `usdKnown: false`; absence means nothing here was catalog-priced, not that `usd` is
1133
+ * measured. */
1134
+ usdEstimated?: number;
1116
1135
  ms: number;
1117
1136
  }
1118
1137
  /** OTP child-spec restart class. */
@@ -1560,6 +1579,8 @@ type SpawnEvent = {
1560
1579
  kind: 'metered';
1561
1580
  id: NodeId;
1562
1581
  spend: Spend;
1582
+ /** Runtime bookkeeping only; this record carries no provider inference attempt. */
1583
+ accountingOnly?: true;
1563
1584
  /** Runtime-owned provider attempt evidence for this driver's own inference turn. */
1564
1585
  providerModel?: ProviderModelExecutionEvidence;
1565
1586
  seq: number;
@@ -1905,4 +1926,4 @@ interface WidenGate<Out> {
1905
1926
  }
1906
1927
  //#endregion
1907
1928
  export { WaitOpts as $, WaitSpec as $t, ResumedWork as A, exportEvalRuns as At, SpawnOpts as B, RuntimeTelemetryOptions as Bt, NodeStatus as C, OtelSpan as Ct, Restart as D, buildRuntimeEventOtelSpans as Dt, ProviderModelExecutionEvidence as E, buildLoopSpanNodes as Et, Runtime as F, toOtelAttributes as Ft, SpendGap as G, sanitizeAgentRuntimeEvent as Gt, SpawnRejection as H, SanitizedKnowledgeRequirement as Ht, Scope as I, RuntimeEventCollector as It, Supervisor as J, PendingWait as Jt, SteerableRootHandle as K, sanitizeKnowledgeReadinessReport as Kt, Settled as L, RuntimeStreamEventCollector as Lt, RootMaterialization as M, loopEventToOtelSpan as Mt, RootProviderModelEvidence as N, padSpanId as Nt, ResultBlobStore as O, createOpenInferenceFileExporter as Ot, RootSignal as P, padTraceId as Pt, UsageEvent as Q, WaitRejection as Qt, SpawnEvent as R, RuntimeStreamEventSink as Rt, NodeSnapshot as S, OtelExporter as St, ProviderModelAttemptEvidence as T, buildLoopOtelSpans as Tt, Spend as U, createRuntimeEventCollector as Ut, SpawnPrior as V, SanitizedKnowledgeReadinessReport as Vt, SpendChannel as W, createRuntimeStreamEventCollector as Wt, TreeView as X, WaitProbe as Xt, SupervisorOpts as Y, WaitOutcome as Yt, UnknownMaterializationReason as Z, WaitProbeRegistry as Zt, MaterializedExecutionIdentity as _, ScopeProgressInput as _n, EvalRunsExportResult as _t, DefaultVerdict as a, waitUntil as an, readWorkerTraceContext as at, NodeExecutionIdentity as b, readWorkerProgress as bn, OtelAttribute as bt, ExecutorAccounting as c, ToolStepInput as cn, workerTraceSeamKey as ct, ExecutorFactory as d, decodeToolPart as dn, mergeTraceEnv as dt, createWaitProbes as en, WidenGate as et, ExecutorMaterialization as f, sandboxSessionTraceSource as fn, readTraceContextFromEnv as ft, Handle as g, ExecutorProgress as gn, EvalRunsExportConfig as gt, ExecutorResult as h, DEFAULT_STALL_AFTER_MS as hn, EvalRunGeneration as ht, Budget as i, validateWaitSpec as in, WorkerTraceSeamCarrier as it, RootHandle as j, generateSpanId as jt, ResumedKeyState as k, createOtelExporter as kt, ExecutorContext as l, TraceSource as ln, TraceContext as lt, ExecutorRegistry as m, ActivityNote as mn, EvalRunEvent as mt, AgentExecutionRef as n, pollFor as nn, WorkerTraceUnavailableReason as nt, ExecutionBindingReceipt as o, SessionMessageLike as on, workerTraceEnv as ot, ExecutorNodeContext as p, ActivityLog as pn, traceContextToEnv as pt, SupervisedResult as q, sanitizeRuntimeStreamEvent as qt, AgentSpec as r, timerAt as rn, WorkerTraceResolver as rt, Executor as s, SessionTraceBox as sn, workerTraceHeaders as st, Agent as t, isWaitOutcome as tn, WorkerTraceEvidence as tt, ExecutorExecutionBinding as u, createPushTraceSource as un, createPropagatingTraceEmitter as ut, MaterializedModelIdentity as v, WorkerProgress as vn, INTELLIGENCE_WIRE_VERSION as vt, ProfileMaterializationReceipt as w, RuntimeEventOtelOptions as wt, NodeId as x, OtelExportConfig as xt, NoWinnerError as y, createActivityLog as yn, LoopSpanNode as yt, SpawnJournal as z, RuntimeStreamEventSummary as zt };
1908
- //# sourceMappingURL=types-D4BfurNs.d.ts.map
1929
+ //# sourceMappingURL=types-XtB9WZzr.d.ts.map
@@ -0,0 +1,282 @@
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
+ /** Copy a token subtotal without dropping optional provider cache telemetry. */
124
+ function cloneTokenUsage(usage) {
125
+ const cacheBreakdownUnknown = usage.cacheBreakdownKnown === false || usage.input > 0 && !hasClassifiedCacheBreakdown(usage);
126
+ return {
127
+ input: usage.input,
128
+ output: usage.output,
129
+ ...usage.tokensKnown === false ? { tokensKnown: false } : {},
130
+ ...usage.freshInput !== void 0 ? { freshInput: usage.freshInput } : {},
131
+ ...usage.cacheRead !== void 0 ? { cacheRead: usage.cacheRead } : {},
132
+ ...usage.cacheWrite !== void 0 ? { cacheWrite: usage.cacheWrite } : {},
133
+ ...cacheBreakdownUnknown ? { cacheBreakdownKnown: false } : {}
134
+ };
135
+ }
136
+ /** True only when every positive prompt token has a consistent cache classification. */
137
+ function hasCompleteCacheBreakdown(usage) {
138
+ if (usage.cacheBreakdownKnown === false) return false;
139
+ return hasClassifiedCacheBreakdown(usage);
140
+ }
141
+ function hasClassifiedCacheBreakdown(usage) {
142
+ if (usage.input === 0) return true;
143
+ if (usage.freshInput === void 0 || usage.cacheRead === void 0 || usage.cacheWrite === void 0) return false;
144
+ return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input;
145
+ }
146
+ /**
147
+ * The token charge for one observation: every token counted ONCE, at the moment it first enters
148
+ * the context — `input − cacheRead + output`.
149
+ *
150
+ * `input` is a rolled-up prompt total that re-counts a cached prefix on every turn that reads it,
151
+ * so charging `input` makes a 100K prefix read 40 times cost 4.1M for content authored once. A
152
+ * cache read is content that was already charged when it was written, so it is the one class the
153
+ * charge subtracts. Under a complete split the result is exactly `freshInput + cacheWrite`. No
154
+ * price weight is involved: this counts work, and money is a separate channel.
155
+ *
156
+ * The subtraction form is what makes the charge ADDITIVE. `input` and `cacheRead` both accumulate
157
+ * through `addTokenUsage`, so the charge on an aggregate equals the sum of the charges on the
158
+ * records that built it — including an aggregate that mixes classified and unclassified turns,
159
+ * where the unclassified remainder is charged in full and only the reported cache reads are
160
+ * credited. A form that read `freshInput + cacheWrite` directly loses that: one unclassified turn
161
+ * would drop the whole aggregate to `input + output` and over-charge every classified turn with it.
162
+ *
163
+ * The one arithmetic guarantee: a set of classes that does not FIT inside the prompt total it
164
+ * partitions credits nothing, so the charge is never below `output` and a class that overflows its
165
+ * own total buys no tokens. It is not a guarantee against a provider that reports a cache read it
166
+ * never served — that provider can under-report `input` just as easily, and the token channel is an
167
+ * accounting unit, not a trust boundary. Prompt tokens the provider left unclassified are charged
168
+ * in full, so a spend with no readable split charges an upper bound on newly-presented work rather
169
+ * than a measurement, and every caller that enforces a ceiling must report the difference
170
+ * (`BudgetPool` does it through `readout().cacheBreakdownKnown`).
171
+ */
172
+ function chargedTokens(usage) {
173
+ return usage.input - creditedCacheRead(usage) + usage.output;
174
+ }
175
+ /** `cacheRead` if the reported classes fit inside `input`, else nothing. */
176
+ function creditedCacheRead(usage) {
177
+ const { cacheRead } = usage;
178
+ if (cacheRead === void 0) return 0;
179
+ return classifiedTotal(usage, cacheRead) > usage.input ? 0 : cacheRead;
180
+ }
181
+ function classifiedTotal(usage, cacheRead) {
182
+ return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0);
183
+ }
184
+ /**
185
+ * Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds
186
+ * and `chargedTokens` credits.
187
+ *
188
+ * The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`
189
+ * vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the
190
+ * three outcomes are different facts that must not collapse into one another:
191
+ *
192
+ * - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,
193
+ * because a provider that says nothing about caching has not said the split is unknowable.
194
+ * - **Read and write both reported, and fitting inside `input`** — a complete partition, so
195
+ * `freshInput` is the remainder and the split is known.
196
+ * - **One counter reported, or classes that overflow `input`** — the counters that ARE measured
197
+ * pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports
198
+ * no write) still credits the read it measured, while declaring the rest unclassified so the
199
+ * charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a
200
+ * partition of a total it exceeds.
201
+ *
202
+ * A counter the provider did not report stays absent. A zero would claim the provider measured no
203
+ * cache, which is a different fact from a provider that did not report.
204
+ */
205
+ function promptCacheTokenClasses(input, promptCache) {
206
+ if (promptCache === void 0) return {};
207
+ const read = tokenCount(promptCache.readTokens);
208
+ const write = tokenCount(promptCache.writeTokens);
209
+ if (read === void 0 && write === void 0) return {};
210
+ if (input === void 0 || (read ?? 0) + (write ?? 0) > input) return { cacheBreakdownKnown: false };
211
+ if (read !== void 0 && write !== void 0) return {
212
+ freshInput: input - read - write,
213
+ cacheRead: read,
214
+ cacheWrite: write
215
+ };
216
+ return {
217
+ ...read !== void 0 ? { cacheRead: read } : {},
218
+ ...write !== void 0 ? { cacheWrite: write } : {},
219
+ cacheBreakdownKnown: false
220
+ };
221
+ }
222
+ function tokenCount(value) {
223
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
224
+ }
225
+ /**
226
+ * Add the observed subtotal into `acc`; token and cache incompleteness are sticky.
227
+ *
228
+ * A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO
229
+ * classes. Folding them in would hide the overflow: the accumulator's larger `input` can absorb a
230
+ * class total that overflowed the one delta that reported it, and `chargedTokens` would then credit
231
+ * at the aggregate a cache read it refuses at the record. That is the one way the charge could come
232
+ * out below the sum of the charges on the records that built it.
233
+ */
234
+ function addTokenUsage(acc, delta) {
235
+ acc.input += delta.input ?? 0;
236
+ acc.output += delta.output ?? 0;
237
+ if (delta.tokensKnown === false) acc.tokensKnown = false;
238
+ const input = delta.input ?? 0;
239
+ const fits = classifiedTotal(delta, delta.cacheRead ?? 0) <= input;
240
+ if (fits) {
241
+ if (delta.freshInput !== void 0) acc.freshInput = (acc.freshInput ?? 0) + delta.freshInput;
242
+ if (delta.cacheRead !== void 0) acc.cacheRead = (acc.cacheRead ?? 0) + delta.cacheRead;
243
+ if (delta.cacheWrite !== void 0) acc.cacheWrite = (acc.cacheWrite ?? 0) + delta.cacheWrite;
244
+ }
245
+ const classified = fits && delta.freshInput !== void 0 && delta.cacheRead !== void 0 && delta.cacheWrite !== void 0 && delta.freshInput + delta.cacheRead + delta.cacheWrite === input;
246
+ if (delta.cacheBreakdownKnown === false || input > 0 && !classified) acc.cacheBreakdownKnown = false;
247
+ }
248
+ /**
249
+ * Map `items` through `fn` with at most `limit` calls in flight at once,
250
+ * preserving input order in the result. On the first `fn` rejection no NEW
251
+ * items are picked up; already-in-flight calls are awaited, then the first
252
+ * error is rethrown. `limit` is clamped to ≥ 1.
253
+ *
254
+ * Used where a burst of provisioning (e.g. forking N child boxes) must respect
255
+ * the loop's concurrency bound instead of firing all N at once.
256
+ */
257
+ async function mapWithConcurrency(items, limit, fn) {
258
+ const bound = Math.max(1, Math.floor(limit));
259
+ const results = new Array(items.length);
260
+ let next = 0;
261
+ let failed = false;
262
+ const worker = async () => {
263
+ while (!failed) {
264
+ const i = next;
265
+ next += 1;
266
+ if (i >= items.length) return;
267
+ try {
268
+ results[i] = await fn(items[i], i);
269
+ } catch (err) {
270
+ failed = true;
271
+ throw err;
272
+ }
273
+ }
274
+ };
275
+ const workerCount = Math.min(bound, items.length);
276
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
277
+ return results;
278
+ }
279
+ //#endregion
280
+ export { zeroTokenUsage as _, hasCompleteCacheBreakdown as a, promptCacheTokenClasses as c, sleep as d, stringifySafe as f, withTimeout as g, usdEstimatedOf as h, deleteBoxSafe as i, randomSuffix as l, throwIfAborted as m, chargedTokens as n, isAbortError as o, throwAbort as p, cloneTokenUsage as r, mapWithConcurrency as s, addTokenUsage as t, randomUuid as u };
281
+
282
+ //# sourceMappingURL=util-C1bv6yog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util-C1bv6yog.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 { 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/** 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/** 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: Readonly<Record<string, number | string>> | 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":";;;;;;AAgBA,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,SAA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,4 @@
1
- import { A as verifyMaterializedWorkspace, C as assertNoGitIndirection, D as captureMaterializedWorkspace, E as candidateWorkspaceManifest, T as runCandidateGit, a as persistCandidateOutputArtifact, at as deepFreezeCandidate, ct as omitTopLevelDigest, k as verifyBytes, lt as sha256Bytes, nt as canonicalCandidateBytes, ot as embeddedCandidateArtifact, rt as canonicalCandidateDigest$1, st as immutableCandidateValue, w as readCandidateGitTreeFiles } from "./prepare-BXEtLOj9.js";
1
+ import { A as verifyMaterializedWorkspace, C as assertNoGitIndirection, D as captureMaterializedWorkspace, E as candidateWorkspaceManifest, T as runCandidateGit, a as persistCandidateOutputArtifact, at as deepFreezeCandidate, ct as omitTopLevelDigest, k as verifyBytes, lt as sha256Bytes, nt as canonicalCandidateBytes, ot as embeddedCandidateArtifact, rt as canonicalCandidateDigest$1, st as immutableCandidateValue, w as readCandidateGitTreeFiles } from "./prepare-Cv7NzRZl.js";
2
2
  import { agentCandidateBundleSchema } from "@tangle-network/agent-interface";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { dirname, isAbsolute, join, resolve, sep, win32 } from "node:path";
@@ -572,4 +572,4 @@ const typedArrayByteLengthGetter = requireTypedArrayGetter("byteLength");
572
572
  //#endregion
573
573
  export { sealAgentCandidateBundle as i, captureAgentCandidateWorkspaceFiles as n, createAgentCandidateWorkspacePort as r, captureAgentCandidateWorkspace as t };
574
574
 
575
- //# sourceMappingURL=workspace-archive-B5oJu5mZ.js.map
575
+ //# sourceMappingURL=workspace-archive-DFwzVhbk.js.map