@tangle-network/agent-runtime 0.104.0 → 0.106.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/README.md +176 -42
  2. package/dist/activation-CRjVfOiy.js +203 -0
  3. package/dist/activation-CRjVfOiy.js.map +1 -0
  4. package/dist/activation-DyWB0K6E.d.ts +98 -0
  5. package/dist/agent.d.ts +216 -234
  6. package/dist/agent.js +615 -547
  7. package/dist/agent.js.map +1 -1
  8. package/dist/analyst-loop-DGdtVENg.js +517 -0
  9. package/dist/analyst-loop-DGdtVENg.js.map +1 -0
  10. package/dist/analyst-loop.d.ts +10 -43
  11. package/dist/analyst-loop.js +2 -11
  12. package/dist/backends-Dy8NujB4.js +713 -0
  13. package/dist/backends-Dy8NujB4.js.map +1 -0
  14. package/dist/candidate-execution/index.d.ts +4 -192
  15. package/dist/candidate-execution/index.js +5 -66
  16. package/dist/candidate-execution-DqMbv1rU.js +488 -0
  17. package/dist/candidate-execution-DqMbv1rU.js.map +1 -0
  18. package/dist/coder-yhVWbdWc.js +40 -0
  19. package/dist/coder-yhVWbdWc.js.map +1 -0
  20. package/dist/conversation-XucG_K3l.js +1265 -0
  21. package/dist/conversation-XucG_K3l.js.map +1 -0
  22. package/dist/conversation.d.ts +2 -804
  23. package/dist/conversation.js +2 -55
  24. package/dist/environment-provider-CfLUmKmf.js +1168 -0
  25. package/dist/environment-provider-CfLUmKmf.js.map +1 -0
  26. package/dist/environment-provider-IUGU3epE.d.ts +964 -0
  27. package/dist/environment-provider.d.ts +2 -78
  28. package/dist/environment-provider.js +2 -18
  29. package/dist/errors-DEAvWQPy.js +111 -0
  30. package/dist/errors-DEAvWQPy.js.map +1 -0
  31. package/dist/improvement-adapter-Cr5TBSji.d.ts +166 -0
  32. package/dist/improvement-cycle-C095kS_g.js +2624 -0
  33. package/dist/improvement-cycle-C095kS_g.js.map +1 -0
  34. package/dist/index-BGdxAwfO.d.ts +838 -0
  35. package/dist/index-C-FYUuFG.d.ts +193 -0
  36. package/dist/index-CbNM40xG.d.ts +140 -0
  37. package/dist/index-DruSKs3Z.d.ts +7224 -0
  38. package/dist/index-Efjb3nrQ.d.ts +671 -0
  39. package/dist/index.d.ts +14 -1134
  40. package/dist/index.js +2134 -1972
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +776 -888
  43. package/dist/intelligence.js +1466 -1410
  44. package/dist/intelligence.js.map +1 -1
  45. package/dist/{kb-gate-CwHO0vz6.d.ts → kb-gate-C8z2juK8.d.ts} +33 -31
  46. package/dist/kb-gate-DpaSwXVx.js +80 -0
  47. package/dist/kb-gate-DpaSwXVx.js.map +1 -0
  48. package/dist/knowledge-Ku-mPP4f.js +433 -0
  49. package/dist/knowledge-Ku-mPP4f.js.map +1 -0
  50. package/dist/knowledge.d.ts +2 -150
  51. package/dist/knowledge.js +2 -40
  52. package/dist/local-harness-Dh8PJ0ot.d.ts +455 -0
  53. package/dist/loop-runner-bin-BXsFEUcf.d.ts +162 -0
  54. package/dist/loop-runner-bin-BwjQ1NfH.js +268 -0
  55. package/dist/loop-runner-bin-BwjQ1NfH.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -17
  57. package/dist/loop-runner-bin.js +2 -24
  58. package/dist/loops.d.ts +5 -4164
  59. package/dist/loops.js +8 -419
  60. package/dist/mcp/bin.d.ts +1 -1
  61. package/dist/mcp/bin.js +116 -146
  62. package/dist/mcp/bin.js.map +1 -1
  63. package/dist/mcp/index.d.ts +295 -437
  64. package/dist/mcp/index.js +1242 -1177
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/mcp/memory-bin.d.ts +1 -1
  67. package/dist/mcp/memory-bin.js +37 -16
  68. package/dist/mcp/memory-bin.js.map +1 -1
  69. package/dist/memory-server-DL6cE2Ag.js +234 -0
  70. package/dist/memory-server-DL6cE2Ag.js.map +1 -0
  71. package/dist/model-resolution-Btd9iIKV.js +98 -0
  72. package/dist/model-resolution-Btd9iIKV.js.map +1 -0
  73. package/dist/openai-tools-B68JaOCx.d.ts +24 -0
  74. package/dist/openai-tools-CKLy1C7M.js +44 -0
  75. package/dist/openai-tools-CKLy1C7M.js.map +1 -0
  76. package/dist/otel-export-D34IQW1C.js +843 -0
  77. package/dist/otel-export-D34IQW1C.js.map +1 -0
  78. package/dist/platform.d.ts +188 -185
  79. package/dist/platform.js +185 -218
  80. package/dist/platform.js.map +1 -1
  81. package/dist/prepare-B53sPV7M.js +4292 -0
  82. package/dist/prepare-B53sPV7M.js.map +1 -0
  83. package/dist/primeintellect/index.d.ts +150 -147
  84. package/dist/primeintellect/index.js +626 -1004
  85. package/dist/primeintellect/index.js.map +1 -1
  86. package/dist/profiles.d.ts +296 -490
  87. package/dist/profiles.js +722 -749
  88. package/dist/profiles.js.map +1 -1
  89. package/dist/protected-model-port-BLPH5VVv.js +722 -0
  90. package/dist/protected-model-port-BLPH5VVv.js.map +1 -0
  91. package/dist/protected-model-port-BP6Z4eau.d.ts +283 -0
  92. package/dist/protected-redaction--F3v1oo8.js +200 -0
  93. package/dist/protected-redaction--F3v1oo8.js.map +1 -0
  94. package/dist/redact-D-u-rrcn.js +82 -0
  95. package/dist/redact-D-u-rrcn.js.map +1 -0
  96. package/dist/redact-kbIOjfjM.d.ts +452 -0
  97. package/dist/researcher-CoVqNhfI.js +433 -0
  98. package/dist/researcher-CoVqNhfI.js.map +1 -0
  99. package/dist/runtime-BG0BziaP.js +5408 -0
  100. package/dist/runtime-BG0BziaP.js.map +1 -0
  101. package/dist/sandbox-events-DeI5xX8P.js +316 -0
  102. package/dist/sandbox-events-DeI5xX8P.js.map +1 -0
  103. package/dist/spawn-journal-CwPvKUTa.js +456 -0
  104. package/dist/spawn-journal-CwPvKUTa.js.map +1 -0
  105. package/dist/structural-rollout-IXUEplky.js +1445 -0
  106. package/dist/structural-rollout-IXUEplky.js.map +1 -0
  107. package/dist/substrate-B0TYNrXn.js +27 -0
  108. package/dist/substrate-B0TYNrXn.js.map +1 -0
  109. package/dist/{substrate-Dyiqmd3o.d.ts → substrate-BcnuSHXm.d.ts} +57 -54
  110. package/dist/supervise-BiRutHS9.js +7321 -0
  111. package/dist/supervise-BiRutHS9.js.map +1 -0
  112. package/dist/supervisor-DTKhF-RV.js +3826 -0
  113. package/dist/supervisor-DTKhF-RV.js.map +1 -0
  114. package/dist/testing.d.ts +4 -3
  115. package/dist/testing.js +2478 -2637
  116. package/dist/testing.js.map +1 -1
  117. package/dist/tool-server-RcWgLIsL.js +141 -0
  118. package/dist/tool-server-RcWgLIsL.js.map +1 -0
  119. package/dist/trace-propagation-CJJC7SVB.js +57 -0
  120. package/dist/trace-propagation-CJJC7SVB.js.map +1 -0
  121. package/dist/types-BaIpb0XT.d.ts +492 -0
  122. package/dist/types-BevOjfTY.d.ts +765 -0
  123. package/dist/types-C9j4qg6l.d.ts +500 -0
  124. package/dist/types-Cja5OTGh.d.ts +190 -0
  125. package/dist/util-MVgdwuIS.js +145 -0
  126. package/dist/util-MVgdwuIS.js.map +1 -0
  127. package/dist/workspace-archive-BosQiotA.js +575 -0
  128. package/dist/workspace-archive-BosQiotA.js.map +1 -0
  129. package/package.json +43 -55
  130. package/skills/build-with-agent-runtime/SKILL.md +16 -9
  131. package/skills/loop-writer/SKILL.md +1 -1
  132. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  133. package/dist/analyst-loop.js.map +0 -1
  134. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  135. package/dist/candidate-execution/index.js.map +0 -1
  136. package/dist/chunk-2KGAN2HM.js +0 -1256
  137. package/dist/chunk-2KGAN2HM.js.map +0 -1
  138. package/dist/chunk-2QJSNOGK.js +0 -48
  139. package/dist/chunk-2QJSNOGK.js.map +0 -1
  140. package/dist/chunk-2UABGGUB.js +0 -474
  141. package/dist/chunk-2UABGGUB.js.map +0 -1
  142. package/dist/chunk-2VZYRB55.js +0 -834
  143. package/dist/chunk-2VZYRB55.js.map +0 -1
  144. package/dist/chunk-2X65HYMI.js +0 -3526
  145. package/dist/chunk-2X65HYMI.js.map +0 -1
  146. package/dist/chunk-3MDZX7YU.js +0 -125
  147. package/dist/chunk-3MDZX7YU.js.map +0 -1
  148. package/dist/chunk-3PPVCS75.js +0 -199
  149. package/dist/chunk-3PPVCS75.js.map +0 -1
  150. package/dist/chunk-5HNDYWUT.js +0 -6424
  151. package/dist/chunk-5HNDYWUT.js.map +0 -1
  152. package/dist/chunk-5IBQAPVB.js +0 -29
  153. package/dist/chunk-5IBQAPVB.js.map +0 -1
  154. package/dist/chunk-5QOB7H74.js +0 -387
  155. package/dist/chunk-5QOB7H74.js.map +0 -1
  156. package/dist/chunk-ATDFUJYI.js +0 -4728
  157. package/dist/chunk-ATDFUJYI.js.map +0 -1
  158. package/dist/chunk-B7K7V22Y.js +0 -699
  159. package/dist/chunk-B7K7V22Y.js.map +0 -1
  160. package/dist/chunk-DPEUKJRO.js +0 -27
  161. package/dist/chunk-DPEUKJRO.js.map +0 -1
  162. package/dist/chunk-FD2MBMOH.js +0 -494
  163. package/dist/chunk-FD2MBMOH.js.map +0 -1
  164. package/dist/chunk-FJI3EXU3.js +0 -2402
  165. package/dist/chunk-FJI3EXU3.js.map +0 -1
  166. package/dist/chunk-HAO4CXHP.js +0 -200
  167. package/dist/chunk-HAO4CXHP.js.map +0 -1
  168. package/dist/chunk-ISPWRSEC.js +0 -408
  169. package/dist/chunk-ISPWRSEC.js.map +0 -1
  170. package/dist/chunk-KRBFHMV6.js +0 -1228
  171. package/dist/chunk-KRBFHMV6.js.map +0 -1
  172. package/dist/chunk-L5DST3QC.js +0 -351
  173. package/dist/chunk-L5DST3QC.js.map +0 -1
  174. package/dist/chunk-M22PL4GH.js +0 -171
  175. package/dist/chunk-M22PL4GH.js.map +0 -1
  176. package/dist/chunk-NURIQBJQ.js +0 -72
  177. package/dist/chunk-NURIQBJQ.js.map +0 -1
  178. package/dist/chunk-PZZKQVQV.js +0 -52
  179. package/dist/chunk-PZZKQVQV.js.map +0 -1
  180. package/dist/chunk-Q2JSAVQ3.js +0 -671
  181. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  182. package/dist/chunk-SBTWKPVR.js +0 -5576
  183. package/dist/chunk-SBTWKPVR.js.map +0 -1
  184. package/dist/chunk-SGKPNBXE.js +0 -60
  185. package/dist/chunk-SGKPNBXE.js.map +0 -1
  186. package/dist/chunk-SNSMRT6H.js +0 -680
  187. package/dist/chunk-SNSMRT6H.js.map +0 -1
  188. package/dist/chunk-STJEHM5F.js +0 -1338
  189. package/dist/chunk-STJEHM5F.js.map +0 -1
  190. package/dist/chunk-UPWGXKXB.js +0 -254
  191. package/dist/chunk-UPWGXKXB.js.map +0 -1
  192. package/dist/chunk-YEJR7IXO.js +0 -68
  193. package/dist/chunk-YEJR7IXO.js.map +0 -1
  194. package/dist/chunk-ZXICDSAK.js +0 -907
  195. package/dist/chunk-ZXICDSAK.js.map +0 -1
  196. package/dist/completion-gate-Bv47cOnn.d.ts +0 -256
  197. package/dist/conversation.js.map +0 -1
  198. package/dist/coordination-CxtzMxSM.d.ts +0 -2570
  199. package/dist/environment-provider.js.map +0 -1
  200. package/dist/improve--2A0gK1-.d.ts +0 -440
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-CtK9dSny.d.ts +0 -175
  204. package/dist/loop-runner-bin-DUOGtvOl.d.ts +0 -207
  205. package/dist/loop-runner-bin.js.map +0 -1
  206. package/dist/loops.js.map +0 -1
  207. package/dist/openai-tools-fnj6SRVg.d.ts +0 -46
  208. package/dist/protected-model-port-DzkUY3HQ.d.ts +0 -271
  209. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  210. package/dist/structural-rollout-C4mabf87.d.ts +0 -446
  211. package/dist/supervise-7q9F5brx.d.ts +0 -379
  212. package/dist/types-BCoemcXU.d.ts +0 -802
  213. package/dist/types-BwoZWq-i.d.ts +0 -510
  214. package/dist/types-Cbp72qyu.d.ts +0 -491
  215. package/dist/types-CmYCMbFT.d.ts +0 -203
  216. package/dist/types-CvNwMzQt.d.ts +0 -957
  217. package/dist/worktree-fanout-WsOzt8qu.d.ts +0 -999
@@ -0,0 +1,964 @@
1
+ import { E as SandboxClient, K as RuntimeHooks, v as LoopTokenUsage } from "./types-BevOjfTY.js";
2
+ import { DefaultVerdict, ToolSpan } from "@tangle-network/agent-eval";
3
+ import { AgentProfile as AgentProfile$1, AgentProfileValidationResult } from "@tangle-network/agent-interface";
4
+ import { BackendType, CreateSandboxOptions, Sandbox } from "@tangle-network/sandbox";
5
+ import { AgentEnvironment, AgentEnvironmentCapabilities, AgentEnvironmentCapabilities as AgentEnvironmentCapabilities$1, AgentEnvironmentEvent, AgentEnvironmentProvider, AgentEnvironmentProvider as AgentEnvironmentProvider$1, AgentEnvironmentQuery, AgentEnvironmentStatus, AgentEnvironmentSummary, AgentProfileRef, AgentProfileRef as AgentProfileRef$1, AgentSession, AgentSessionRef, AgentSessionStatus, AgentTurnInput, AgentTurnInput as AgentTurnInput$1, AgentTurnResult, CheckpointRef, CheckpointRequest, CreateAgentEnvironmentInput, CreateAgentEnvironmentInput as CreateAgentEnvironmentInput$1, ExecRequest, ExecResult, ForkRequest, PlacementInfo, ResourceRequest, WorkspaceRequest } from "@tangle-network/agent-interface/environment-provider";
6
+ //#region src/runtime/supervise/progress.d.ts
7
+ /** How long a worker may produce no metered activity before a `progress()` read calls it stalled.
8
+ * Deliberately generous: a coding harness routinely spends minutes inside one tool call, and a
9
+ * false stall that provokes a steer is worse than a late one. */
10
+ declare const DEFAULT_STALL_AFTER_MS = 180000;
11
+ /** The most recent activity the executor can name — one tool call, one turn, or a free-form note.
12
+ * `label` is the tool/file/turn name; `detail` is a short, already-truncated descriptor (a path,
13
+ * a command head) that a driver can read without pulling the whole transcript. */
14
+ interface ActivityNote {
15
+ readonly at: number;
16
+ readonly kind: 'turn' | 'tool' | 'note';
17
+ readonly label: string;
18
+ readonly status?: 'ok' | 'error';
19
+ readonly detail?: string;
20
+ }
21
+ /** What an executor OPTIONALLY adds to the scope-derived progress (`Executor.progress()`). Every
22
+ * field is optional: an executor that knows only its own turn count reports only that. */
23
+ interface ExecutorProgress {
24
+ /** The executor's own turn/step count when it is more meaningful than metered iterations. */
25
+ readonly turns?: number;
26
+ /** Steers/answers delivered but not yet folded into the worker's conversation. */
27
+ readonly pendingMessages?: number;
28
+ /** Newest-last window of what the worker has been doing. */
29
+ readonly recentActivity?: ReadonlyArray<ActivityNote>;
30
+ /** A one-line human-readable state ("turn 3, running tests"). */
31
+ readonly note?: string;
32
+ }
33
+ /** The full live view of one worker, as `observe_agent` returns it mid-flight. */
34
+ interface WorkerProgress {
35
+ readonly id: string;
36
+ readonly status: NodeStatus;
37
+ /** True while the node is neither done, failed, nor cancelled — i.e. a steer could still land. */
38
+ readonly live: boolean;
39
+ /** True when this worker's executor exposes an inbox (`Executor.deliver`) — i.e. `steer_agent`
40
+ * can actually reach it. False means a steer would be recorded and dropped. */
41
+ readonly steerable: boolean;
42
+ readonly startedAt: number;
43
+ /** Epoch ms of the last metered usage event or executor-reported activity. */
44
+ readonly lastActivityAt: number;
45
+ readonly idleMs: number;
46
+ readonly stalled: boolean;
47
+ readonly stallAfterMs: number;
48
+ /** Metered iterations so far (the executor's own count when it reports one). */
49
+ readonly turns: number;
50
+ readonly tokens: {
51
+ readonly input: number;
52
+ readonly output: number;
53
+ };
54
+ readonly usd: number;
55
+ /** Steers delivered but not yet read by the worker. */
56
+ readonly pendingMessages: number;
57
+ /** Newest-last window of tool/turn activity; empty when the executor exposes none. */
58
+ readonly recentActivity: ReadonlyArray<ActivityNote>;
59
+ readonly note?: string;
60
+ }
61
+ /** A bounded newest-last ring of `ActivityNote`s an executor keeps to answer `progress()`. */
62
+ interface ActivityLog {
63
+ push(note: ActivityNote): void;
64
+ /** Newest-last, at most `limit` entries. */
65
+ read(): ReadonlyArray<ActivityNote>;
66
+ last(): ActivityNote | undefined;
67
+ size(): number;
68
+ }
69
+ /** Create a bounded activity ring. `limit` caps memory for a worker that runs thousands of tools. */
70
+ declare function createActivityLog(limit?: number): ActivityLog;
71
+ /** The scope-side facts about a child, independent of whether its executor cooperates. */
72
+ interface ScopeProgressInput {
73
+ readonly id: string;
74
+ readonly status: NodeStatus;
75
+ readonly steerable: boolean;
76
+ readonly startedAt: number;
77
+ readonly lastActivityAt: number;
78
+ readonly turns: number;
79
+ readonly tokens: {
80
+ readonly input: number;
81
+ readonly output: number;
82
+ };
83
+ readonly usd: number;
84
+ }
85
+ /** Fold the scope-derived facts and the executor's optional enrichment into one read. Pure: the
86
+ * caller supplies `now`, so a test can observe a stall without waiting for one. */
87
+ declare function readWorkerProgress(scope: ScopeProgressInput, executor: ExecutorProgress | undefined, now: number, stallAfterMs?: number): WorkerProgress;
88
+ //#endregion
89
+ //#region src/runtime/supervise/trace-source.d.ts
90
+ interface ToolStepInput {
91
+ readonly toolName: string;
92
+ readonly args: unknown;
93
+ readonly status?: 'ok' | 'error';
94
+ readonly result?: unknown;
95
+ /** Stable id of the tool call — used to de-duplicate the repeated state transitions a harness
96
+ * streams for one call (opencode emits pending→running→completed, plus a `raw`-wrapped copy). */
97
+ readonly callId?: string;
98
+ /** Real per-call wall-clock when the source has it (owned tool-loop; opencode parts with `time`).
99
+ * When omitted the span collapses to a single instant (`at`) — order + counts only, no duration. */
100
+ readonly startedAt?: number;
101
+ readonly endedAt?: number;
102
+ }
103
+ interface TraceSource {
104
+ /** Subscribe to tool spans as they are produced (ONLINE). Returns an unsubscribe. A source that
105
+ * only exposes its trace at the end registers nothing and returns a no-op. */
106
+ onSpan(handler: (span: ToolSpan) => void): () => void;
107
+ /** The full set of tool spans for the run (SETTLE / batch). Always available. */
108
+ collect(): Promise<ToolSpan[]>;
109
+ }
110
+ /** Decode a part with a specific harness's adapter when known, else try every registered adapter
111
+ * (the composite — robust to mixed/unknown streams). Never throws. */
112
+ declare function decodeToolPart(part: unknown, harness?: string): ToolStepInput | undefined;
113
+ /** A push source for OWNED tool loops (router-tools / cli-bridge tool dispatch): the loop calls
114
+ * `record(step)` for each tool call; it becomes a span, fan-out to live subscribers + buffered for
115
+ * `collect`. */
116
+ declare function createPushTraceSource(opts?: {
117
+ runId?: string;
118
+ now?: () => number;
119
+ }): {
120
+ source: TraceSource;
121
+ record: (input: ToolStepInput) => ToolSpan;
122
+ };
123
+ /** A harness session message carrying parts (the shape `box.messages()` returns). Structurally typed
124
+ * so this works with the real `@tangle-network/sandbox` box AND a test double, no SDK import. */
125
+ interface SessionMessageLike {
126
+ readonly parts?: ReadonlyArray<unknown>;
127
+ }
128
+ /** The minimal box surface this needs: list a session's messages (incl. mid-turn partials). */
129
+ interface SessionTraceBox {
130
+ messages(opts: {
131
+ sessionId: string;
132
+ }): Promise<ReadonlyArray<SessionMessageLike>>;
133
+ }
134
+ /** The SANDBOX / fleet trace source: read a box session's message parts and decode the harness's tool
135
+ * calls into spans. `collect` (settle) is the solid path — `box.messages({sessionId})` → parts → spans;
136
+ * black-box harnesses aren't mid-step interruptible, so online steering is the owned-loop's job and a
137
+ * live `subscribe` is opt-in (pass `subscribeParts` from `streamPrompt` when the harness streams parts). */
138
+ declare function sandboxSessionTraceSource(box: SessionTraceBox, sessionId: string, opts?: {
139
+ /** The box's harness (e.g. 'opencode', 'claude-code') → selects its decoder adapter. */
140
+ harness?: string;
141
+ subscribeParts?: (onPart: (part: unknown) => void) => () => void;
142
+ runId?: string;
143
+ now?: () => number;
144
+ }): TraceSource;
145
+ //#endregion
146
+ //#region src/runtime/supervise/wait.d.ts
147
+ /**
148
+ *
149
+ * WAIT-STATES — a supervision-tree node that waits on wall-clock time or an external condition
150
+ * without holding a worker, an executor, a sandbox, or a single LLM turn.
151
+ *
152
+ * A long-horizon run spends most of its wall-clock NOT computing: waiting for CI to finish,
153
+ * for a nightly job to land, for a human to reply, for a rate-limit window to reopen. Before
154
+ * this, the only way to express that was to keep something alive and re-ask — which spends
155
+ * driver tokens per re-ask and pins a process to the wait.
156
+ *
157
+ * Two node kinds, both first-class:
158
+ * - `timer` — wake at an ABSOLUTE wall-clock instant (`untilMs`).
159
+ * - `poll` — re-run a named predicate every `intervalMs` until it returns true, or until an
160
+ * absolute `timeoutAtMs` passes (CI status, file existence, an HTTP probe, an
161
+ * inbox message).
162
+ *
163
+ * ── How this differs from `await_event`'s 15s poll fence (`DEFAULT_AWAIT_EVENT_TIMEOUT_MS`) ──
164
+ *
165
+ * They look similar and are not the same mechanism. `await_event` is an IN-RUN RENDEZVOUS: the
166
+ * driver blocks on the coordination bus for the next event from a live worker, and the 15s fence
167
+ * exists only so a remote MCP request does not exceed the client's timeout — the caller re-polls.
168
+ * Every re-poll is another driver inference turn (real tokens) against a process that must stay
169
+ * up, and nothing about that wait is recorded: kill the process and the wait is simply gone.
170
+ *
171
+ * A wait-state is a NODE, not a call. It has a node id in the tree, a journal record carrying its
172
+ * ABSOLUTE deadline, and it settles through the same `Scope.next()` cursor as any worker. Nobody
173
+ * is blocked on it — the driver can stop reasoning entirely, and the process can die. Cost while
174
+ * waiting: zero LLM calls, zero executor, zero sandbox, zero conserved budget (a wait reserves
175
+ * nothing from the pool). The only in-process residue is one timer entry.
176
+ *
177
+ * ── Why probes are NAMED, not passed as closures ────────────────────────────────────────────
178
+ *
179
+ * A wait must survive a process restart with its original deadline intact, and a closure cannot
180
+ * be journaled. So a `poll` names its predicate (`probe: 'ci-green'`) and the run resolves it
181
+ * through a `WaitProbeRegistry`. A brand-new process re-resolves the SAME name against its own
182
+ * registry and re-arms the wait — which is what makes "kill the box, the wait keeps waiting"
183
+ * true rather than aspirational.
184
+ *
185
+ * Absolute instants for the same reason: `untilMs` / `timeoutAtMs` are epoch ms, not durations,
186
+ * so a resumed wait counts down from the original arm, not from the restart. `timerAt`/`pollFor`
187
+ * build them from a duration when that is what the caller has.
188
+ *
189
+ * @experimental
190
+ */
191
+ /** What a wait node is waiting for. Both variants carry ABSOLUTE epoch-ms instants so a wait
192
+ * re-armed by a later process keeps the deadline the first process set. */
193
+ type WaitSpec = {
194
+ readonly kind: 'timer';
195
+ /** Absolute epoch ms to wake at. A past instant fires immediately. */
196
+ readonly untilMs: number;
197
+ } | {
198
+ readonly kind: 'poll';
199
+ /** Name of the predicate in the run's `WaitProbeRegistry`. Named (not a closure) so a
200
+ * resumed process can re-resolve it — see the module header. */
201
+ readonly probe: string;
202
+ /** How often to re-run the predicate, in ms. Must be > 0. */
203
+ readonly intervalMs: number;
204
+ /** Absolute epoch ms after which an unfired poll settles `timeout`. Omit = no timeout
205
+ * (then the run's own deadline is the only bound, and a run WITH a deadline refuses an
206
+ * unbounded poll — see `assertWaitWithinDeadline`). */
207
+ readonly timeoutAtMs?: number;
208
+ /** Opaque JSON handed to the probe on every check. Journaled with the spec, so a resumed
209
+ * probe gets the same arguments. */
210
+ readonly args?: Record<string, unknown>;
211
+ };
212
+ /** Build a `timer` spec from a DURATION. The instant is resolved once, at arm time — a resumed
213
+ * wait re-uses the journaled instant, never a fresh `now + ms`. */
214
+ declare function timerAt(ms: number, now: number): WaitSpec;
215
+ /** Build a bounded `poll` spec from a duration. */
216
+ declare function pollFor(probe: string, opts: {
217
+ readonly intervalMs: number;
218
+ readonly timeoutMs?: number;
219
+ readonly args?: Record<string, unknown>;
220
+ }, now: number): WaitSpec;
221
+ /**
222
+ * A named predicate a `poll` node re-checks. Returns true when the condition it watches has
223
+ * flipped. A throw is treated as "not yet" (an unreachable CI endpoint is not a settled answer),
224
+ * and is counted in the outcome's `probeErrors` so a probe that never works is visible rather
225
+ * than silently polling forever.
226
+ */
227
+ type WaitProbe = (args: Record<string, unknown> | undefined, signal: AbortSignal) => boolean | Promise<boolean>;
228
+ /** Resolves a `poll` spec's `probe` name to its predicate. Threaded through `SupervisorOpts` so
229
+ * the SAME registry a fresh run used is what a resumed run re-resolves against. */
230
+ interface WaitProbeRegistry {
231
+ resolve(name: string): WaitProbe | undefined;
232
+ }
233
+ /** Registry over a plain name→predicate record. */
234
+ declare function createWaitProbes(entries: Record<string, WaitProbe>): WaitProbeRegistry;
235
+ /** The `out` a settled wait node delivers through `Scope.next()`. `settled` is the outcome the
236
+ * caller branches on: `'fired'` = the timer reached its instant or the predicate flipped;
237
+ * `'timeout'` = a bounded poll gave up. A timeout is a first-class ANSWER, not a failure — a
238
+ * wait only settles `down` when it is cancelled or aborted. */
239
+ interface WaitOutcome {
240
+ /** Tag for `isWaitOutcome` — a wait outcome arrives on the same cursor as worker outputs. */
241
+ readonly waitOutcome: true;
242
+ readonly kind: WaitSpec['kind'];
243
+ readonly settled: 'fired' | 'timeout';
244
+ readonly label: string;
245
+ /** The absolute instant this wait was armed for (timer `untilMs` / poll `timeoutAtMs`); absent
246
+ * for an unbounded poll. */
247
+ readonly untilMs?: number;
248
+ /** Epoch ms the wait was FIRST armed — preserved across a resume, so `wokenAt - armedAt` is
249
+ * the true end-to-end wait even when it spanned several processes. */
250
+ readonly armedAt: number;
251
+ readonly wokenAt: number;
252
+ /** Predicate checks performed in the process that settled it (a resume restarts this count). */
253
+ readonly polls: number;
254
+ /** Probe checks that threw (counted, not fatal). */
255
+ readonly probeErrors: number;
256
+ /** True when a later process re-armed this wait from the journal instead of creating it. */
257
+ readonly resumed: boolean;
258
+ }
259
+ /** Narrow a settlement's `out` to a wait outcome — a wait settles on the SAME cursor as workers,
260
+ * so a driver that mixes them tags them apart with this. */
261
+ declare function isWaitOutcome(value: unknown): value is WaitOutcome;
262
+ /** A wait recorded in the journal that never woke — what a resumed run re-arms. */
263
+ interface PendingWait {
264
+ readonly id: string;
265
+ readonly label: string;
266
+ readonly spec: WaitSpec;
267
+ /** The ORIGINAL arm instant. A re-armed wait keeps it, so its deadline never slides. */
268
+ readonly armedAt: number;
269
+ /** The wait ordinal in its parent scope, so a resumed scope continues past it. */
270
+ readonly ordinal: number;
271
+ }
272
+ /** Reject reasons for `Scope.wait`, mirroring `Scope.spawn`'s fail-closed admission shape. */
273
+ type WaitRejection = 'invalid-spec' | 'unknown-probe' | 'deadline-exceeded';
274
+ /** The absolute instant a spec is bounded by, or `undefined` for an unbounded poll. */
275
+ declare function waitUntil(spec: WaitSpec): number | undefined;
276
+ /** Structural validation, independent of the run. Returns null when the spec is usable. */
277
+ declare function validateWaitSpec(spec: WaitSpec): string | null;
278
+ //#endregion
279
+ //#region src/runtime/supervise/types.d.ts
280
+ /** Options for `Scope.wait`. `label` is the wait's identity within its parent scope — it is what
281
+ * a resumed run matches to re-adopt a journaled, still-unfired wait, so it must be stable across
282
+ * processes (a label derived from wall-clock would resume as a NEW wait). */
283
+ interface WaitOpts {
284
+ readonly label: string;
285
+ }
286
+ /**
287
+ * One self-similar atom. A leaf is an `Agent` that never calls `scope.spawn`; a driver
288
+ * is an `Agent` whose `act` spawns children and reacts to them via `scope.next()`. An
289
+ * analyst is an `Agent` whose task is "read these traces → findings" — `where` it runs
290
+ * is its executor, not a separate type.
291
+ *
292
+ * `act` MUST be replay-safe: it may read `verdict`, `spent`, and `out` (rehydrated by
293
+ * `outRef`) off each `Settled`; it MUST NOT read `Date.now`, `Math.random`, or any
294
+ * unordered collection. `scope.next()` delivers strictly in recorded `seq` order.
295
+ */
296
+ interface Agent<Task, Out> {
297
+ readonly name: string;
298
+ act(task: Task, scope: Scope<Out>): Promise<Out>;
299
+ }
300
+ /**
301
+ * The leaf runtime — ONE open interface, not a closed union. `execute` returns a
302
+ * `Promise<ExecutorResult>` for one-shot executors OR an `AsyncIterable<UsageEvent>` for
303
+ * streaming ones; a streaming executor reports incremental normalized usage as it runs
304
+ * (the budget pool reconciles against it) and exposes its terminal artifact via
305
+ * `resultArtifact()`. Both shapes normalize usage to `UsageEvent` so the conserved pool
306
+ * meters every runtime identically.
307
+ *
308
+ * Built-in implementations (in `runtime.ts`, NOT variants here): router/inline (a direct
309
+ * Router/HTTP inference call, no box), sandbox (COMPOSES `runAgentRounds` as a leaf, forwarding
310
+ * PR #150's optional `lineage` passthrough — does NOT reinvent checkpoint/fork), cli
311
+ * (Halo/RLM subprocess; `budgetExempt`, excluded from equal-k by construction). A user's
312
+ * own agent (mastra/agno/raw HTTP/anything) is first-class by implementing this interface.
313
+ */
314
+ interface Executor<Out> {
315
+ /** Stable runtime tag for traces + the equal-k exemption check. */
316
+ readonly runtime: Runtime;
317
+ /**
318
+ * When true, this executor's spend is NOT metered against the conserved pool and its
319
+ * iterations are excluded from the equal-k assertion (a `cli` subprocess without
320
+ * token accounting). Fail-loud everywhere else: a metered executor MUST report usage.
321
+ */
322
+ readonly budgetExempt?: boolean;
323
+ /**
324
+ * One-shot → resolves a `ExecutorResult`; streaming → yields incremental `UsageEvent`s and
325
+ * the terminal artifact is read from `resultArtifact()` after the stream drains.
326
+ * `signal` is the spawn-scoped abort (chains the acquire lifecycle for sandbox).
327
+ */
328
+ execute(task: unknown, signal: AbortSignal): Promise<ExecutorResult<Out>> | AsyncIterable<UsageEvent>;
329
+ /**
330
+ * Optional inbox: receive an out-of-band message from the driver mid-run (the `send`/`steer_agent`
331
+ * verb). A streaming executor drains pending messages between turns and folds them into the next
332
+ * step (a steer / interrupt / resume). A one-shot executor that can't be steered mid-flight omits
333
+ * this; `Scope.send` then returns `false` for it. Never throws — a malformed message is the
334
+ * executor's to ignore.
335
+ */
336
+ deliver?(msg: unknown): void;
337
+ /**
338
+ * Optional LIVE progress: what this worker is doing RIGHT NOW, read synchronously and
339
+ * cheaply while `execute` is still streaming. The scope already derives activity timing,
340
+ * turns, and spend from the metered usage stream for EVERY executor; this adds only what
341
+ * the executor alone knows — the harness's tool/file activity, its own turn count, and how
342
+ * many delivered steers it has not yet folded in. Never throws; a read that cannot be
343
+ * answered returns `undefined`.
344
+ *
345
+ * This is the observe half of steering: `deliver` lets a driver correct a worker, and this
346
+ * is the evidence it corrects FROM. An executor that implements neither cannot be supervised
347
+ * mid-flight — it can only be waited on.
348
+ */
349
+ progress?(): ExecutorProgress | undefined;
350
+ /**
351
+ * Optional live tool-call trace for the ONLINE detectors (`watchTrace`). An executor that
352
+ * can see its worker's tool calls exposes them here, so a supervisor can run the streaming
353
+ * repeated-action / error-streak panel over a RUNNING worker and raise a `finding` the
354
+ * moment it loops, instead of discovering it at settle. Omitted = no online detection for
355
+ * this runtime (the settle-time analyzers still work).
356
+ */
357
+ traceSource?(): TraceSource | undefined;
358
+ /**
359
+ * Tear the executor's resources down. `grace` mirrors the OTP shutdown spec
360
+ * (`'brutalKill'` = immediate, a number = ms grace, `'infinity'` = await clean exit).
361
+ */
362
+ teardown(grace: number | 'brutalKill' | 'infinity'): Promise<{
363
+ destroyed: boolean;
364
+ }>;
365
+ /**
366
+ * The replay source (B1): the content-addressed `outRef` + the materialized output the
367
+ * driver branched on, its verdict, and the conserved spend. Read once, after settle.
368
+ */
369
+ resultArtifact(): {
370
+ outRef: string;
371
+ out: Out;
372
+ verdict?: DefaultVerdict;
373
+ spent: Spend;
374
+ };
375
+ /**
376
+ * A driver-executor's OWN-inference subtree total (rolled up from its nested tree's `metered`
377
+ * events) — the parent scope journals it as a `metered` event for this node on settle, on BOTH
378
+ * the done AND the down/crash paths, so a crashed sub-driver's partial inference still re-homes
379
+ * (the pool already debited it via `observe`; the journal must match). NOT reconciled, so it never
380
+ * trips the reservation clamp. Read on settle, valid after `execute` resolves OR throws. Leaf
381
+ * executors omit it (returns `undefined`).
382
+ */
383
+ metered?(): Spend | undefined;
384
+ }
385
+ /** Terminal artifact of a one-shot `Executor.execute`. */
386
+ interface ExecutorResult<Out> {
387
+ outRef: string;
388
+ out: Out;
389
+ verdict?: DefaultVerdict;
390
+ spent: Spend;
391
+ }
392
+ /**
393
+ * Normalized usage event — the single channel every executor reports through, so the
394
+ * conserved pool meters all runtimes identically. `tokens` carries `LoopTokenUsage`'s
395
+ * `{ input, output }`; `usd` is a SEPARATE channel (never folded into tokens).
396
+ */
397
+ type UsageEvent = {
398
+ kind: 'tokens';
399
+ input: number;
400
+ output: number;
401
+ } | {
402
+ kind: 'cost';
403
+ usd: number;
404
+ } | {
405
+ kind: 'iteration';
406
+ };
407
+ /** The runtime tag of a `Executor` impl. Open by intent: custom runtimes use their own string name.
408
+ * External executors can register additional runtime strings without widening this type. */
409
+ type Runtime = 'router' | 'inline' | 'sandbox' | 'cli' | (string & {});
410
+ /**
411
+ * `AgentProfile` does NOT carry a `harness`/backend field — `harness` lives on the
412
+ * sandbox SDK's `BackendConfig`, not the portable profile. So an agent is mapped to its
413
+ * executor through this MINIMAL wrapper, never by fabricating a field onto `AgentProfile`.
414
+ *
415
+ * Resolution (in `runtime.ts`):
416
+ * - `executor` present → BYO: use it verbatim (a user's own `Executor`).
417
+ * - `harness === null` → router/inline: a direct Router call, no box.
418
+ * - `harness` is a `BackendType` → sandbox: compose `runAgentRounds` against `profile` on that backend.
419
+ * Fail loud on an unresolvable spec (no executor and an unknown harness).
420
+ */
421
+ interface AgentSpec {
422
+ readonly profile: AgentProfile$1;
423
+ /** `null` selects router/inline; a `BackendType` selects the sandboxed harness. */
424
+ readonly harness: BackendType | null;
425
+ /** Bring-your-own executor: when set, overrides harness-based resolution entirely. */
426
+ readonly executor?: Executor<unknown>;
427
+ }
428
+ /**
429
+ * Builds a fresh `Executor` for one spawn from the resolved spec. Per-spawn (not
430
+ * shared) so each child owns its own box/abort/teardown lifecycle. A BYO factory lets a
431
+ * user supply construction args without pre-instantiating.
432
+ */
433
+ type ExecutorFactory<Out> = (spec: AgentSpec, ctx: ExecutorContext) => Executor<Out>;
434
+ /** Construction context handed to a `ExecutorFactory` — the seams a built-in needs
435
+ * (sandbox client for the sandbox executor, router config for router/inline) without
436
+ * the factory reaching into module globals. */
437
+ interface ExecutorContext {
438
+ readonly signal: AbortSignal;
439
+ /** Opaque seams the registry threads through; a built-in narrows what it needs. */
440
+ readonly seams: Readonly<Record<string, unknown>>;
441
+ }
442
+ /**
443
+ * The OPEN resolver: maps an `AgentSpec` to a `ExecutorFactory`. The default
444
+ * registry resolves the three built-ins AND accepts a BYO `executor`/factory; callers
445
+ * register more runtimes by name. NOT a closed switch — registration is the extension
446
+ * point, mirroring the open `Executor` interface.
447
+ */
448
+ interface ExecutorRegistry {
449
+ /** Register a factory for a named runtime. Throws on a duplicate name (fail loud). */
450
+ register<Out>(runtime: Runtime, factory: ExecutorFactory<Out>): void;
451
+ /**
452
+ * Resolve a spec to a factory. Precedence: a BYO `spec.executor` → a trivial factory
453
+ * returning it; else `harness === null` → the `'router'` factory; else a registered
454
+ * factory for the harness-derived runtime. Returns a typed outcome — the caller
455
+ * inspects `succeeded` before `value` (no silent fallback).
456
+ */
457
+ resolve<Out>(spec: AgentSpec): {
458
+ succeeded: true;
459
+ value: ExecutorFactory<Out>;
460
+ } | {
461
+ succeeded: false;
462
+ error: string;
463
+ };
464
+ }
465
+ /** A budget envelope on a spawn or the root. All ceilings; the pool reserves against them. */
466
+ interface Budget {
467
+ readonly maxIterations: number;
468
+ readonly maxTokens: number;
469
+ readonly maxUsd?: number;
470
+ readonly deadlineMs?: number;
471
+ }
472
+ /** Conserved spend, reconciled from the normalized `UsageEvent` stream. Tokens and usd
473
+ * are separate channels (never folded). */
474
+ interface Spend {
475
+ iterations: number;
476
+ tokens: LoopTokenUsage;
477
+ /** Dollar accounting is known unless explicitly false. A false value must not be treated as $0
478
+ * when enforcing a dollar-denominated comparison or limit. */
479
+ usdKnown?: boolean;
480
+ usd: number;
481
+ ms: number;
482
+ }
483
+ /** OTP child-spec restart class. */
484
+ type Restart = 'temporary' | 'transient' | 'permanent';
485
+ /** `'acquiring'` is first-class (M1): a node spends real time + reaps an orphan box
486
+ * during sandbox acquire BEFORE it is `running`, so abort must be defined over it.
487
+ * `'waiting'` is first-class for the opposite reason: a wait-state node holds NO executor, NO
488
+ * box, and no conserved budget — it is neither in flight nor settled, so neither `inFlight` nor
489
+ * a terminal status describes it (see `Scope.wait`). */
490
+ type NodeStatus = 'pending' | 'acquiring' | 'running' | 'waiting' | 'done' | 'failed' | 'cancelled';
491
+ /** Deterministic node id — `${parent}:s${seq}` from the cursor order, never wall-clock. */
492
+ type NodeId = string;
493
+ interface SpawnOpts {
494
+ readonly budget: Budget;
495
+ readonly label: string;
496
+ readonly restart?: Restart;
497
+ /** Teardown grace handed to the executor when this node is reaped. */
498
+ readonly shutdown?: number | 'brutalKill' | 'infinity';
499
+ }
500
+ /**
501
+ * A live child handle. `abort()` is defined over the ACQUIRE lifecycle: it chains into
502
+ * the `acquireSandbox` signal and reaps a find-by-name orphan box, so a node aborted
503
+ * mid-acquire never leaks (M1).
504
+ */
505
+ interface Handle<Out> {
506
+ readonly id: NodeId;
507
+ readonly label: string;
508
+ readonly status: NodeStatus;
509
+ abort(reason?: string): void;
510
+ /** Phantom: binds the handle to the child's output type so `spawn<C>` returns a
511
+ * `Handle<C>` distinct from a `Handle<other>`. Type-only — never present at runtime. */
512
+ readonly __out?: Out;
513
+ }
514
+ /**
515
+ * A settled child, delivered by `scope.next()`. `seq` is the monotonic cursor order
516
+ * `next()` yielded this settlement (B2) — NOT wall-clock — and replay delivers strictly
517
+ * in `seq` order. `outRef` rehydrates `out` from the `ResultBlobStore` on replay.
518
+ */
519
+ type Settled<Out> = {
520
+ kind: 'done';
521
+ handle: Handle<Out>;
522
+ out: Out;
523
+ outRef: string;
524
+ verdict?: DefaultVerdict;
525
+ spent: Spend;
526
+ seq: number;
527
+ } | {
528
+ kind: 'down';
529
+ handle: Handle<Out>;
530
+ reason: string;
531
+ /** True = infrastructure failure (excluded from merge `n` / equal-k), not a bad result. */
532
+ infra: boolean;
533
+ restartCount: number;
534
+ seq: number;
535
+ };
536
+ /**
537
+ * The budget-conserving reactive scope an `Agent.act` runs inside. `spawn` reserves
538
+ * budget atomically from the shared pool and fails closed when the pool cannot cover it.
539
+ * `next()` waits for one settlement from this scope's live set; `view` reads live state,
540
+ * not the replay log.
541
+ */
542
+ interface Scope<Out> {
543
+ /**
544
+ * Spawn a child. Reserves `opts.budget` from the conserved pool atomically; refunds the
545
+ * unspent remainder on settle. Returns a typed outcome — fail-closed on an exhausted
546
+ * pool or an exceeded depth ceiling (the caller inspects `ok` before `handle`).
547
+ */
548
+ spawn<C extends Out>(agent: Agent<unknown, C>, task: unknown, opts: SpawnOpts): {
549
+ ok: true;
550
+ handle: Handle<C>;
551
+ } | {
552
+ ok: false;
553
+ reason: 'budget-exhausted' | 'depth-exceeded';
554
+ };
555
+ /** ray.wait n=1 over this scope's in-memory live set; resolves as each child settles;
556
+ * `null` when the live set is empty. */
557
+ next(): Promise<Settled<Out> | null>;
558
+ /**
559
+ * Non-blocking twin of `next()`: deliver an ALREADY-settled, undelivered child, or `null`
560
+ * when none is ready — never awaits a live child. The driver's post-loop drain reads this so
561
+ * a child that settled while the driver was busy (or after it stopped pulling) still reaches
562
+ * the finalize ledger instead of being silently lost.
563
+ */
564
+ nextResolved(): Promise<Settled<Out> | null>;
565
+ /**
566
+ * Steer a RUNNING child out-of-band — deliver a message to its executor's inbox (the driver's
567
+ * `send` verb: next-instruction, interrupt, or resume). Returns `true` if the message was
568
+ * delivered to a live child whose executor accepts delivery, `false` otherwise (unknown id,
569
+ * already settled, or an executor with no inbox). The executor drains its inbox between turns;
570
+ * a leaf that does not implement `deliver` simply cannot be steered mid-flight. In-process this
571
+ * is a direct call; the sandbox/Agent-Bus transports surface the SAME verb as an MCP tool.
572
+ */
573
+ send(nodeId: NodeId, msg: unknown): boolean;
574
+ /**
575
+ * Arm a WAIT-STATE node: a first-class tree node that waits on wall-clock time (`timer`) or on
576
+ * a named external predicate (`poll`) and settles through THIS scope's `next()` cursor like any
577
+ * other child — but holds no executor, no sandbox, and no conserved budget. Waiting costs zero
578
+ * tokens and zero dollars by construction.
579
+ *
580
+ * It is journaled (`waiting` → `woken`) with its ABSOLUTE deadline, so a run that dies mid-wait
581
+ * resumes still waiting: the supervisor surfaces the un-woken waits on `Scope.resume.waits`, and
582
+ * re-arming the same `label` adopts the recorded node id and original instant instead of
583
+ * restarting the countdown.
584
+ *
585
+ * Fail-closed admission, mirroring `spawn`: `invalid-spec`, `unknown-probe` (a `poll` naming a
586
+ * predicate this run's registry cannot resolve), or `deadline-exceeded` (the wait would outlive
587
+ * the pool's hard wall-clock ceiling — a wait never extends a budget guard).
588
+ *
589
+ * NOT `await_event`: that is an in-run rendezvous on the coordination bus whose 15s fence makes
590
+ * the caller re-poll — each re-poll a driver inference turn against a process that must stay up,
591
+ * and nothing about it survives a restart. See `supervise/wait.ts`.
592
+ */
593
+ wait(spec: WaitSpec, opts: WaitOpts): {
594
+ ok: true;
595
+ handle: Handle<WaitOutcome>;
596
+ } | {
597
+ ok: false;
598
+ reason: WaitRejection;
599
+ };
600
+ /**
601
+ * The LIVE read-model of one child, valid WHILE it runs: last-activity timestamp, idle time,
602
+ * a derived `stalled` flag, tokens/turns spent so far, whether a steer can even reach it
603
+ * (`steerable`), and whatever tool activity its executor exposes. `undefined` for an unknown
604
+ * id. This is the counterpart to `send`: a driver that can steer but cannot observe has
605
+ * nothing to steer on, which is precisely why steering went unused.
606
+ *
607
+ * Pull-based and side-effect free — reading it starts no timer and spends nothing. `now` and
608
+ * `stallAfterMs` are injectable so a caller (and a test) controls what counts as stalled.
609
+ */
610
+ progress(nodeId: NodeId, opts?: {
611
+ now?: number;
612
+ stallAfterMs?: number;
613
+ }): WorkerProgress | undefined;
614
+ /** The live tool-call trace of one child when its executor exposes one (`Executor.traceSource`),
615
+ * for running the online detector panel over a RUNNING worker. `undefined` otherwise. */
616
+ traceSource(nodeId: NodeId): TraceSource | undefined;
617
+ /** This scope's abort signal — aborted when the run is cancelled, a breaker trips, the pool
618
+ * is exhausted, or a parent scope cascades. A long-running driver `act` over this scope reads
619
+ * it to break promptly (the conserved pool + driver-stop are the other bounds). A nested
620
+ * scope carries its own signal, chained off its driver child's abort. */
621
+ readonly signal: AbortSignal;
622
+ /**
623
+ * Meter the driver's OWN compute against the conserved pool — its inference turns, which are
624
+ * real tokens/usd but not a spawned child (no reserve/reconcile). A direct `free → committed`
625
+ * debit, so equal-k counts the driver's tokens AND the in-loop budget guard (`budget.tokensLeft`)
626
+ * halts a driver that thinks the pool dry. `detail` rides an `agent.turn` trace event for live
627
+ * observability (turn index, tool calls, cumulative spend). It also journals a `metered` event —
628
+ * the durable twin of the pool debit (as `settled` is the twin of `reconcile`) — so every
629
+ * journal-based cost reader (`spentFromJournal`, `trajectoryReport`) sums driver inference
630
+ * automatically. A leaf never calls this; a driver meters each chat turn and awaits it (the
631
+ * metered event is cost-critical, so it lands before the join-barrier roll-up).
632
+ */
633
+ meter(spend: Spend, detail?: Record<string, unknown>): Promise<void>;
634
+ /**
635
+ * Prior committed work, present ONLY on a resumed run (`undefined` on a fresh run, which is
636
+ * every run that did not pass `SupervisorOpts.resume`). The supervisor `loadTree`s the journal
637
+ * first; when a non-empty tree exists it rehydrates the already-settled children (via
638
+ * `replaySpawnTree`) and hands them here so a resume-aware `act` re-uses them instead of
639
+ * re-spawning committed work. A resume-blind driver simply ignores it and re-spawns — correct
640
+ * but redundant. The scope's spawn ordinal + cursor seq are already advanced past the recorded
641
+ * maxima, so any NEW spawn appends without colliding with a journaled event.
642
+ */
643
+ readonly resume?: ResumedWork<Out>;
644
+ /** The live tree — reads the in-memory nursery, not the journal. */
645
+ readonly view: TreeView;
646
+ /** Conserved-pool readouts (post-reservation). */
647
+ readonly budget: Readonly<{
648
+ tokensLeft: number;
649
+ usdLeft: number;
650
+ usdCapped: boolean;
651
+ deadlineMs: number;
652
+ reservedTokens: number;
653
+ }>;
654
+ }
655
+ /**
656
+ * The committed work a resumed run inherits from its journal. `settled` is the replayed
657
+ * `Settled[]` (cursor-ordered, rehydrated from the blob store by `replaySpawnTree`); `view`
658
+ * is the tree as `materializeTreeView` folded it at the recorded cursor position. A
659
+ * resume-aware `act` reads `scope.resume?.settled` to pick up where the crashed run left off.
660
+ */
661
+ interface ResumedWork<Out> {
662
+ readonly settled: ReadonlyArray<Settled<Out>>;
663
+ readonly view: TreeView;
664
+ /**
665
+ * Wait-state nodes the journal shows as ARMED but never woken — the run died mid-wait. Each
666
+ * carries the ORIGINAL arm instant and absolute deadline, so re-arming the same `label` through
667
+ * `Scope.wait` resumes the countdown instead of restarting it. Empty on a fresh run and on a
668
+ * resumed run that was not waiting.
669
+ */
670
+ readonly waits: ReadonlyArray<PendingWait>;
671
+ }
672
+ interface NodeSnapshot {
673
+ readonly id: NodeId;
674
+ readonly parent?: NodeId;
675
+ readonly label: string;
676
+ readonly status: NodeStatus;
677
+ readonly runtime: Runtime;
678
+ readonly budget: Budget;
679
+ /** Conserved spend so far for this node. */
680
+ readonly spent: Spend;
681
+ /** `outRef` once the node is `done` (the replay/result pointer). */
682
+ readonly outRef?: string;
683
+ }
684
+ /** The live tree — what `scope.view` / `RootHandle.view()` materialize for a viewer. */
685
+ interface TreeView {
686
+ readonly root: NodeId;
687
+ readonly nodes: ReadonlyArray<NodeSnapshot>;
688
+ /** Count of nodes in `running` or `acquiring` — the "what's in flow?" answer. */
689
+ readonly inFlight: number;
690
+ /** Count of nodes in `waiting` — armed wait-states. Deliberately NOT folded into `inFlight`:
691
+ * a wait burns no executor and no budget, so counting it as flow would misreport both idle
692
+ * capacity and how much work is actually running. */
693
+ readonly waiting: number;
694
+ }
695
+ /** Journaled spawn-tree events (B1/B2). `seq` is the cursor order; `at` is an ISO
696
+ * timestamp for human inspection only (NOT a replay input). */
697
+ type SpawnEvent = {
698
+ kind: 'spawned';
699
+ id: NodeId;
700
+ parent?: NodeId;
701
+ label: string;
702
+ budget: Budget;
703
+ runtime: Runtime;
704
+ seq: number;
705
+ at: string;
706
+ } | {
707
+ kind: 'settled';
708
+ id: NodeId;
709
+ status: 'done' | 'down';
710
+ /** Content-addressed result pointer; rehydrates `out` from `ResultBlobStore`. */
711
+ outRef?: string;
712
+ verdict?: DefaultVerdict;
713
+ spent: Spend;
714
+ infra?: boolean;
715
+ seq: number;
716
+ at: string;
717
+ } | {
718
+ kind: 'cancelled';
719
+ id: NodeId;
720
+ reason: string;
721
+ seq: number;
722
+ at: string;
723
+ } | {
724
+ /** A wait-state node was ARMED. Lives in the SPAWN-ORDINAL namespace (`seq` is the wait
725
+ * ordinal within its parent scope), exactly like `spawned` — it creates a node, it does not
726
+ * settle one. It carries the whole `spec` and the original `armedAt` so a brand-new process
727
+ * re-arms the identical wait with the identical ABSOLUTE deadline. */
728
+ kind: 'waiting';
729
+ id: NodeId;
730
+ parent?: NodeId;
731
+ label: string;
732
+ spec: WaitSpec;
733
+ armedAt: number;
734
+ seq: number;
735
+ at: string;
736
+ } | {
737
+ /** A wait-state node SETTLED — the cursor-namespace twin of `settled`, kept distinct so a
738
+ * reader can tell zero-cost waiting apart from paid work without inspecting payloads. A
739
+ * wait carries no `spent` (it is free by construction, not by measurement); `outRef`
740
+ * rehydrates its `WaitOutcome`, absent when the wait was cancelled. */
741
+ kind: 'woken';
742
+ id: NodeId;
743
+ by: 'fired' | 'timeout' | 'cancelled';
744
+ outRef?: string;
745
+ seq: number;
746
+ at: string;
747
+ } | {
748
+ /** A driver's OWN inference spend, journaled separately from spawned-child work — the journal
749
+ * TWIN of `BudgetPool.observe`, exactly as `settled` is the twin of `reconcile`. So every
750
+ * journal-based cost reader sums it automatically — the journal is the single cost ledger.
751
+ * It carries spend only and is NOT a settlement: replay + `materializeTreeView` skip it for
752
+ * structure, and its `seq` lives outside the cursor-uniqueness namespace. A
753
+ * driver re-homes its nested subtree's metered total up to its parent (like settled spend),
754
+ * so summing any sub-tree root yields that sub-tree's true driver-inference cost. */
755
+ kind: 'metered';
756
+ id: NodeId;
757
+ spend: Spend;
758
+ seq: number;
759
+ at: string;
760
+ };
761
+ /**
762
+ * The spawn-tree event source (mirrors `ConversationJournal`'s begin/append/load shape).
763
+ * `loadTree` returns events for inspection and completed-settlement replay, not live process
764
+ * recovery; `appendEvent` runs only AFTER the event is observed-committed (never speculative).
765
+ */
766
+ interface SpawnJournal {
767
+ loadTree(root: NodeId): Promise<SpawnEvent[] | undefined>;
768
+ beginTree(root: NodeId, at: string): Promise<void>;
769
+ appendEvent(root: NodeId, ev: SpawnEvent): Promise<void>;
770
+ }
771
+ /** Content-addressed result blobs (the `outRef` → artifact map) backing the replay
772
+ * invariant. Split from the journal so the journal stays small (decisions) and the
773
+ * payloads (evidence) live where a viewer/replayer rehydrates them. */
774
+ interface ResultBlobStore {
775
+ put(outRef: string, artifact: unknown): Promise<void>;
776
+ get(outRef: string): Promise<unknown | undefined>;
777
+ }
778
+ /**
779
+ * Owns the conserved pool, the spawn log, the abort cascade, the OTP intensity breaker,
780
+ * and the root handle. `run` executes the root `Agent` to completion; `attach` wires a
781
+ * live `RootHandle` (the Q2 substrate the chat/pi-viz client later consumes).
782
+ */
783
+ interface Supervisor<Task, Out> {
784
+ run(root: Agent<Task, Out>, task: Task, opts: SupervisorOpts): Promise<SupervisedResult<Out>>;
785
+ attach(h: RootHandle<Out>): void;
786
+ }
787
+ interface SupervisorOpts {
788
+ /** The root conserved-pool ceiling (tokens + usd + iterations + deadline). */
789
+ readonly budget: Budget;
790
+ /** Trace-correlation root + the journal/blob root key. */
791
+ readonly runId: NodeId;
792
+ /** Event source — defaults to the in-memory journal in the impl; pass JSONL/FS for durability. */
793
+ readonly journal: SpawnJournal;
794
+ /** Result payload store backing `outRef` rehydration. */
795
+ readonly blobs: ResultBlobStore;
796
+ /** Executor resolution — the open registry mapping `AgentSpec` → `Executor`. */
797
+ readonly executors: ExecutorRegistry;
798
+ /** Predicate resolution for `poll` wait-states (`Scope.wait`). A `poll` names its predicate so
799
+ * the wait can be journaled and re-armed by a later process; this is what the name resolves
800
+ * against. Unset ⇒ `poll` waits are refused (`unknown-probe`); `timer` waits are unaffected. */
801
+ readonly probes?: WaitProbeRegistry;
802
+ /** Runtime recursion-depth ceiling (paired with the conserved pool per R3). */
803
+ readonly maxDepth?: number;
804
+ /**
805
+ * OTP intensity breaker: more than `maxRestarts` child restarts within `withinMs`
806
+ * trips the supervisor to `no-winner` rather than restarting forever.
807
+ */
808
+ readonly maxRestarts?: number;
809
+ readonly withinMs?: number;
810
+ /**
811
+ * Opt into RESUME-FIRST: read any prior journal tree for this `runId` BEFORE beginning a fresh
812
+ * one, and when a non-empty tree exists rehydrate its committed work onto `Scope.resume`
813
+ * (`replaySpawnTree` + `materializeTreeView`) instead of starting over. Requires a journal +
814
+ * blob store that OUTLIVE the process (`createFileRunContext(dir)`); against the in-memory
815
+ * stores there is never a prior tree, so it is a no-op.
816
+ *
817
+ * Default `false` — a run always begins a fresh tree, which is the behavior every existing
818
+ * consumer has. Resume is a durability contract the caller opts into, never a silent default.
819
+ */
820
+ readonly resume?: boolean;
821
+ readonly now?: () => number;
822
+ readonly signal?: AbortSignal;
823
+ /** Lifecycle stream sink, threaded into the root `Scope` so every `spawn`/settle emits on the
824
+ * same `agent.spawn`/`agent.child` stream `runAgentRounds` feeds — one observable recursive tree. */
825
+ readonly hooks?: RuntimeHooks;
826
+ }
827
+ /** Typed terminal result (M2) — a no-winner is NEVER coerced to a best-effort output. */
828
+ type SupervisedResult<Out> = {
829
+ kind: 'winner';
830
+ out: Out;
831
+ outRef: string;
832
+ verdict?: DefaultVerdict;
833
+ tree: TreeView;
834
+ spentTotal: Spend;
835
+ /** Where `spentTotal` went: `driverInference` = the drivers' own chat turns (metered via
836
+ * `Scope.meter`); `childWork` = every spawned child's reconciled spend (the journal sum).
837
+ * `driverInference + childWork === spentTotal`. Present whenever any driver metered. */
838
+ spentBreakdown?: {
839
+ driverInference: Spend;
840
+ childWork: Spend;
841
+ };
842
+ } | {
843
+ kind: 'no-winner';
844
+ reason: 'all-children-down' | 'budget-exhausted' | 'aborted';
845
+ tree: TreeView;
846
+ downCount: number;
847
+ /** The conserved spend incurred before the run failed — real cost is paid even when no
848
+ * worker delivers, so the caller always learns what the delegation actually spent. Summed
849
+ * off the same journal the `winner` path reads. */
850
+ spentTotal: Spend;
851
+ };
852
+ /** Live root handle — the substrate a chat/pi-viz client attaches to (Q2). `signal`
853
+ * delivers an out-of-band message to the running root; `view()` materializes the tree. */
854
+ interface RootHandle<Out> {
855
+ view(): TreeView;
856
+ signal(msg: RootSignal): void;
857
+ abort(reason?: string): void;
858
+ /** Phantom: binds the handle to the supervised run's output type. Type-only — never
859
+ * present at runtime; lets `attach(h: RootHandle<Out>)` stay output-typed. */
860
+ readonly __out?: Out;
861
+ }
862
+ /** Out-of-band message to a running root. Open by intent — a client extends it. */
863
+ type RootSignal = {
864
+ kind: 'pause';
865
+ } | {
866
+ kind: 'resume';
867
+ } | {
868
+ kind: 'cancel';
869
+ reason?: string;
870
+ } | {
871
+ kind: 'ask';
872
+ question: string;
873
+ };
874
+ /**
875
+ * The progressive-widening gate (MCTS-PW). Decides whether a settled child is
876
+ * `promising` enough to spawn another under the remaining pool. DEFAULTS TO FLAT
877
+ * (`shouldWiden` always false) so a gate run never widens and the selector≠judge
878
+ * firewall conflict (R2) stays dormant. When widening IS enabled, `promising` MUST be
879
+ * derived from TRACE findings (`analyses`), never raw `verdict` — or the gate carries
880
+ * an explicit, argued `judgeExempt: true` (the documented escape hatch, off by default).
881
+ */
882
+ interface WidenGate<Out> {
883
+ /** Default impl returns false for every settlement (flat — never widens). */
884
+ shouldWiden(settled: Settled<Out>, budget: Scope<Out>['budget']): boolean;
885
+ /** When true, widening may read `verdict` directly (collides with the steer firewall —
886
+ * must be explicitly argued per cell, never defaulted on). */
887
+ readonly judgeExempt?: boolean;
888
+ }
889
+ //#endregion
890
+ //#region src/runtime/tangle-sandbox-exact-process-provider.d.ts
891
+ type SandboxControlClient = Pick<Sandbox, 'create' | 'get' | 'list'>;
892
+ interface CreateTangleSandboxExactProcessProviderOptions {
893
+ name?: string;
894
+ }
895
+ /**
896
+ * Adapt Tangle Sandbox's managed control runtime to Runtime's exact-process provider.
897
+ *
898
+ * The adapter deliberately exposes no ordinary agent environment: an exact experiment
899
+ * must start a fresh Sandbox with no managed agent and launch its declared argv directly.
900
+ */
901
+ declare function createTangleSandboxExactProcessProvider(client: SandboxControlClient, options?: CreateTangleSandboxExactProcessProviderOptions): AgentEnvironmentProvider;
902
+ //#endregion
903
+ //#region src/runtime/environment-provider.d.ts
904
+ /** Provider object or registry name accepted by runtime provider adapters.
905
+ * @experimental */
906
+ type AgentEnvironmentProviderRef = AgentEnvironmentProvider | string;
907
+ /** In-memory registry for named `AgentEnvironmentProvider` instances.
908
+ * @experimental */
909
+ interface AgentEnvironmentProviderRegistry {
910
+ register(provider: AgentEnvironmentProvider, options?: {
911
+ replace?: boolean;
912
+ }): void;
913
+ has(name: string): boolean;
914
+ get(name: string): AgentEnvironmentProvider | undefined;
915
+ require(name: string): AgentEnvironmentProvider;
916
+ names(): string[];
917
+ providers(): AgentEnvironmentProvider[];
918
+ capabilities(name: string): Promise<AgentEnvironmentCapabilities>;
919
+ }
920
+ /** Create a registry that resolves provider names to concrete provider instances.
921
+ * @experimental */
922
+ declare function createAgentEnvironmentProviderRegistry(providers?: Iterable<AgentEnvironmentProvider>): AgentEnvironmentProviderRegistry;
923
+ /** Resolve a provider instance or registry name, failing loudly when a name is unknown.
924
+ * @experimental */
925
+ declare function resolveAgentEnvironmentProvider(provider: AgentEnvironmentProviderRef, registry?: AgentEnvironmentProviderRegistry): AgentEnvironmentProvider;
926
+ /** Options for exposing an `AgentEnvironmentProvider` through the legacy sandbox client port.
927
+ * @experimental */
928
+ interface ProviderAsSandboxClientOptions {
929
+ defaults?: Partial<CreateAgentEnvironmentInput>;
930
+ requireTerminalEvent?: boolean;
931
+ mapCreateOptions?: (options: CreateSandboxOptions | undefined) => Partial<CreateAgentEnvironmentInput>;
932
+ }
933
+ /** Adapt a neutral environment provider to the `SandboxClient` interface used by existing loop paths.
934
+ * @experimental */
935
+ declare function providerAsSandboxClient(provider: AgentEnvironmentProvider, options?: ProviderAsSandboxClientOptions): SandboxClient;
936
+ /** Options for wrapping the current Tangle sandbox client as an environment provider.
937
+ * @experimental */
938
+ interface SandboxClientProviderOptions {
939
+ name?: string;
940
+ defaultBackend?: BackendType;
941
+ capabilities?: AgentEnvironmentCapabilities | (() => AgentEnvironmentCapabilities | Promise<AgentEnvironmentCapabilities>);
942
+ validateProfile?: (profile: AgentProfileRef) => AgentProfileValidationResult | Promise<AgentProfileValidationResult>;
943
+ /** Resolve a named profile before calling Sandbox, which accepts inline profiles only. */
944
+ resolveProfile?: (profileId: string) => AgentProfile$1 | Promise<AgentProfile$1>;
945
+ mapCreateInput?: (input: CreateAgentEnvironmentInput) => CreateSandboxOptions;
946
+ }
947
+ /** Adapt a `SandboxClient` into the shared `AgentEnvironmentProvider` contract.
948
+ * @experimental */
949
+ declare function sandboxClientAsProvider(client: SandboxClient, options?: SandboxClientProviderOptions): AgentEnvironmentProvider;
950
+ /** Options for running a provider as a supervise-mode executor.
951
+ * @experimental */
952
+ interface ProviderExecutorOptions {
953
+ defaults?: Partial<CreateAgentEnvironmentInput>;
954
+ runtime?: Runtime;
955
+ destroyOnSettle?: boolean;
956
+ requireTerminalEvent?: boolean;
957
+ taskToTurn?: (task: unknown, specProfile: AgentProfile$1) => AgentTurnInput;
958
+ }
959
+ /** Adapt an environment provider into an `ExecutorFactory` for `createExecutor`.
960
+ * @experimental */
961
+ declare function providerAsExecutor(provider: AgentEnvironmentProvider, options?: ProviderExecutorOptions): ExecutorFactory<unknown>;
962
+ //#endregion
963
+ export { RootSignal as $, providerAsSandboxClient as A, createPushTraceSource as At, Executor as B, readWorkerProgress as Bt, ProviderAsSandboxClientOptions as C, timerAt as Ct, WorkspaceRequest as D, SessionTraceBox as Dt, SandboxClientProviderOptions as E, SessionMessageLike as Et, createTangleSandboxExactProcessProvider as F, DEFAULT_STALL_AFTER_MS as Ft, Handle as G, ExecutorFactory as H, Agent as I, ExecutorProgress as It, NodeStatus as J, NodeId as K, AgentSpec as L, ScopeProgressInput as Lt, sandboxClientAsProvider as M, sandboxSessionTraceSource as Mt, CreateTangleSandboxExactProcessProviderOptions as N, ActivityLog as Nt, createAgentEnvironmentProviderRegistry as O, ToolStepInput as Ot, SandboxControlClient as P, ActivityNote as Pt, RootHandle as Q, Budget as R, WorkerProgress as Rt, PlacementInfo as S, pollFor as St, ResourceRequest as T, waitUntil as Tt, ExecutorRegistry as U, ExecutorContext as V, ExecutorResult as W, ResultBlobStore as X, Restart as Y, ResumedWork as Z, CheckpointRequest as _, WaitProbeRegistry as _t, AgentEnvironmentProviderRef as a, SpawnOpts as at, ExecResult as b, createWaitProbes as bt, AgentEnvironmentStatus as c, Supervisor as ct, AgentSession as d, UsageEvent as dt, Runtime as et, AgentSessionRef as f, WaitOpts as ft, CheckpointRef as g, WaitProbe as gt, AgentTurnResult as h, WaitOutcome as ht, AgentEnvironmentProvider$1 as i, SpawnJournal as it, resolveAgentEnvironmentProvider as j, decodeToolPart as jt, providerAsExecutor as k, TraceSource as kt, AgentEnvironmentSummary as l, SupervisorOpts as lt, AgentTurnInput$1 as m, PendingWait as mt, AgentEnvironmentCapabilities$1 as n, Settled as nt, AgentEnvironmentProviderRegistry as o, Spend as ot, AgentSessionStatus as p, WidenGate as pt, NodeSnapshot as q, AgentEnvironmentEvent as r, SpawnEvent as rt, AgentEnvironmentQuery as s, SupervisedResult as st, AgentEnvironment as t, Scope as tt, AgentProfileRef$1 as u, TreeView as ut, CreateAgentEnvironmentInput$1 as v, WaitRejection as vt, ProviderExecutorOptions as w, validateWaitSpec as wt, ForkRequest as x, isWaitOutcome as xt, ExecRequest as y, WaitSpec as yt, DefaultVerdict as z, createActivityLog as zt };
964
+ //# sourceMappingURL=environment-provider-IUGU3epE.d.ts.map