@tangle-network/agent-runtime 1.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/{activation-CFS31SWI.d.ts → activation-BuK2H7qx.d.ts} +2 -2
  2. package/dist/{activation-BwoSqHCc.js → activation-ZQWz04u8.js} +4 -4
  3. package/dist/{activation-BwoSqHCc.js.map → activation-ZQWz04u8.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +4 -3
  6. package/dist/agent.js.map +1 -1
  7. package/dist/{bundle-DeDkJbsr.js → bundle-PDYNXIEf.js} +2 -2
  8. package/dist/{bundle-DeDkJbsr.js.map → bundle-PDYNXIEf.js.map} +1 -1
  9. package/dist/candidate-execution/index.js +4 -4
  10. package/dist/{coordination-manager-ewBF777W.js → coordination-manager-BZLp9qpE.js} +8 -363
  11. package/dist/coordination-manager-BZLp9qpE.js.map +1 -0
  12. package/dist/coordination-map-routing-CUvwHAtv.js +362 -0
  13. package/dist/coordination-map-routing-CUvwHAtv.js.map +1 -0
  14. package/dist/{delegate-BiuSfwBa.js → delegate-C-MUU6ML.js} +2 -2
  15. package/dist/{delegate-BiuSfwBa.js.map → delegate-C-MUU6ML.js.map} +1 -1
  16. package/dist/durable-file-CksURHlH.js +1 -0
  17. package/dist/durable-file-DstVeHcj.js +228 -0
  18. package/dist/durable-file-DstVeHcj.js.map +1 -0
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/durable.js +10 -8
  21. package/dist/durable.js.map +1 -1
  22. package/dist/{graph-D6FL1xze.js → graph-CM-6CV_K.js} +6 -5
  23. package/dist/{graph-D6FL1xze.js.map → graph-CM-6CV_K.js.map} +1 -1
  24. package/dist/graph-registry-72DlMnUl.js +585 -0
  25. package/dist/graph-registry-72DlMnUl.js.map +1 -0
  26. package/dist/graph-registry-CAX15LO6.js +1 -0
  27. package/dist/{improve-SiKDcz5_.js → improve-BuZ-I8DP.js} +9 -8
  28. package/dist/{improve-SiKDcz5_.js.map → improve-BuZ-I8DP.js.map} +1 -1
  29. package/dist/index.d.ts +3 -3
  30. package/dist/index.js +12 -11
  31. package/dist/index.js.map +1 -1
  32. package/dist/intelligence.d.ts +2 -2
  33. package/dist/intelligence.js +7 -7
  34. package/dist/{journal-store-BJPMUydp.js → journal-store-BpCOCDoO.js} +208 -635
  35. package/dist/journal-store-BpCOCDoO.js.map +1 -0
  36. package/dist/jsonl-file-BBP9Dz9w.js +429 -0
  37. package/dist/jsonl-file-BBP9Dz9w.js.map +1 -0
  38. package/dist/kernel.d.ts +1 -1
  39. package/dist/kernel.js +13 -12
  40. package/dist/{loop-runner-CqlcC0i4.js → loop-runner-BWD6v1rd.js} +2 -2
  41. package/dist/{loop-runner-CqlcC0i4.js.map → loop-runner-BWD6v1rd.js.map} +1 -1
  42. package/dist/{loop-runner-D9rcTNf2.d.ts → loop-runner-BpLTU_J4.d.ts} +2 -2
  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 +1 -1
  47. package/dist/mcp/index.js +5 -5
  48. package/dist/{prepare-XWwsOh8O.js → prepare-Bv6X2Wnx.js} +4 -4
  49. package/dist/{prepare-XWwsOh8O.js.map → prepare-Bv6X2Wnx.js.map} +1 -1
  50. package/dist/{profile-C01SQZKa.js → profile-Dir2A1_2.js} +2 -2
  51. package/dist/{profile-C01SQZKa.js.map → profile-Dir2A1_2.js.map} +1 -1
  52. package/dist/profiles.d.ts +1 -1
  53. package/dist/{provision-supervisor-DnwR0AyW.js → provision-supervisor-BWEeWag1.js} +8 -6
  54. package/dist/{provision-supervisor-DnwR0AyW.js.map → provision-supervisor-BWEeWag1.js.map} +1 -1
  55. package/dist/{run-cancellation-CoJRKvih.js → run-cancellation-Cpm-BIUu.js} +3 -2
  56. package/dist/{run-cancellation-CoJRKvih.js.map → run-cancellation-Cpm-BIUu.js.map} +1 -1
  57. package/dist/{runtime-DSYZeav8.js → runtime-Cnr3213E.js} +18 -15
  58. package/dist/{runtime-DSYZeav8.js.map → runtime-Cnr3213E.js.map} +1 -1
  59. package/dist/{sandbox-profile-compat-CXjozdWL.js → sandbox-profile-compat-DRiz9kME.js} +2 -2
  60. package/dist/{sandbox-profile-compat-CXjozdWL.js.map → sandbox-profile-compat-DRiz9kME.js.map} +1 -1
  61. package/dist/{search-executor-DcGAOrAh.js → search-executor-__X1VKnU.js} +5 -5
  62. package/dist/{search-executor-DcGAOrAh.js.map → search-executor-__X1VKnU.js.map} +1 -1
  63. package/dist/{server-SrPLb8w0.js → server-CntFSTpW.js} +4 -4
  64. package/dist/{server-SrPLb8w0.js.map → server-CntFSTpW.js.map} +1 -1
  65. package/dist/{structural-rollout-C_lg83-u.js → structural-rollout-s8W19Mws.js} +5 -5
  66. package/dist/{structural-rollout-C_lg83-u.js.map → structural-rollout-s8W19Mws.js.map} +1 -1
  67. package/dist/{supervise-BXw89Ajc.js → supervise-Cl0F57m9.js} +32 -647
  68. package/dist/supervise-Cl0F57m9.js.map +1 -0
  69. package/dist/{supervision-discovery-CewADdEs.js → supervision-discovery-C3t0Xw-T.js} +5 -158
  70. package/dist/supervision-discovery-C3t0Xw-T.js.map +1 -0
  71. package/dist/{supervisor-hHU3ZJnR.js → supervisor-L7u3pQ1j.js} +99 -150
  72. package/dist/supervisor-L7u3pQ1j.js.map +1 -0
  73. package/dist/task-queue-DbpZAp6C.js +49 -0
  74. package/dist/task-queue-DbpZAp6C.js.map +1 -0
  75. package/dist/task-queue.js +1 -49
  76. package/dist/testing.d.ts +1 -1
  77. package/dist/testing.js +13 -13
  78. package/dist/top-web-CkXPPXjI.js +1114 -0
  79. package/dist/top-web-CkXPPXjI.js.map +1 -0
  80. package/dist/tui/bin.js +4 -3
  81. package/dist/tui/bin.js.map +1 -1
  82. package/dist/tui/index.d.ts +22 -2
  83. package/dist/tui/index.js +3 -3
  84. package/dist/{types-DTHxh4X9.d.ts → types-BfnQq-_k.d.ts} +17 -21
  85. package/dist/{util-ebWMWzY0.js → util-BX20UJ9X.js} +2 -2
  86. package/dist/{util-ebWMWzY0.js.map → util-BX20UJ9X.js.map} +1 -1
  87. package/package.json +4 -4
  88. package/skills/agent-graphs/references/authoring.md +1 -0
  89. package/dist/coordination-manager-ewBF777W.js.map +0 -1
  90. package/dist/journal-store-BJPMUydp.js.map +0 -1
  91. package/dist/supervise-BXw89Ajc.js.map +0 -1
  92. package/dist/supervision-discovery-CewADdEs.js.map +0 -1
  93. package/dist/supervisor-hHU3ZJnR.js.map +0 -1
  94. package/dist/task-queue.js.map +0 -1
  95. package/dist/top-snapshot-DcV7VG4m.js +0 -520
  96. package/dist/top-snapshot-DcV7VG4m.js.map +0 -1
@@ -192,6 +192,8 @@ interface RetainedRunStartMaterial {
192
192
  };
193
193
  /** Reuse an environment whose retained ownership key is verified instead of creating one. */
194
194
  readonly existingEnvironmentId?: string;
195
+ /** Keep a newly created environment after dispatch fails so its original intent can replay. */
196
+ readonly preserveEnvironment?: boolean;
195
197
  readonly turn: RetainedRunTurnInput;
196
198
  /** Accepted destination to attach, without creating or replacing its environment. */
197
199
  readonly contextTransferReceipt?: ContextTransferReceipt;
@@ -212,6 +214,8 @@ interface StartRetainedRunOptions extends RetainedRunStartMaterial {
212
214
  readonly intent?: RetainedRunIntentAdmission;
213
215
  readonly onAdmission: RetainedRunAdmissionHook;
214
216
  readonly now?: () => number;
217
+ /** Directory whose `<runId>/observer.jsonl` (intent run id) receives admissions for agent-runtime-top. */
218
+ readonly journalRoot?: string;
215
219
  }
216
220
  /** A fresh retained session inside a provider environment that already exists. @stable */
217
221
  interface StartRetainedRunInEnvironmentOptions {
@@ -1687,6 +1691,8 @@ interface StartRetainedInteractiveRunOptions extends RetainedInteractiveStartMat
1687
1691
  readonly intent?: RetainedInteractiveIntentAdmission;
1688
1692
  readonly onAdmission: RetainedInteractiveAdmissionHook;
1689
1693
  readonly signal?: AbortSignal;
1694
+ /** Directory whose `<runId>/observer.jsonl` (intent run id) receives admissions for agent-runtime-top. */
1695
+ readonly journalRoot?: string;
1690
1696
  }
1691
1697
  /** Persist each exact interactive record before the runtime proceeds. @stable */
1692
1698
  type RetainedInteractiveAdmissionHook = (admission: RetainedInteractiveAdmission) => Promise<void>;
@@ -2791,18 +2797,17 @@ interface RunLocalHarnessOptions {
2791
2797
  harness: LocalHarness;
2792
2798
  /** Working directory for the subprocess (typically a worktree path). */
2793
2799
  cwd: string;
2794
- /** Prompt forwarded as the harness CLI's task argument. */
2800
+ /** Task prompt delivered through the harness's supported input transport. */
2795
2801
  taskPrompt: string;
2796
2802
  /**
2797
- * Pre-built command + args (e.g. from `harnessInvocation` so the full authored
2798
- * `AgentProfile` — systemPrompt + model — reaches the harness). When set it OVERRIDES the
2799
- * default prompt-only `buildArgs(taskPrompt)` path; `command` defaults to the harness's
2800
- * default binary when only `args` is supplied. When absent the legacy prompt-only shape
2801
- * is used unchanged.
2803
+ * Mapper invocation or custom argv; command defaults to the harness binary.
2804
+ * The mapper's exact composed `prompt` enables supported stdin transport.
2805
+ * Without an invocation, use the default prompt-only shape.
2802
2806
  */
2803
2807
  invocation?: {
2804
2808
  command?: string;
2805
2809
  args: ReadonlyArray<string>;
2810
+ prompt?: string;
2806
2811
  };
2807
2812
  /** Allow autonomous edits without an interactive approval gate, using whichever bypass argv the
2808
2813
  * harness declares. Use only when `cwd` is an isolated candidate worktree. */
@@ -2860,22 +2865,13 @@ interface LocalHarnessResult {
2860
2865
  evidence?: CodexExecutionEvidence;
2861
2866
  }
2862
2867
  /**
2863
- * Spawn a local coding harness CLI as a subprocess + collect its output.
2868
+ * Spawn a local harness, collect output and confirm process-tree cleanup.
2869
+ * The caller owns output parsing and workspace diffs.
2864
2870
  *
2865
- * NOT responsible for parsing the harness's output or extracting a diff —
2866
- * the in-process executor's `streamPrompt` orchestrates `git diff` against
2867
- * the worktree after this resolves. This function is intentionally narrow:
2868
- * spawn, wait, capture, return.
2871
+ * Spawn failures and signals already aborted before launch reject.
2869
2872
  *
2870
- * Fails loud — throws when:
2871
- * - `cwd` doesn't exist (subprocess emits ENOENT; surfaced as Error)
2872
- * - the harness binary is not on PATH (ENOENT)
2873
- * - the caller signal was already aborted before process launch
2874
- *
2875
- * Does NOT throw when:
2876
- * - the subprocess exits non-zero (`result.exitCode` carries the code)
2877
- * - a non-reproducible subprocess is aborted / timed out (`result.aborted` /
2878
- * `result.timedOut` carries the reason even when a TERM-aware child exits zero)
2873
+ * Ordinary nonzero exits and cancellation return the exit code and timeout/abort flags.
2874
+ * A failed prompt delivery rejects after the child is reaped.
2879
2875
  *
2880
2876
  * Reproducible Codex additionally requires a terminal usage event. If cancellation
2881
2877
  * prevents that event, this rejects with `CodexExecutionDiagnosticError` instead of
@@ -19640,4 +19636,4 @@ interface KnowledgeReadinessDecision {
19640
19636
  nonBlockingGapIds: string[];
19641
19637
  }
19642
19638
  export { NoWinnerError as $, NativeContextContinuationInput as $S, WaterfallCollector as $_, filterAuthoredAsserts as $a, NodeExecutionIdentity as $b, defaultAnalystInstruction as $c, SeatSelectionInput as $d, SupervisorProfile as $f, verdictFromJudgeScore as $g, DelegationRunContext as $h, SpawnJournal as $i, LeaderboardFlagSpec as $l, BridgeHarnessStore as $m, validateStoredGraph as $n, profileChatClient as $o, SpawnResourceBytes as $p, InteractiveWorkerOptions as $r, inlineSandboxClient as $s, createVerifierEnvironment as $t, observerRecordDigest as $u, QuestionEscalationRecord as $v, resolveHarnessTranscriptCapture as $x, AnalystKind as $y, TraceRootArtifact as A, LoopTeardownFailedPayload as AS, GroupOf as A_, ProfileRichnessThresholds as Aa, InMemorySpawnJournal as Ab, AuthoredStrategy as Ac, RUN_FORK_CORRELATION_KEYS as Ad, ReservationStage as Af, ResearchOutput as Ag, FeedbackStore as Ah, lookupGraph as Ai, Widen as Al, InboxMessage as Am, settledWorkerOut as An, openSandboxRun as Ao, serveCoordinationMcp as Ap, RemoteSupervisorCancelResult as Ar, createMcpEnvironment as As, AgentEnvironmentStatus as At, SuperviseGraphPursuitOptions as Au, WorktreeProfileMaterializationReceipt as Av, readWorkerProgress as Ax, PeerMailbox as Ay, Handle as B, SelectionReceipt as BS, pairwiseSignificance as B_, CheckSource as Ba, ValidationError as Bb, sampleThenRefine as Bc, createWorkerSlots as Bd, CoordinationVerbs as Bf, DelegationPersistenceError as Bg, FleetHandle as Bh, RollingDispatchOptions as Bi, PersonaContext as Bl, ROUTER_CLIENT_HEADER as Bm, WorkspaceRun as Bn, PrivateCasNamespaceObject as Bo, ContinuationPanel as Bp, ProvisionedSupervisor as Br, runBenchmark as Bs, CreateAgentEnvironmentInput$1 as Bt, PursuitNodePlatform as Bu, DecideGate as Bv, HarnessTranscriptEvidence as Bx, McpToolDescriptor as By, RuntimeFailureCause as C, StartRetainedRunOptions as CC, LoopIterationStartedPayload as CS, CodeModeToolContext as C_, ChatTransportTool as Ca, SpawnForestNode as Cb, SurfaceScore as Cc, dumbContinuationFailPrompt as Cd, BudgetPoolRestore as Cf, UiAuditorDelegationOutput as Cg, ToolLoopCallContext as Ch, graphCorpusSummary as Ci, ScopeWidenGate as Cl, SandboxSteeringOptions as Cm, readWorkerInteractiveBinding as Cn, Deliverable as Co, bestDelivered as Cp, readWorkerSteerRequests as Cr, assertTraceDerivedFindings as Cs, SuperviseProfileEntry as Ct, PursuitVersionChain as Cu, createRuntimeEventCollector as Cv, ActivityNote as Cx, PeerMailEnvelope as Cy, RetainedPendingCause as D, LoopResult as DS, createCodeModeTools as D_, createChatSessionStore as Da, replaySpawnTree as Db, runAgentic as Dc, naiveContinuationPrompt as Dd, ReservationHolder as Df, UiLens as Dg, ToolLoopMessageRecord as Dh, graphRunsFor as Di, TrajectoryReportOptions as Dl, AuthorityInboxMessage as Dm, WorkerEvidenceInput as Dn, SandboxRun as Do, CoordinationPublicAddress as Dp, workerInboxFileFromEventDir as Dr, observationFromRegistry as Ds, AgentEnvironmentEvent$1 as Dt, VersionJudge as Du, WorktreeCheckRunner as Dv, TeamProgress as Dx, PeerMailReadout as Dy, EvidencePendingEvent as E, LoopPlanPayload as ES, RunCodeModeOptions as E_, chatWorkerSeam as Ea, FileResultBlobStore as Eb, refine as Ec, kernelPromptRegistry as Ed, ReservationFloor as Ef, UiFindingSeverity as Eg, ToolLoopCompactionOptions as Eh, graphRegistry as Ei, TrajectoryReport as El, createSteerableSandboxSession as Em, VERIFY_TAIL_CHARS as En, OpenSandboxRunPromptOptions as Eo, CoordinationMcpHandle as Ep, supervisorRunsRoot as Er, registryScopeAnalyst as Es, AgentEnvironmentCapabilities$1 as Et, SettledPursuitVersion as Eu, InPlaceHarnessResult as Ev, ScopeProgressInput as Ex, PeerMailOutcome as Ey, ResourceLimit as F, MountManifestEntry as FS, PairwiseOptions as F_, supervisorInstructions as Fa, AgentEvalErrorCode as Fb, StrategyResult as Fc, AuthorizedSpawn as Fd, readRootStream as Ff, TraceContext as Fg, DetachedSessionDelegateOptions as Fh, taskShapeDigest as Fi, DefinePersona as Fl, SharedBoxPlacement as Fm, withUntrackedArtifacts as Fn, acquireSandbox as Fo, FileCoordinationLog as Fp, RemoteWorkerEvents as Fr, BenchmarkReport as Fs, AgentSessionStatus$1 as Ft, supervisePursuit as Fu, LeadMessage as Fv, RetainedInteractiveRunHandle as Fx, peerMailTools as Fy, Settled as G, RuntimeRunHandle as GS, AnytimeReport as G_, StructuralRolloutPolicy as Ga, SpawnModelSubstitution as Gb, HarvestFailure as Gc, isPreSpawnExecutorFailure as Gd, ResolveSupervisorTools as Gf, CoderTask as Gg, DetachedTurn as Gh, DesignerToolsEnv as Gi, ShapeContext as Gl, createAgentEnvironmentProviderRegistry as Gm, TrajectoryAnalysis as Gn, startRetainedRunInEnvironment as Go, PanelFinding as Gp, bestProfileFor as Gr, SuperviseOptionsForDispatch as Gs, PlacementInfo as Gt, PursuitRunProjection as Gu, RouteGate as Gv, captureHarnessTranscript as Gx, EventBus as Gy, NodeSnapshot as H, Validator as HS, renderLeaderboardMarkdown as H_, RepairStop as Ha, ExecutorContext as Hb, strategyAuthorSystemPrompt as Hc, WorkerSpawnRetryAttempt as Hd, DriveHarnessOwnerContext as Hf, FileDelegationStore as Hg, SiblingSandboxExecutorOptions as Hh, queueOf as Hi, RunPersonified as Hl, sharedWorkerClientName as Hm, jjWorkspace as Hn, reconnectRetainedRun as Ho, ContinuationPanelResult as Hp, provisionSupervisor as Hr, LoopDispatchOptions as Hs, ExecRequest as Ht, PursuitNodeTiming as Hu, GateRequest as Hv, HarnessTranscriptUnavailable as Hx, BusEvent as Hy, ResourceSpend as I, MountRecorder as IS, PairwiseVerdict as I_, CheckExecChannel as Ia, BackendTransportError as Ib, adaptiveRefine as Ic, AuthorizedSpawnContext as Id, readRootStreamReceipt as If, createPropagatingTraceEmitter as Ig, DetachedWinnerSelection as Ih, GraphTriggerBinding as Ii, DefinePersonaInput as Il, SharedBoxPlacementOptions as Im, GitWorkspaceOptions as In, S3PrivateCasStore as Io, PriorCoordination as Ip, connectRemoteSupervisor as Ir, BenchmarkStrategySummary as Is, AgentTurnResult$2 as It, RunReopen as Iu, ManagerReentryState as Iv, RetainedInteractiveStartMaterial as Ix, peerMailVerbNames as Iy, SpawnRejection as J, RuntimeRunRow as JS, anytimeReport as J_, canDisplace as Ja, ExecutorExecutionBinding as Jb, Observation as Jc, withWorkerSpawnRetry as Jd, SupervisorNodeContext as Jf, CompletionCheckContext as Jg, DelegationArgs as Jh, DelegateOptions as Ji, providerAsSandboxClient as Jl, ProviderLeafOut as Jm, parseWorkerToolTraceArtifact as Jn, reconnectRetainedInteractiveRun as Jo, DriverContractState as Jp, profileRegistry as Jr, superviseDispatch as Js, SandboxInstance$1 as Jt, projectPursuit as Ju, ChildQuestionInbox as Jv, HarnessTranscriptMetadata as Jx, WatchTraceOptions as Jy, SpawnOpts as K, RuntimeRunOptions as KS, AnytimeStrategySummary as K_, StructuralRolloutResult as Ka, AgentExecutionRef as Kb, HarvestReport as Kc, resolveWorkerSpawnRetry as Kd, SupervisorAgentDeps as Kf, CheckUnavailableError as Kg, RunDetachedTurnOptions as Kh, GraphDesignerExtraTools as Ki, ShapeRegistry as Kl, resolveAgentEnvironmentProvider as Km, analyzeTrace as Kn, ClaimRetainedInteractiveControlOptions as Ko, VerdictSummary as Kp, loadProfile as Kr, loopCampaignDispatch as Ks, ResourceRequest as Kt, PursuitRunTotals as Ku, RouteMatch as Kv, harnessTranscriptArtifact as Kx, PublishOptions as Ky, Spend as L, OutputAdapter as LS, ProfileKeyOf as L_, CheckOutcome as La, ConfigError as Lb, assertStrategyContract as Lc, SuperviseOptions as Ld, supervisorAgent as Lf, readTraceContextFromEnv as Lg, UiAuditorDelegate as Lh, DispatchReport as Li, LoopShape as Ll, SharedBoxStats as Lm, Shell as Ln, S3PrivateCasStoreOptions as Lo, CheckRead as Lp, connectRemoteSupervisorControl as Lr, BenchmarkTaskRow as Ls, AnalystFinding$1 as Lt, PursuitObserverDelivery as Lu, ManagerWake as Lv, StartRetainedInteractiveRunOptions as Lx, JsonRpcMessage as Ly, Budget as M, LoopTraceEmitter as MS, Leaderboard as M_, assessAuthoredProfile as Ma, Redactor as Mb, Strategy as Mc, superviseFleetCapabilities as Md, ReserveOptions as Mf, ResearchTask as Mg, CoderReview as Mh, recordGraphRun as Mi, WidenLineage as Ml, DEFAULT_SHARED_BOX_RESOURCES as Mm, CopyOptions as Mn, SandboxLineageHandle as Mo, CoordinationRejectReason as Mp, RemoteSupervisorReader as Mr, BenchmarkCell as Ms, AgentProfile$2 as Mt, SupervisePursuitOptions as Mu, AwaitWakeInput as Mv, RecoverRetainedInteractiveRunOptions as Mx, claimsAuthority as My, BudgetOverspend as N, LoopTraceEvent as NS, LeaderboardOptions as N_, defaultProfileRichnessThresholds as Na, defaultRedactor as Nb, StrategyArtifacts as Nc, superviseWithTestBrain as Nd, createBudgetPool as Nf, ResearcherProfileOptions as Ng, CoderReviewer as Nh, recordStoredGraphRun as Ni, WidenSpec as Nl, DEFAULT_SHARED_BOX_WORKERS as Nm, UntrackedCopyStats as Nn, createSandboxLineage as No, CoordinationDeliveryEvidence as Np, RemoteSupervisorSteerResult as Nr, BenchmarkConfig as Ns, AgentSession as Nt, SupervisedPursuitResult as Nu, CoordinationEvent as Nv, RetainedInteractiveAdmissionHook as Nx, createPeerMailbox as Ny, TRACE_ROOT_SCHEMA as O, LoopSandboxPlacement as OS, runCodeMode as O_, AuthoredProfile as Oa, FileSpawnJournal as Ob, sample as Oc, promptHandle as Od, ReservationRejection as Of, KnowledgeItem as Og, ToolLoopToolCall as Oh, listGraphRuns as Oi, Verify as Ol, Inbox as Om, closingWorkerNote as On, SandboxRunAbortError as Oo, CoordinationReadAccess as Op, writeWorkerSteer as Or, McpEndpoint as Os, AgentEnvironmentProvider$1 as Ot, VersionVerdict as Ou, WorktreeCommandResult as Ov, WorkerProgress as Ox, PeerMailRefusal as Oy, BudgetViolation as P, LoopWinner as PS, LeaderboardRow as P_, profileRichnessFinding as Pa, AgentEvalError$1 as Pb, StrategyCtx as Pc, workerFromBackend as Pd, RootStreamRecord as Pf, researcherProfile as Pg, DelegateRunCtx as Ph, storedGraphDigests as Pi, WinnerStrategy as Pl, SharedBoxCloseReceipt as Pm, copyUntrackedIntoClone as Pn, AcquireOptions as Po, CoordinationLog as Pp, RemoteSupervisorTree as Pr, BenchmarkLift as Ps, AgentSessionRef as Pt, superviseGraphPursuit as Pu, EventAcknowledgement as Pv, RetainedInteractiveEnvironmentInput as Px, isPeerMailEnvelope as Py, FleetYield as Q, NativeContextContinuationHandle as QS, renderAnytimeTable as Q_, defaultStructuralRolloutPolicy as Qa, MaterializedModelIdentity as Qb, ObserveOptions as Qc, SeatSelection as Qd, ManagerWakePolicy as Qf, mapExecutorResult as Qg, DelegationResumeTick as Qh, SpawnEvent as Qi, LeaderboardBenchmarkAdapter as Ql, ProviderPlacement as Qm, ValidateStoredGraphOptions as Qn, resolveSandboxClient as Qo, ResolvedSpawnResourcePath as Qp, InteractiveWorkerKeyInput as Qr, defaultSelectWinner as Qs, VerifierEnvironmentOptions as Qt, ObserverRecordKind as Qu, QuestionEscalationOutcome as Qv, RetainedHarnessTranscriptDescriptor as Qx, AnalystFindingEvent as Qy, SpendChannel as R, RunProvenance as RS, ScoreOf as R_, CheckRunContext as Ra, JudgeError as Rb, authorStrategy as Rc, SuperviseTestOptions as Rd, supervisorAgentWithTestBrain as Rf, DelegationTraceSpan as Rg, detachedSessionDelegate as Rh, DispatchStopReason as Ri, Outcome as Rl, SharedWorkerIdentity as Rm, Workspace as Rn, createS3PrivateCasStore as Ro, ContinuationAppend as Rp, ProvisionSupervisorConnection as Rr, Environment as Rs, CheckpointRef as Rt, PursuitCostProvenance as Ru, ToolOutcomeEvent as Rv, HarnessTranscriptArtifact as Rx, JsonRpcResponse as Ry, RuntimeStreamEvent as S, StartRetainedRunInEnvironmentOptions as SC, LoopIterationEndedPayload as SS, CodeModeTool as S_, ChatTransportExecutorOptions as Sa, SpawnForestMissingTree as Sb, StrategyShotResult as Sc, delegatesWorkerBriefPrompt as Sd, BudgetPool as Sf, UiAuditLensFilter as Sg, ToolSpec as Sh, digestOfGraph as Si, ScopeAnalyzeInput as Sl, DEFAULT_SANDBOX_STEERING_MAX_TURNS as Sm, attachWorker as Sn, strategyTournament as So, SupervisorFinalizer as Sp, readWorkerSteerAcknowledgement as Sr, RegistryAnalyzeProjection as Ss, SpawnRefusalCause as St, NextPursuitVersionInput as Su, SanitizedKnowledgeRequirement as Sv, ActivityLog as Sx, PEER_MAIL_WIRE_KEY as Sy, RuntimeFailureOwner as T, LoopPlanDescription as TS, CodeModeToolset as T_, chatTransportExecutor as Ta, loadSpawnForest as Tb, depthStrategy as Tc, formatPromptHandle as Td, LeakedReservation as Tf, UiFindingScreenshot as Tg, ToolLoopCompaction as Th, graphFromStored as Ti, TrajectoryNode as Tl, SteerableSandboxSession as Tm, NOTE_MAX_CHARS as Tn, OpenSandboxRunOptions as To, CoordinationControlAccess as Tp, supervisorRunDir as Tr, createScopeAnalyst as Ts, AgentEnvironment$1 as Tt, PursuitVersions as Tu, sanitizeKnowledgeReadinessReport as Tv, ExecutorProgress as Tx, PeerMailLimits as Ty, NodeStatus as U, RuntimeRunCompleteInput as US, renderLeaderboardSvg as U_, StructuralRolloutConfig as Ua, ExecutorFactory as Ub, HarvestCorpusOptions as Uc, WorkerSpawnRetryHooks as Ud, ObserveSupervisorNodeEvent as Uf, FileDelegationStoreOptions as Ug, createFleetWorkspaceExecutor as Uh, rollingDispatch as Ui, RunPersonifiedOptions as Ul, AgentEnvironmentProviderRef as Um, localShell as Un, recoverRetainedRun as Uo, ContinuationPolicy as Up, ProfileRegistryDir as Ur, LoopOptionsForDispatch as Us, ExecResult as Ut, PursuitNodeUsage as Uu, JsonScalar as Uv, HarnessTranscriptUnavailableReason as Ux, BusRecord as Uy, NodeId as V, ValidationCtx as VS, renderLeaderboardHtml as V_, CheckSourceCtx as Va, AgentSpec as Vb, strategyAuthorContract as Vc, ResolvedWorkerSpawnRetry as Vd, DriveHarness as Vf, DelegationStore as Vg, FleetWorkspaceExecutorOptions as Vh, freeSlots as Vi, PersonaExecutors as Vl, sharedBoxRefusal as Vm, gitWorkspace as Vn, PrivateCasNamespaceRetirement as Vo, ContinuationPanelInput as Vp, SupervisorCleanupReceipt as Vr, LoopCampaignDispatchOptions as Vs, CreateSandboxOptions$1 as Vt, PursuitNodeProjection as Vu, GateDecision as Vv, HarnessTranscriptFile as Vx, McpTransport as Vy, RetainedExecutionState as W, RuntimeRunCost as WS, renderPairwiseMarkdown as W_, StructuralRolloutMessage as Wa, ExecutorRegistry as Wb, HarvestError as Wc, WorkerSpawnRetryPolicy as Wd, ResolveDriveHarness as Wf, CoderOutput as Wg, createSiblingSandboxExecutor as Wh, DesignerRunGraphEnv as Wi, ShapeBudget as Wl, AgentEnvironmentProviderRegistry as Wm, runInWorkspace as Wn, startRetainedRun as Wo, ContinuationProfile as Wp, ProfileRunRecord as Wr, SuperviseDispatchOptions as Ws, ForkRequest as Wt, PursuitProjection as Wu, RouteFlow as Wv, ReadableEnvironment as Wx, BusStats as Wy, SubtreeSummary as X, startRuntimeRun as XS, bestSoFar as X_, composeCheckSources as Xa, ExecutorNodeContext as Xb, ObservationError as Xc, SuperviseRegistryTable as Xd, SupervisorToolDescriptor as Xf, ExecutorResultMapping as Xg, DelegationResumeContext as Xh, delegate as Xi, LeaderboardBenchScore as Xl, providerAsExecutor as Xm, createSupervisor as Xn, startRetainedInteractiveRun as Xo, DriverRetryPolicy as Xp, recordProfileRun as Xr, TERMINAL_DECISIONS as Xs, computeFindingId$1 as Xt, ObserverJournal as Xu, Question as Xv, HarnessTranscriptReadOptions as Xx, watchTrace as Xy, SubtreeResult as Y, RuntimeRunStatus as YS, areaUnderCurve as Y_, compareCheckOutcomes as Ya, ExecutorMaterialization as Yb, ObservationAnalysis as Yc, SuperviseRegistry as Yd, SupervisorNodeContextSeed as Yf, DeliverableSpec as Yg, DelegationRecord as Yh, defaultDelegateBudget as Yi, DefinedLeaderboard as Yl, ProviderPromptOptions as Ym, DEFAULT_MAX_DEPTH as Yn, recoverRetainedInteractiveRun as Yo, DriverReentry as Yp, profileRunsForName as Yr, LocalSandboxClientOptions as Ys, WorkspaceRequest as Yt, FileObserverJournal as Yu, EscalateQuestion as Yv, HarnessTranscriptReadLimits as Yx, defaultToolDetectors as Yy, TreeView as Z, NativeContextContinuationExecution as ZS, plateauLength as Z_, defaultExtractCandidate as Za, MaterializedExecutionIdentity as Zb, ObserveInput as Zc, SeatSegment as Zd, SupervisorToolInvocationContext as Zf, gateOnDeliverable as Zg, DelegationResumeDriver as Zh, ResultBlobStore as Zi, LeaderboardBenchTask as Zl, UnavailablePausePolicy as Zm, createRootHandle as Zn, ResolveSandboxClientOptions as Zo, ResolveSpawnResourcePathsResult as Zp, InteractiveWorkerEnvironment as Zr, TerminalDecision as Zs, makeFinding$1 as Zt, ObserverRecord as Zu, QuestionDecision as Zv, RetainedHarnessTranscriptCapture as Zx, AnalystAssignmentRecord as Zy, RunAgentTaskOptions as _, RetainedRunIntentAdmission as _C, ExecCtx as _S, harnessUsageIsEmpty as __, WorkerEventCursor as _a, SqlAdapter as _b, AgenticTool as _c, PromptHandle as _d, ParkedRun as _f, DelegationStatus as _g, extractLlmCallEvent as _h, GraphRunQuery as _i, PanelSpec as _l, CliWorktreeSeam as _m, WorktreePatchArtifact as _n, StrategyEvolutionConfig as _o, UNPROVEN_CONTINUITY as _p, WorkerSteerRequest as _r, pipeline as _s, PeerAuditAccess as _t, IsolatedCheckOptions as _u, RuntimeStreamEventCollector as _v, WorkerTraceUnavailableReason as _x, MapOnSettleRoute as _y, AgentKnowledgeProvider as a, RetainedInteractiveEnvironmentAdmission as aC, ProviderWorkspaceCaptureReceipt as aS, deterministicCompletion as a_, RootSegmentEntry as aa, AuthoredAnalystLimits as ab, LocalMcpMaterialization as ac, GraphNode as ad, RunContext as af, DelegateCodeConfig as ag, mcpSecretEnvMetadataKey as ah, ObservedSessionFacts as ai, CorpusFilter as al, McpServerOptions as am, SurfaceReader as an, structuralRollout as ao, StopRule as ap, SearchSpec as ar, createPrivateCasArtifactPort as as, DriverAttemptRecord as at, defineLeaderboard as au, SandboxEvidenceContext as av, ExecutorAccounting as ax, QuestionUrgency as ay, RuntimeSession as b, RetainedRunStartMaterial as bC, LoopEndedPayload as bS, decodeHarnessUsage as b_, ChatCompletionsTransport as ba, SpawnForestEvent as bb, RunAgenticOptions as bc, analyzesFindingsReportPrompt as bd, RunParkingRecord as bf, FeedbackRefersTo as bg, RouterTransportConfig as bh, StoredGraph as bi, RenderCorpusToInstructionsOptions as bl, RouterToolsSeam as bm, WorkerInteractiveBinding as bn, TournamentRow as bo, FinalizeContext as bp, legacySupervisorRunDir as br, widen as bs, SpawnPreflightContext as bt, JudgedPursuitVersion as bu, RuntimeTelemetryOptions as bv, TraceSource as bx, AUTHORITY_MARKERS as by, AgentTaskContext as c, RetainedRunAdmission as cC, ProviderWorkspaceRetentionContext as cS, CodexForkBoundary as c_, Supervisor as ca, LocalHarnessResult as cb, McpSpawnFault as cc, RunGraphOptions as cd, createInMemoryRunContext as cf, DelegateUiAuditArgs as cg, secretEnvOfMcpServer as ch, graphRouteWhenSchema as ci, EqualKOnCostOptions as cl, DelegateHandlerOptions as cm, fsSurfaceReader as cn, AgentTurnInput$1 as co, noProgressFor as cp, assertSearchSpec as cr, definePersona as cs, DriverFailureClass as ct, DeclaredCheckStateCapture as cu, OtelAttribute as cv, ExecutorResult as cx, AuthorizedDownMessage as cy, AgentTaskStatus as d, RetainedRunCancellation as dC, ExecutorToolCall as dS, CodexRolloutStoreReader as d_, ReenteredWorkers as da, LOCAL_HARNESSES as db, connectStdioMcp as dc, runGraph as dd, SupervisorSpanOptions as df, DelegationError as dg, SandboxToolPartState as dh, LoadGraphFileOptions as di, FanoutSynthesis as dl, createExecutorRegistry as dm, analystsFromRegistry as dn, StreamAgentTurnOptions as do, RunCancellation as dp, searchSpecDigest as dr, InMemoryCorpus as ds, CoordinationStats as dt, declaredCheckDeliverable as du, OtelExporter as dv, HeldForContinuation as dx, DownMessageAuthorizationInput as dy, ReconnectRetainedRunOptions as eC, retainHarnessTranscript as eS, CompletionAnalyst as e_, TraceRootReceipt as ea, AnalystLensOutput as eb, InProcessOnPrompt as ec, AgentGraph as ed, SeatStage as ef, DelegationTaskQueue as eg, BridgeModelCredential as eh, InteractiveWorkerResult as ei, observe as el, SpawnResourceRead as em, BoxSurfaceReaderOptions as en, modelAuthoredChecks as eo, AllWorkersStalledOptions as ep, FencedSqlRunContext as er, profileOptimizerModelCall as es, ProviderModelAttemptEvidence as et, LeaderboardIterationInfo as eu, WaterfallReport as ev, ProfileMaterializationReceipt as ex, QuestionEscalationTarget as ey, BackendErrorDetail as f, RetainedRunDispatchedAdmission as fC, TokenUsageProvenance as fS, CodexRolloutStoreRef as f_, ResumedKeyState as fa, LocalHarness as fb, materializeLocalMcp as fc, runGraphWithTestBrain as fd, SupervisorSpanOutcome as ff, DelegationFeedbackSnapshot as fg, createSandboxToolPartState as fh, LoadedGraphFile as fi, FanoutWinnerSelector as fl, ExecutorConfig as fm, failuresAnalyst as fn, collectAgentTurn as fo, cancelRun as fp, settledToIteration as fr, renderCorpusToInstructions as fs, CoordinationTools as ft, declaredCheckDigest as fu, OtelSpan as fv, HeldRelease as fx, DownMessageDeliveryAttempt as fy, OpenAIChatToolChoice as g, RetainedRunHandle as gC, Driver as gS, createCodexRolloutStoreReader as g_, WidenGate as ga, openSqlRunStore as gb, AgenticTask as gc, GraphRouteError as gd, DeadlineCheckIn as gf, DelegationResultPayload as gg, SandboxUsageLedger as gh, GraphRegistryDir as gi, PanelJudge as gl, CliWorktreeBridgeSeam as gm, WorktreeCliExecutorOptions as gn, EvolutionStrategy as go, ReentryTaskInput as gp, WorkerSteerAcknowledgement as gr, panel as gs, MakeWorkerAgent as gt, IsolatedCheckBoxEvidence as gu, RuntimeEventCollector as gv, WorkerTraceEvidence as gx, MapItemFailurePolicy as gy, OpenAIChatTool as h, RetainedRunEventOptions as hC, DefaultVerdict$2 as hS, addHarnessUsage as h_, UnconfirmedTeardown as ha, SqlRunOwnershipError as hb, AgenticSurface as hc, defaultEdgeTraversalCap as hd, WorkerTraceResolver as hf, DelegationProgress as hg, SandboxServedBackend as hh, GraphCorpusSummary as hi, Panel as hl, CliSeam as hm, worktreeFanout as hn, EvolutionReport as ho, ReentryContinuity as hp, WorkerCancellation as hr, loopUntil as hs, GraphSubtasks as ht, IsolatedCheckBox as hu, loopEventToOtelSpan as hv, WorkerInteractiveUnavailableReason as hx, WorkerResumeContext as hy, AgentExecutionBackend as i, RetainedInteractiveAdmission as iC, ProviderWorkspaceCaptureProvenance as iS, completionAuthorizes as i_, RootSegment as ia, AuthoredAnalystDefinition as ib, HttpMcpServerSpec as ic, GraphEdgeCapError as id, InMemoryRunContextOptions as if, DelegateCodeArgs as ig, envKeyProvider as ih, GraphSessionObservationOptions as ii, Corpus as il, McpServer as im, SurfaceReadOutcome as in, selectBestIndex as io, StopDecision as ip, SEARCH_SPEC_CORRELATION_KEY as ir, PrivateCasOptions as is, SupervisedResult as it, LeaderboardSpec as iu, runAgentRounds as iv, Executor as ix, QuestionRecord as iy, TraceSummary as j, LoopTokenUsage as jS, Interval as j_, asAuthoredProfile as ja, contentAddress as jb, ShotSpec as jc, supervise as jd, ReservationTicket as jf, ResearchSource as jg, CoderDelegate as jh, pickBestGraph as ji, WidenDecision as jl, PeerInboxMessage as jm, spendFromUsageEvents as jn, SandboxLineage as jo, CoordinationHttpAudit as jp, RemoteSupervisorControl as jr, sanitizeMcpToolSchema as js, AgentEnvironmentSummary as jt, SupervisePursuitError as ju, GitRunner as jv, ReconnectRetainedInteractiveRunOptions as jx, PeerMailboxOptions as jy, TRACE_SUMMARY_SCHEMA as k, LoopStartedPayload as kS, AxisScoresOf as k_, ProfileRichness as ka, InMemoryResultBlobStore as kb, AuthorStrategyOptions as kc, PursuitFork as kd, ReservationShortfall as kf, KnowledgeUpdate as kg, FeedbackEvent as kh, loadGraph as ki, VerifySpec as kl, InboxLease as km, composeWorkerEvidence as kn, TurnResult as ko, CoordinationTransportOptions as kp, RemoteSupervisorAgent as kr, McpEnvironmentOptions as ks, AgentEnvironmentQuery as kt, assertPursuitVersions as ku, WorktreeHarnessResult as kv, createActivityLog as kx, PeerMailSendInput as ky, AgentTaskRunResult as l, RetainedRunAdmissionHook as lC, ProviderWorkspaceRetentionPort as lS, CodexRolloutIdentity as l_, SupervisorOpts as la, RunLocalHarnessOptions as lb, StdioMcpConnection as lc, RunGraphTestOptions as ld, withRunContext as lf, DelegateUiAuditConfig as lg, SandboxLeafOut as lh, GraphFileResolutionError as li, EqualKVerdict as ll, DelegateResult as lm, harvestSurfaceDiffs as ln, AgentTurnUsage as lo, plateau as lp, compileSearchSpec as lr, runPersonified as ls, DriverRepromptRefusal as lt, assertDeclaredCheck as lu, OtelExportConfig as lv, ExecutorTeardownWarning as lx, ContinuationInstruction as ly, OpenAIChatResponseFormat as m, RetainedRunEnvironmentAdmission as mC, AgentRunSpec as mS, CodexStoreDelta as m_, Scope as ma, CodexExecutionPolicy as mb, AgenticRunResult as mc, GraphFromStoredOptions as md, createSupervisorSpanRecorder as mf, DelegationHistoryEntry as mg, mapSandboxToolEvent as mh, GraphCorpusGroup as mi, LoopUntilState as ml, CliInPlaceSeam as mm, WorktreeFanoutOptions as mn, EvolutionAuthor as mo, readRunCancellation as mp, ScopeArgs as mr, flatWidenGate as ms, GraphSubtaskPreparation as mt, readDeclaredCheck as mu, createOtelExporter as mv, WorkerInteractiveSession as mx, DownMessageEvent as my, AgentBackendContext as n, RecoverRetainedRunOptions as nC, ProviderNativeCapturePhase as nS, CompletionPolicy as n_, RecursiveReservationPolicy as na, AnalystRunContext as nb, InProcessSandboxClientOptions as nc, EdgeTraversal as nd, subscriptionUsageLimitSignal as nf, SubmitInput as ng, KeyProvider as nh, InPlaceCliExecutorOptions as ni, AssertTraceDerivedFindings as nl, environmentReader as nm, SurfaceDiff as nn, resolveEntrySymbol as no, PlateauOptions as np, createFencedSqlRunContext as nr, PrivateCasDurableStore as ns, RootProviderModelEvidence as nt, LeaderboardScenario as nu, createWaterfallCollector as nv, UnknownMaterializationReason as nx, QuestionOption as ny, AgentRuntimeEvent as o, RetainedInteractiveIntentAdmission as oC, ProviderWorkspaceCaptureResult as oS, sentinelCompletion as o_, RootSignal as oa, DefinedAnalystRecord as ob, MaterializeLocalMcpOptions as oc, GraphResult as od, RunContextLease as of, DelegateResearchArgs as og, resolveMcpServerLaunch as oh, graphFromSessionFacts as oi, CorpusRecord as ol, createMcpServer as om, WatchedSurface as on, visibleCheckScore as oo, allWorkersStalled as op, SearchSpecInputs as or, equalKOnCost as os, DriverAttemptStop as ot, DeclaredCheck as ou, SandboxEvidenceReceipt as ov, ExecutorCancellation as ox, questionEscalationTargets as oy, KnowledgeReadinessDecision as p, RetainedRunEffect as pC, UsageEvent as pS, CodexRolloutTurn as p_, ResumedWork as pa, CodexTokenUsage as pb, AgenticOptions as pc, GraphCommandCheck as pd, SupervisorSpanRecorder as pf, DelegationHistoryArgs as pg, mapSandboxEvent as ph, loadGraphFile as pi, LoopUntilSpec as pl, createExecutor as pm, AuthoredHarness as pn, streamAgentTurn as po, readRunCancelRequest as pp, createScope as pr, fanout as ps, CoordinationToolsOptions as pt, declaredCheckJudge as pu, buildLoopOtelSpans as pv, Runtime as px, DownMessageDeliveryOutcome as py, SpawnPrior as q, RuntimeRunPersistenceAdapter as qS, AnytimeTaskCurve as q_, VisibleCheck as qa, ExecutionBindingReceipt as qb, harvestCorpus as qc, retryPreSpawnRefusals as qd, SupervisorAgentTestDeps as qf, CheckVerdict as qg, runDetachedTurn as qh, graphDesignerExtraTools as qi, ProviderAsSandboxClientOptions as ql, ProviderExecutorOptions as qm, WorkerToolTraceArtifact as qn, claimRetainedInteractiveControl as qo, admitContinuationPolicy as qp, pickBestProfile as qr, loopDispatch as qs, SandboxEvent$1 as qt, PursuitStatus as qu, RouteWhen as qv, persistHarnessTranscript as qx, createEventBus as qy, AgentBackendInput as r, RecoverRetainedRunResult as rC, ProviderWorkspaceAttemptProvenance as rS, CompletionVerdict as r_, RootHandle as ra, AnalyzeOnSettleRoute as rb, inProcessSandboxClient as rc, GraphEdge as rd, InMemoryRunContext as rf, SubmitOutput as rg, ResolvedMcpServerLaunch as rh, createInPlaceCliExecutor as ri, CombinatorShape as rl, resolveSpawnResourcePaths as rm, SurfaceReadBox as rn, sandboxCheckRunner as ro, ProgressView as rp, CompiledSearchSpec as rr, PrivateCasOffloadReport as rs, RootStreamReceipt as rt, LeaderboardScore as ru, RunAgentRoundsOptions as rv, EnvironmentTeardownReceipt as rx, QuestionPolicy as ry, AgentRuntimeEventSink as s, RetainedInteractiveStartedAdmission as sC, ProviderWorkspaceEntryMetadata as sS, stopSentinel as s_, SteerableRootHandle as sa, CodexExecutionEvidence as sb, McpListedTool as sc, GraphTopology as sd, createFileRunContext as sf, DelegateResearchConfig as sg, resolveSecretEnv as sh, graphFileSchema as si, EqualKArm as sl, DelegateError as sm, boxSurfaceReader as sn, AgentTurnBackend as so, anyOf as sp, SearchSpecOwnedOption as sr, trajectoryReport as ss, DriverContinuationRecord as st, DeclaredCheckPlacement as su, SandboxEvidenceRetentionPort as sv, ExecutorCancellationRequest as sx, AuthorizeDownMessage as sy, AgentAdapter as t, RecoverRetainedRunIntentOptions as tC, ProviderCheckpointCaptureContext as tS, CompletionEvidence as t_, WorkspaceCheckpointMarker as ta, AnalystRegistry$1 as tb, InProcessPromptCtx as tc, EdgeDeliveryOutcome as td, SelectSeat as tf, DelegationTaskQueueOptions as tg, BridgeSeam as th, workerFromInteractiveProvider as ti, renderReport as tl, SpawnResourceReader as tm, HarvestSurfaceDiffsOptions as tn, officialChecksFromMeta as to, NoProgressForOptions as tp, SqlRunContextOptions as tr, PrivateCasArtifactPort as ts, ProviderModelExecutionEvidence as tt, LeaderboardRunContext as tu, WaterfallSpan as tv, RootMaterialization as tx, QuestionLevel as ty, AgentTaskSpec as u, RetainedRunCancelOptions as uC, ExecutorProgressEvent as uS, CodexRolloutSession as u_, Agent as ua, runLocalHarness as ub, StdioMcpServerSpec as uc, TraversalContinuity as ud, SupervisorSpanAttributes as uf, DelegateUiAuditRoute as ug, SandboxOutputMarker as uh, GraphFileSeat as ui, FanoutOptions as ul, createDelegateHandler as um, AnalystAuthoring as un, CollectedAgentTurn as uo, RunCancelRequest as up, searchPresets as ur, FileCorpus as us, BlockedToolReport as ut, checkProgramDigest as uu, OtelExportStats as uv, HeldEnvironment as ux, ContinuityMode as uy, RunAgentTaskStreamOptions as v, RetainedRunReplayPoint as vC, Iteration as vS, readCodexRolloutSession as v_, WorkerEventEntry as va, materializeTreeView as vb, ArtifactHandle as vc, PromptRegistry as vd, RunParkedError as vf, DelegationStatusResult as vg, sumSandboxUsage as vh, GraphRunRecord as vi, PanelVerdict as vl, ProviderSeam as vm, createWorktreeCliExecutor as vn, StrategyTournament as vo, composeReentryTask as vp, WriteWorkerSteerOptions as vr, selectValidWinner as vs, SettledWorker as vt, IsolatedCheckResult as vu, RuntimeStreamEventSink as vv, SessionMessageLike as vx, MapSpawnMarker as vy, RuntimeFailureCode as w, LoopLineageOptions as wS, CodeModeToolsOptions as w_, ChatWorkerSeamOptions as wa, SpawnForestTree as wb, breadthStrategy as wc, dumbContinuationPassPrompt as wd, BudgetReadout as wf, UiFinding as wg, ToolLoopChat as wh, graphDigest as wi, SteerContext as wl, SteerableSandboxArgs as wm, EVIDENCE_MAX_CHARS as wn, OpenSandboxRunBeforeStartContext as wo, CoordinationAuthentication as wp, safeWorkerFile as wr, buildSteerContext as ws, WorkerSpawnContext as wt, PursuitVersionStop as wu, createRuntimeStreamEventCollector as wv, DEFAULT_STALL_AFTER_MS as wx, PeerMailEvent as wy, RuntimeSessionStore as x, RetainedRunTurnInput as xC, LoopIterationDispatchPayload as xS, CodeModeStore as x_, ChatSessionStore as xa, SpawnForestInDoubtNode as xb, StrategyMessage as xc, createPromptRegistry as xd, readRunParking as xf, ResearchOutputShape as xg, RouterRouting as xh, StoredGraphInput as xi, ScopeAnalyst as xl, SandboxSeam as xm, WorkerInteractiveProviderSource as xn, runStrategyEvolution as xo, FinalizerSettled as xp, readWorkerCancellation as xr, CreateScopeAnalystOptions as xs, SpawnRefusal as xt, NextPursuitVersion as xu, SanitizedKnowledgeReadinessReport as xv, createPushTraceSource as xx, DEFAULT_PEER_MAIL_LIMITS as xy, RuntimeCanonicalStreamEvent as y, RetainedRunSnapshot as yC, LoopDecisionPayload as yS, HarnessUsage as y_, WorkerEventPage as ya, SpawnForest as yb, CorpusReadbackOptions as yc, RegisteredPrompt as yd, RunParkingPolicy as yf, FeedbackRating as yg, RouterResponseReceipt as yh, GraphSelection as yi, PipelineStage as yl, RouterSeam as ym, AttachWorkerOptions as yn, TournamentCell as yo, DeliveredOutput as yp, cancelWorker as yr, verify as ys, SpawnPreflight as yt, runIsolatedCheck as yu, RuntimeStreamEventSummary as yv, ToolStepInput as yx, MapTraversalEvent as yy, SpendGap as z, SandboxClient as zS, leaderboard as z_, CheckRunner as za, NotFoundError as zb, defineStrategy as zc, WorkerSlots as zd, CoordinationToolFace as zf, composeLoopTraceEmitters as zg, DelegationExecutor as zh, DispatchUnit as zi, Persona as zl, sharedBoxPlacement as zm, WorkspaceCommit as zn, PrivateCasNamespaceInventory as zo, ContinuationEntry as zp, ProvisionSupervisorRequest as zr, printBenchmarkReport as zs, CheckpointRequest as zt, PursuitNodeCost as zu, WorkerWatchOptions as zv, HarnessTranscriptCapture as zx, McpToolAnnotations as zy };
19643
- //# sourceMappingURL=types-DTHxh4X9.d.ts.map
19639
+ //# sourceMappingURL=types-BfnQq-_k.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { m as ValidationError } from "./errors-AzSuGI23.js";
2
- import { runTaskQueue } from "./task-queue.js";
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;
5
5
  const DEFAULT_SUCCESSFUL_SHUTDOWN_MS = 5e3;
@@ -621,4 +621,4 @@ function fnv1a32Hex(text) {
621
621
  }
622
622
  export { ACCEPTED_RESULT_GRACE_MS as A, teardownExecutor as B, withTimeout as C, assertResources as D, addResourceSpend as E, armDeadlineTimer as F, boundedChildDeadlineAt as I, checkInIdleMs as L, DEADLINE_CHECK_IN_MESSAGE as M, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as N, resourceTelemetry as O, ROOT_DEADLINE_REASON as P, isDeadlineAbortReason as R, unmeteredSpend as S, zeroTokenUsage as T, teardownSurfaces as V, roundBoxMinutes as _, cloneSpend as a, throwAbort as b, errorMessage as c, isAbortError as d, isAsyncIterable as f, randomUuid as g, randomSuffix as h, chargedTokens as i, CHILD_DEADLINE_REASON as j, withBudgetResources as k, fnv1a32Hex as l, promptCacheTokenClasses as m, addSpend as n, cloneTokenUsage as o, mapWithConcurrency as p, addTokenUsage as r, deleteBoxSafe as s, abortError as t, hasCompleteCacheBreakdown as u, sleep as v, zeroSpend as w, throwIfAborted as x, stringifySafe as y, singleFlightTeardown as z };
623
623
 
624
- //# sourceMappingURL=util-ebWMWzY0.js.map
624
+ //# sourceMappingURL=util-BX20UJ9X.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"util-ebWMWzY0.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/**\n * How long an abort waits for a manager whose result was already accepted to end the turn that\n * submitted it. Acceptance asks the turn's harness to stop; what remains is the turn's final\n * session copy (a bounded native capture), metering its usage and committing its result. Its\n * workspace capture is not part of it: the manager's owner runs that after the result.\n */\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 { 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/**\n * The spend of work that HAPPENED and reported no usage receipt.\n *\n * Not the same value as {@link zeroSpend} even though both carry `{0,0}` tokens and `$0`. A bare\n * zero asserts a MEASUREMENT — \"this ran and cost nothing\" — and every consumer downstream reads it\n * that way: the pool keeps reporting `readout().tokensKnown === true`, the journal totals stay\n * clean, the OTEL span records a priced zero, and a caller's token-denominated ceiling can never\n * fire no matter how much the work really burned. A ceiling that cannot fire is worse than no\n * ceiling, because it reads as protection.\n *\n * `tokensKnown` is the marker the substrate already threads end to end for exactly this case\n * (`budget.ts`, `otel-spans.ts`, `spawn-journal.ts`, `supervisor.ts`): the work is recorded, the\n * zero is labelled a floor rather than a total, and every rollup that touches it reports its\n * balance as a ceiling rather than a measurement. Use this — never a bare zero — whenever a runtime\n * cannot see what its worker spent.\n *\n * The same rule applies to dollars. A dollar-capped run must refuse an executor whose billed spend\n * is unknowable; `budgetExempt` does not authorize Runtime to relabel unknown spend as a measured\n * zero. Callers that require dollar accounting must use a backend with a trusted billing receipt.\n */\nexport function unmeteredSpend(ms: number): Spend {\n return {\n iterations: 0,\n tokens: zeroTokenUsage(),\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms,\n }\n}\n\n/** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */\nexport function cloneSpend(spend: Spend): Spend {\n return {\n ...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 }\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 }\n}\n\n/**\n * Fold the token-provenance channel across spends, as a field to spread.\n *\n * Returns nothing when no contributor stated one, because ABSENT already means \"the executor's own\n * live stream\", which is what every path reported before a harness store was readable. A\n * contributor that stated one and a contributor that did not therefore disagree, and the sum is\n * `'mixed'` — the honest answer for a tree whose spend came from two kinds of receipt.\n */\nfunction tokensProvenanceOf(...spends: ReadonlyArray<Spend>): {\n tokensProvenance?: TokenUsageProvenance\n} {\n let folded: TokenUsageProvenance | undefined\n let sawStated = false\n for (const spend of spends) {\n const stated = spend.tokensProvenance ?? 'stream-receipt'\n if (spend.tokensProvenance !== undefined) sawStated = true\n folded = folded === undefined || folded === stated ? stated : 'mixed'\n }\n return !sawStated || folded === undefined || folded === 'stream-receipt'\n ? {}\n : { tokensProvenance: folded }\n}\n\n/**\n * Fold the platform box-time channel across spends, as a field to spread.\n *\n * Returns nothing when no input carried the channel, so a fold over router or cli-bridge work —\n * which runs no box at all — never gains a `boxMinutesProvenance: 'uncaptured'` that would claim\n * a box ran and went unmetered.\n *\n * Three rules, one per field:\n * - `boxMinutes` sums the numbers that are present, and stays ABSENT when none is. A missing\n * measurement never enters the sum as a zero.\n * - `boxMinutesKnown` is sticky-false, like `tokensKnown`: one contributor that could not state\n * its box time makes the whole sum a floor.\n * - `boxMinutesProvenance` degrades. `'observed'` survives only when every contributor that\n * carried a number was observed; one derived number makes the sum `'estimated'`; no number at\n * all is `'uncaptured'`.\n */\nfunction boxMinutesOf(...spends: ReadonlyArray<Spend>): {\n boxMinutes?: number\n boxMinutesKnown?: boolean\n boxMinutesProvenance?: 'observed' | 'estimated' | 'uncaptured'\n} {\n const present = spends.filter((spend) => spend.boxMinutesProvenance !== undefined)\n if (present.length === 0) return {}\n let minutes = 0\n let sawNumber = false\n let known = true\n let observedOnly = true\n for (const spend of present) {\n if (typeof spend.boxMinutes === 'number' && Number.isFinite(spend.boxMinutes)) {\n minutes += spend.boxMinutes\n sawNumber = true\n if (spend.boxMinutesProvenance !== 'observed') observedOnly = false\n }\n if (spend.boxMinutesKnown !== true) known = false\n }\n return {\n ...(sawNumber ? { boxMinutes: roundBoxMinutes(minutes) } : {}),\n boxMinutesKnown: known,\n boxMinutesProvenance: sawNumber ? (observedOnly ? 'observed' : 'estimated') : 'uncaptured',\n }\n}\n\n/**\n * Box minutes at four decimals — a tenth of a second.\n *\n * Fine enough that a box alive for two seconds reports `0.0333` instead of a zero that would read\n * as a measured free box, and coarse enough that summing floats does not print\n * `1.5000000000000002`.\n */\nexport function roundBoxMinutes(minutes: number): number {\n return Number(minutes.toFixed(4))\n}\n\n/** Copy a token subtotal without dropping optional provider cache telemetry. */\nexport function cloneTokenUsage(usage: LoopTokenUsage): LoopTokenUsage {\n const cacheBreakdownUnknown =\n usage.cacheBreakdownKnown === false || (usage.input > 0 && !hasClassifiedCacheBreakdown(usage))\n return {\n input: usage.input,\n output: usage.output,\n ...(usage.tokensKnown === false ? { tokensKnown: false as const } : {}),\n ...(usage.freshInput !== undefined ? { freshInput: usage.freshInput } : {}),\n ...(usage.cacheRead !== undefined ? { cacheRead: usage.cacheRead } : {}),\n ...(usage.cacheWrite !== undefined ? { cacheWrite: usage.cacheWrite } : {}),\n ...(cacheBreakdownUnknown ? { cacheBreakdownKnown: false as const } : {}),\n }\n}\n\n/** True only when every positive prompt token has a consistent cache classification. */\nexport function hasCompleteCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.cacheBreakdownKnown === false) return false\n return hasClassifiedCacheBreakdown(usage)\n}\n\nfunction hasClassifiedCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.input === 0) return true\n if (\n usage.freshInput === undefined ||\n usage.cacheRead === undefined ||\n usage.cacheWrite === undefined\n ) {\n return false\n }\n return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input\n}\n\n/**\n * The token charge for one observation: every token counted ONCE, at the moment it first enters\n * the context — `input − cacheRead + output`.\n *\n * `input` is a rolled-up prompt total that re-counts a cached prefix on every turn that reads it,\n * so charging `input` makes a 100K prefix read 40 times cost 4.1M for content authored once. A\n * cache read is content that was already charged when it was written, so it is the one class the\n * charge subtracts. Under a complete split the result is exactly `freshInput + cacheWrite`. No\n * price weight is involved: this counts work, and money is a separate channel.\n *\n * The subtraction form is what makes the charge ADDITIVE. `input` and `cacheRead` both accumulate\n * through `addTokenUsage`, so the charge on an aggregate equals the sum of the charges on the\n * records that built it — including an aggregate that mixes classified and unclassified turns,\n * where the unclassified remainder is charged in full and only the reported cache reads are\n * credited. A form that read `freshInput + cacheWrite` directly loses that: one unclassified turn\n * would drop the whole aggregate to `input + output` and over-charge every classified turn with it.\n *\n * The one arithmetic guarantee: a set of classes that does not FIT inside the prompt total it\n * partitions credits nothing, so the charge is never below `output` and a class that overflows its\n * own total buys no tokens. It is not a guarantee against a provider that reports a cache read it\n * never served — that provider can under-report `input` just as easily, and the token channel is an\n * accounting unit, not a trust boundary. Prompt tokens the provider left unclassified are charged\n * in full, so a spend with no readable split charges an upper bound on newly-presented work rather\n * than a measurement, and every caller that enforces a ceiling must report the difference\n * (`BudgetPool` does it through `readout().cacheBreakdownKnown`).\n */\nexport function chargedTokens(usage: LoopTokenUsage): number {\n return usage.input - creditedCacheRead(usage) + usage.output\n}\n\n/** `cacheRead` if the reported classes fit inside `input`, else nothing. */\nfunction creditedCacheRead(usage: LoopTokenUsage): number {\n const { cacheRead } = usage\n if (cacheRead === undefined) return 0\n return classifiedTotal(usage, cacheRead) > usage.input ? 0 : cacheRead\n}\n\nfunction classifiedTotal(usage: Partial<LoopTokenUsage>, cacheRead: number): number {\n return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0)\n}\n\n/**\n * The only two members this reads out of a provider prompt-cache report, named rather than taken as\n * an open record: both the typed `PromptCacheUsage` and the open `promptCache` an `llm_call` carries\n * satisfy it, and each value is validated before it is credited.\n */\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/**\n * Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds\n * and `chargedTokens` credits.\n *\n * The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`\n * vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the\n * three outcomes are different facts that must not collapse into one another:\n *\n * - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,\n * because a provider that says nothing about caching has not said the split is unknowable.\n * - **Read and write both reported, and fitting inside `input`** — a complete partition, so\n * `freshInput` is the remainder and the split is known.\n * - **One counter reported, or classes that overflow `input`** — the counters that ARE measured\n * pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports\n * no write) still credits the read it measured, while declaring the rest unclassified so the\n * charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a\n * partition of a total it exceeds.\n *\n * A counter the provider did not report stays absent. A zero would claim the provider measured no\n * cache, which is a different fact from a provider that did not report.\n */\nexport function promptCacheTokenClasses(\n input: number | undefined,\n promptCache: PromptCacheCounters | undefined,\n): PromptCacheTokenClasses {\n if (promptCache === undefined) return {}\n const read = tokenCount(promptCache.readTokens)\n const write = tokenCount(promptCache.writeTokens)\n if (read === undefined && write === undefined) return {}\n if (input === undefined || (read ?? 0) + (write ?? 0) > input) {\n return { cacheBreakdownKnown: false }\n }\n if (read !== undefined && write !== undefined) {\n return { freshInput: input - read - write, cacheRead: read, cacheWrite: write }\n }\n return {\n ...(read !== undefined ? { cacheRead: read } : {}),\n ...(write !== undefined ? { cacheWrite: write } : {}),\n cacheBreakdownKnown: false,\n }\n}\n\nfunction tokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\n/**\n * Add the observed subtotal into `acc`; token and cache incompleteness are sticky.\n *\n * A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO\n * classes. Folding them in would hide the overflow: the accumulator's larger `input` can absorb a\n * class total that overflowed the one delta that reported it, and `chargedTokens` would then credit\n * at the aggregate a cache read it refuses at the record. That is the one way the charge could come\n * out below the sum of the charges on the records that built it.\n */\nexport function addTokenUsage(acc: LoopTokenUsage, delta: Partial<LoopTokenUsage>): void {\n acc.input += delta.input ?? 0\n acc.output += delta.output ?? 0\n if (delta.tokensKnown === false) acc.tokensKnown = false\n\n const input = delta.input ?? 0\n const fits = classifiedTotal(delta, delta.cacheRead ?? 0) <= input\n if (fits) {\n if (delta.freshInput !== undefined) acc.freshInput = (acc.freshInput ?? 0) + delta.freshInput\n if (delta.cacheRead !== undefined) acc.cacheRead = (acc.cacheRead ?? 0) + delta.cacheRead\n if (delta.cacheWrite !== undefined) acc.cacheWrite = (acc.cacheWrite ?? 0) + delta.cacheWrite\n }\n\n const classified =\n fits &&\n delta.freshInput !== undefined &&\n delta.cacheRead !== undefined &&\n delta.cacheWrite !== undefined &&\n delta.freshInput + delta.cacheRead + delta.cacheWrite === input\n // A provider that reports prompt input without all three classes leaves the\n // split unknown. Do not let an earlier complete turn make the aggregate look\n // complete after a later unclassified positive-input turn.\n if (delta.cacheBreakdownKnown === false || (input > 0 && !classified)) {\n acc.cacheBreakdownKnown = false\n }\n}\n\n/**\n * Map `items` through `fn` with at most `limit` calls in flight at once,\n * preserving input order in the result. On the first `fn` rejection no NEW\n * items are picked up; already-in-flight calls are awaited, then the first\n * error is rethrown. `limit` is clamped to ≥ 1.\n *\n * Used where a burst of provisioning (e.g. forking N child boxes) must respect\n * the loop's concurrency bound instead of firing all N at once.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const 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"],"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;;;;;;;AAQA,MAAa,2BAA2B;;AAGxC,SAAgB,sBAAsB,QAA0B;CAC9D,OAAO,WAAA,6BAAoC,WAAA;AAC7C;AACA,M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MAAM,QAAQ;EACjD,QAAQ,QAAQ,KAAK,SAAS,QAAQ;CACxC;CACA,OAAO;AACT;;AAGA,SAAgB,aAAa,OAAwB;CACnD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;AAGA,SAAgB,gBAAmB,OAA2C;CAC5E,OACE,UAAU,QACV,OAAO,UAAU,YACjB,OAAQ,MAA+C,OAAO,mBAAmB;AAErF;;AAGA,SAAgB,WAAW,MAAsB;CAC/C,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;EACvC,KAAK,KAAK,WAAW,CAAC;EACtB,IAAI,KAAK,KAAK,GAAG,QAAU;CAC7B;CACA,QAAQ,MAAM,EAAA,CAAG,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;AAC/C"}
1
+ {"version":3,"file":"util-BX20UJ9X.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/**\n * How long an abort waits for a manager whose result was already accepted to end the turn that\n * submitted it. Acceptance asks the turn's harness to stop; what remains is the turn's final\n * session copy (a bounded native capture), metering its usage and committing its result. Its\n * workspace capture is not part of it: the manager's owner runs that after the result.\n */\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 { 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/**\n * The spend of work that HAPPENED and reported no usage receipt.\n *\n * Not the same value as {@link zeroSpend} even though both carry `{0,0}` tokens and `$0`. A bare\n * zero asserts a MEASUREMENT — \"this ran and cost nothing\" — and every consumer downstream reads it\n * that way: the pool keeps reporting `readout().tokensKnown === true`, the journal totals stay\n * clean, the OTEL span records a priced zero, and a caller's token-denominated ceiling can never\n * fire no matter how much the work really burned. A ceiling that cannot fire is worse than no\n * ceiling, because it reads as protection.\n *\n * `tokensKnown` is the marker the substrate already threads end to end for exactly this case\n * (`budget.ts`, `otel-spans.ts`, `spawn-journal.ts`, `supervisor.ts`): the work is recorded, the\n * zero is labelled a floor rather than a total, and every rollup that touches it reports its\n * balance as a ceiling rather than a measurement. Use this — never a bare zero — whenever a runtime\n * cannot see what its worker spent.\n *\n * The same rule applies to dollars. A dollar-capped run must refuse an executor whose billed spend\n * is unknowable; `budgetExempt` does not authorize Runtime to relabel unknown spend as a measured\n * zero. Callers that require dollar accounting must use a backend with a trusted billing receipt.\n */\nexport function unmeteredSpend(ms: number): Spend {\n return {\n iterations: 0,\n tokens: zeroTokenUsage(),\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms,\n }\n}\n\n/** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */\nexport function cloneSpend(spend: Spend): Spend {\n return {\n ...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 }\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 }\n}\n\n/**\n * Fold the token-provenance channel across spends, as a field to spread.\n *\n * Returns nothing when no contributor stated one, because ABSENT already means \"the executor's own\n * live stream\", which is what every path reported before a harness store was readable. A\n * contributor that stated one and a contributor that did not therefore disagree, and the sum is\n * `'mixed'` — the honest answer for a tree whose spend came from two kinds of receipt.\n */\nfunction tokensProvenanceOf(...spends: ReadonlyArray<Spend>): {\n tokensProvenance?: TokenUsageProvenance\n} {\n let folded: TokenUsageProvenance | undefined\n let sawStated = false\n for (const spend of spends) {\n const stated = spend.tokensProvenance ?? 'stream-receipt'\n if (spend.tokensProvenance !== undefined) sawStated = true\n folded = folded === undefined || folded === stated ? stated : 'mixed'\n }\n return !sawStated || folded === undefined || folded === 'stream-receipt'\n ? {}\n : { tokensProvenance: folded }\n}\n\n/**\n * Fold the platform box-time channel across spends, as a field to spread.\n *\n * Returns nothing when no input carried the channel, so a fold over router or cli-bridge work —\n * which runs no box at all — never gains a `boxMinutesProvenance: 'uncaptured'` that would claim\n * a box ran and went unmetered.\n *\n * Three rules, one per field:\n * - `boxMinutes` sums the numbers that are present, and stays ABSENT when none is. A missing\n * measurement never enters the sum as a zero.\n * - `boxMinutesKnown` is sticky-false, like `tokensKnown`: one contributor that could not state\n * its box time makes the whole sum a floor.\n * - `boxMinutesProvenance` degrades. `'observed'` survives only when every contributor that\n * carried a number was observed; one derived number makes the sum `'estimated'`; no number at\n * all is `'uncaptured'`.\n */\nfunction boxMinutesOf(...spends: ReadonlyArray<Spend>): {\n boxMinutes?: number\n boxMinutesKnown?: boolean\n boxMinutesProvenance?: 'observed' | 'estimated' | 'uncaptured'\n} {\n const present = spends.filter((spend) => spend.boxMinutesProvenance !== undefined)\n if (present.length === 0) return {}\n let minutes = 0\n let sawNumber = false\n let known = true\n let observedOnly = true\n for (const spend of present) {\n if (typeof spend.boxMinutes === 'number' && Number.isFinite(spend.boxMinutes)) {\n minutes += spend.boxMinutes\n sawNumber = true\n if (spend.boxMinutesProvenance !== 'observed') observedOnly = false\n }\n if (spend.boxMinutesKnown !== true) known = false\n }\n return {\n ...(sawNumber ? { boxMinutes: roundBoxMinutes(minutes) } : {}),\n boxMinutesKnown: known,\n boxMinutesProvenance: sawNumber ? (observedOnly ? 'observed' : 'estimated') : 'uncaptured',\n }\n}\n\n/**\n * Box minutes at four decimals — a tenth of a second.\n *\n * Fine enough that a box alive for two seconds reports `0.0333` instead of a zero that would read\n * as a measured free box, and coarse enough that summing floats does not print\n * `1.5000000000000002`.\n */\nexport function roundBoxMinutes(minutes: number): number {\n return Number(minutes.toFixed(4))\n}\n\n/** Copy a token subtotal without dropping optional provider cache telemetry. */\nexport function cloneTokenUsage(usage: LoopTokenUsage): LoopTokenUsage {\n const cacheBreakdownUnknown =\n usage.cacheBreakdownKnown === false || (usage.input > 0 && !hasClassifiedCacheBreakdown(usage))\n return {\n input: usage.input,\n output: usage.output,\n ...(usage.tokensKnown === false ? { tokensKnown: false as const } : {}),\n ...(usage.freshInput !== undefined ? { freshInput: usage.freshInput } : {}),\n ...(usage.cacheRead !== undefined ? { cacheRead: usage.cacheRead } : {}),\n ...(usage.cacheWrite !== undefined ? { cacheWrite: usage.cacheWrite } : {}),\n ...(cacheBreakdownUnknown ? { cacheBreakdownKnown: false as const } : {}),\n }\n}\n\n/** True only when every positive prompt token has a consistent cache classification. */\nexport function hasCompleteCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.cacheBreakdownKnown === false) return false\n return hasClassifiedCacheBreakdown(usage)\n}\n\nfunction hasClassifiedCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.input === 0) return true\n if (\n usage.freshInput === undefined ||\n usage.cacheRead === undefined ||\n usage.cacheWrite === undefined\n ) {\n return false\n }\n return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input\n}\n\n/**\n * The token charge for one observation: every token counted ONCE, at the moment it first enters\n * the context — `input − cacheRead + output`.\n *\n * `input` is a rolled-up prompt total that re-counts a cached prefix on every turn that reads it,\n * so charging `input` makes a 100K prefix read 40 times cost 4.1M for content authored once. A\n * cache read is content that was already charged when it was written, so it is the one class the\n * charge subtracts. Under a complete split the result is exactly `freshInput + cacheWrite`. No\n * price weight is involved: this counts work, and money is a separate channel.\n *\n * The subtraction form is what makes the charge ADDITIVE. `input` and `cacheRead` both accumulate\n * through `addTokenUsage`, so the charge on an aggregate equals the sum of the charges on the\n * records that built it — including an aggregate that mixes classified and unclassified turns,\n * where the unclassified remainder is charged in full and only the reported cache reads are\n * credited. A form that read `freshInput + cacheWrite` directly loses that: one unclassified turn\n * would drop the whole aggregate to `input + output` and over-charge every classified turn with it.\n *\n * The one arithmetic guarantee: a set of classes that does not FIT inside the prompt total it\n * partitions credits nothing, so the charge is never below `output` and a class that overflows its\n * own total buys no tokens. It is not a guarantee against a provider that reports a cache read it\n * never served — that provider can under-report `input` just as easily, and the token channel is an\n * accounting unit, not a trust boundary. Prompt tokens the provider left unclassified are charged\n * in full, so a spend with no readable split charges an upper bound on newly-presented work rather\n * than a measurement, and every caller that enforces a ceiling must report the difference\n * (`BudgetPool` does it through `readout().cacheBreakdownKnown`).\n */\nexport function chargedTokens(usage: LoopTokenUsage): number {\n return usage.input - creditedCacheRead(usage) + usage.output\n}\n\n/** `cacheRead` if the reported classes fit inside `input`, else nothing. */\nfunction creditedCacheRead(usage: LoopTokenUsage): number {\n const { cacheRead } = usage\n if (cacheRead === undefined) return 0\n return classifiedTotal(usage, cacheRead) > usage.input ? 0 : cacheRead\n}\n\nfunction classifiedTotal(usage: Partial<LoopTokenUsage>, cacheRead: number): number {\n return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0)\n}\n\n/**\n * The only two members this reads out of a provider prompt-cache report, named rather than taken as\n * an open record: both the typed `PromptCacheUsage` and the open `promptCache` an `llm_call` carries\n * satisfy it, and each value is validated before it is credited.\n */\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/**\n * Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds\n * and `chargedTokens` credits.\n *\n * The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`\n * vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the\n * three outcomes are different facts that must not collapse into one another:\n *\n * - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,\n * because a provider that says nothing about caching has not said the split is unknowable.\n * - **Read and write both reported, and fitting inside `input`** — a complete partition, so\n * `freshInput` is the remainder and the split is known.\n * - **One counter reported, or classes that overflow `input`** — the counters that ARE measured\n * pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports\n * no write) still credits the read it measured, while declaring the rest unclassified so the\n * charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a\n * partition of a total it exceeds.\n *\n * A counter the provider did not report stays absent. A zero would claim the provider measured no\n * cache, which is a different fact from a provider that did not report.\n */\nexport function promptCacheTokenClasses(\n input: number | undefined,\n promptCache: PromptCacheCounters | undefined,\n): PromptCacheTokenClasses {\n if (promptCache === undefined) return {}\n const read = tokenCount(promptCache.readTokens)\n const write = tokenCount(promptCache.writeTokens)\n if (read === undefined && write === undefined) return {}\n if (input === undefined || (read ?? 0) + (write ?? 0) > input) {\n return { cacheBreakdownKnown: false }\n }\n if (read !== undefined && write !== undefined) {\n return { freshInput: input - read - write, cacheRead: read, cacheWrite: write }\n }\n return {\n ...(read !== undefined ? { cacheRead: read } : {}),\n ...(write !== undefined ? { cacheWrite: write } : {}),\n cacheBreakdownKnown: false,\n }\n}\n\nfunction tokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\n/**\n * Add the observed subtotal into `acc`; token and cache incompleteness are sticky.\n *\n * A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO\n * classes. Folding them in would hide the overflow: the accumulator's larger `input` can absorb a\n * class total that overflowed the one delta that reported it, and `chargedTokens` would then credit\n * at the aggregate a cache read it refuses at the record. That is the one way the charge could come\n * out below the sum of the charges on the records that built it.\n */\nexport function addTokenUsage(acc: LoopTokenUsage, delta: Partial<LoopTokenUsage>): void {\n acc.input += delta.input ?? 0\n acc.output += delta.output ?? 0\n if (delta.tokensKnown === false) acc.tokensKnown = false\n\n const input = delta.input ?? 0\n const fits = classifiedTotal(delta, delta.cacheRead ?? 0) <= input\n if (fits) {\n if (delta.freshInput !== undefined) acc.freshInput = (acc.freshInput ?? 0) + delta.freshInput\n if (delta.cacheRead !== undefined) acc.cacheRead = (acc.cacheRead ?? 0) + delta.cacheRead\n if (delta.cacheWrite !== undefined) acc.cacheWrite = (acc.cacheWrite ?? 0) + delta.cacheWrite\n }\n\n const classified =\n fits &&\n delta.freshInput !== undefined &&\n delta.cacheRead !== undefined &&\n delta.cacheWrite !== undefined &&\n delta.freshInput + delta.cacheRead + delta.cacheWrite === input\n // A provider that reports prompt input without all three classes leaves the\n // split unknown. Do not let an earlier complete turn make the aggregate look\n // complete after a later unclassified positive-input turn.\n if (delta.cacheBreakdownKnown === false || (input > 0 && !classified)) {\n acc.cacheBreakdownKnown = false\n }\n}\n\n/**\n * Map `items` through `fn` with at most `limit` calls in flight at once,\n * preserving input order in the result. On the first `fn` rejection no NEW\n * items are picked up; already-in-flight calls are awaited, then the first\n * error is rethrown. `limit` is clamped to ≥ 1.\n *\n * Used where a burst of provisioning (e.g. forking N child boxes) must respect\n * the loop's concurrency bound instead of firing all N at once.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const 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 >>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AE9B;;;;;;;;;;AAWA,eAAsB,mBACpB,OACA,OACA,IACc;CACd,MAAM,UAAU,IAAI,MAAS,MAAM,MAAM;CACzC,IAAI,OAAO;CACX,WAAW,MAAM,WAAW,aAAa;EACvC,aAAa,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC;EAClE,YAAY;GACV,MAAM,QAAQ;GACd,OAAO,QAAQ,MAAM,SAAS;IAAE,IAAI,OAAO,KAAK;IAAG,OAAO;GAAM,IAAI,KAAA;EACtE;EACA,UAAU,EAAE,OAAO,YAAY,GAAG,MAAM,QAAa,KAAK;CAC5D,CAAC,GAAG;EACF,IAAI,QAAQ,WAAW,YAAY,MAAM,QAAQ;EACjD,QAAQ,QAAQ,KAAK,SAAS,QAAQ;CACxC;CACA,OAAO;AACT;;AAGA,SAAgB,aAAa,OAAwB;CACnD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;AAGA,SAAgB,gBAAmB,OAA2C;CAC5E,OACE,UAAU,QACV,OAAO,UAAU,YACjB,OAAQ,MAA+C,OAAO,mBAAmB;AAErF;;AAGA,SAAgB,WAAW,MAAsB;CAC/C,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;EACvC,KAAK,KAAK,WAAW,CAAC;EACtB,IAAI,KAAK,KAAK,GAAG,QAAU;CAC7B;CACA,QAAQ,MAAM,EAAA,CAAG,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;AAC/C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "1.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
5
5
  "homepage": "https://github.com/tangle-network/agent-runtime#readme",
6
6
  "repository": {
@@ -119,12 +119,12 @@
119
119
  "@biomejs/biome": "^2.6.3",
120
120
  "@modelcontextprotocol/sdk": "1.32.2",
121
121
  "@tangle-network/agent-eval": "1.0.0",
122
- "@tangle-network/agent-interface": "5.9.0",
122
+ "@tangle-network/agent-interface": "5.10.2",
123
123
  "@tangle-network/agent-provider-cli-bridge": "2.0.1",
124
124
  "@tangle-network/agent-provider-daytona": "0.6.0",
125
125
  "@tangle-network/agent-provider-e2b": "0.6.0",
126
126
  "@tangle-network/agent-provider-tangle": "4.5.0",
127
- "@tangle-network/sandbox": "1.0.8",
127
+ "@tangle-network/sandbox": "1.0.33",
128
128
  "@types/node": "26.6.5",
129
129
  "@types/tar-stream": "3.1.5",
130
130
  "miniflare": "4.20260730.0",
@@ -152,7 +152,7 @@
152
152
  "@earendil-works/pi-codemode": "1.4.0",
153
153
  "@tangle-network/agent-core": "^1.0.0",
154
154
  "@tangle-network/agent-knowledge": "^23.0.0",
155
- "@tangle-network/agent-profile-materialize": "^1.0.0",
155
+ "@tangle-network/agent-profile-materialize": "^1.1.2",
156
156
  "@tangle-network/agent-trace-contract": "^2.2.0",
157
157
  "tar-stream": "3.2.2",
158
158
  "yaml": "2.9.1",
@@ -48,6 +48,7 @@ Routes edges run a flow graph and need `entry`; a flow graph takes no delegation
48
48
  On each usable settle of `from`, its routes edges are tried in declaration order and the first whose `when` holds fires; one settle fires at most one edge.
49
49
  `when` compares JSON scalars only (`equals`, `in`, `exists` at an RFC 6901 pointer, or `all` of several); a numeric or stateful rule is a field the node settles, such as a boolean or a counter.
50
50
  A match reads `from` unless it names a node listed in the edge's `evidence`; a pointer that does not resolve does not match.
51
+ A node that must know its own earlier settle (which round this is, a streak it counts) lists itself in the `evidence` of the edge that reaches it; without that it starts every visit from nothing (`loop-until-dry`, `debate-rounds`).
51
52
  An edge without `when` is the default branch: at most one per node, and last.
52
53
  A node target receives `{ from: { node, result }, evidence }` (a join's target `{ from: { nodes }, evidence }`) and the edge directive; `{ stop: reason }` ends the run with no winner; `{ finish: reason }` makes this settle part of the output.
53
54
  The output is `{ [node]: latest usable result }` over terminal nodes (no outgoing routes or map edge) and finish sources, and the deliverable decides it.