@demlik/tea 0.1.2 → 0.3.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 (212) hide show
  1. package/README.md +49 -0
  2. package/dist/agent/index.d.ts +16 -770
  3. package/dist/agent/index.js +18 -16
  4. package/dist/authed-call/index.d.ts +3 -3
  5. package/dist/authed-call/index.js +22 -36
  6. package/dist/authed-call/index.js.map +1 -1
  7. package/dist/await-terminal/index.d.ts +2 -2
  8. package/dist/await-terminal/index.js +2 -2
  9. package/dist/batch-window/index.d.ts +3 -3
  10. package/dist/batch-window/index.js +3 -3
  11. package/dist/cache/index.d.ts +2 -2
  12. package/dist/cache/index.js +5 -2
  13. package/dist/{chunk-3545BOYL.js → chunk-25LBDCBC.js} +6 -5
  14. package/dist/chunk-25LBDCBC.js.map +1 -0
  15. package/dist/{chunk-IN33Q4VJ.js → chunk-2KNLKQVN.js} +3 -3
  16. package/dist/{chunk-IN33Q4VJ.js.map → chunk-2KNLKQVN.js.map} +1 -1
  17. package/dist/{chunk-MMH7CW5K.js → chunk-BP2R7TPP.js} +216 -157
  18. package/dist/chunk-BP2R7TPP.js.map +1 -0
  19. package/dist/chunk-C6QC273X.js +71 -0
  20. package/dist/chunk-C6QC273X.js.map +1 -0
  21. package/dist/{chunk-7W4LMPUW.js → chunk-CAXMQJJ3.js} +17 -24
  22. package/dist/chunk-CAXMQJJ3.js.map +1 -0
  23. package/dist/{chunk-UV6UWGEO.js → chunk-D736QUGF.js} +6 -5
  24. package/dist/chunk-D736QUGF.js.map +1 -0
  25. package/dist/chunk-EWJP3YYP.js +21 -0
  26. package/dist/chunk-EWJP3YYP.js.map +1 -0
  27. package/dist/{chunk-TGG26XMK.js → chunk-FV3Z5MBE.js} +10 -5
  28. package/dist/chunk-FV3Z5MBE.js.map +1 -0
  29. package/dist/chunk-G5E74IJB.js +8 -0
  30. package/dist/chunk-G5E74IJB.js.map +1 -0
  31. package/dist/{chunk-27N2SPTN.js → chunk-IXBKFQH5.js} +12 -11
  32. package/dist/chunk-IXBKFQH5.js.map +1 -0
  33. package/dist/{chunk-SQTCS44W.js → chunk-JFFVBEDI.js} +3 -3
  34. package/dist/{chunk-SQTCS44W.js.map → chunk-JFFVBEDI.js.map} +1 -1
  35. package/dist/chunk-LYLDCIPH.js +365 -0
  36. package/dist/chunk-LYLDCIPH.js.map +1 -0
  37. package/dist/{chunk-HJO6VNQI.js → chunk-MU6MCIAC.js} +3 -3
  38. package/dist/{chunk-HJO6VNQI.js.map → chunk-MU6MCIAC.js.map} +1 -1
  39. package/dist/{chunk-UYWUVEP6.js → chunk-MUUROGIH.js} +2 -2
  40. package/dist/chunk-MUUROGIH.js.map +1 -0
  41. package/dist/{chunk-EHIX7NYZ.js → chunk-MVY5DAMF.js} +4 -4
  42. package/dist/{chunk-EHIX7NYZ.js.map → chunk-MVY5DAMF.js.map} +1 -1
  43. package/dist/{chunk-LP7VQBRG.js → chunk-NPERUUUE.js} +76 -95
  44. package/dist/chunk-NPERUUUE.js.map +1 -0
  45. package/dist/{chunk-QLA76GIT.js → chunk-PBDYW2TU.js} +68 -9
  46. package/dist/chunk-PBDYW2TU.js.map +1 -0
  47. package/dist/{chunk-5VNWZADP.js → chunk-Q2UM7BXU.js} +18 -7
  48. package/dist/chunk-Q2UM7BXU.js.map +1 -0
  49. package/dist/chunk-RMX4EOQK.js +26 -0
  50. package/dist/chunk-RMX4EOQK.js.map +1 -0
  51. package/dist/{chunk-2YOE5PIS.js → chunk-S2EGRPCM.js} +8 -6
  52. package/dist/chunk-S2EGRPCM.js.map +1 -0
  53. package/dist/{chunk-ON24RKSE.js → chunk-S4O26D7B.js} +7 -14
  54. package/dist/chunk-S4O26D7B.js.map +1 -0
  55. package/dist/{chunk-3XJWC7VW.js → chunk-SK5JGUY7.js} +3 -3
  56. package/dist/{chunk-3XJWC7VW.js.map → chunk-SK5JGUY7.js.map} +1 -1
  57. package/dist/{chunk-5DEQ5I3U.js → chunk-TPGASTFF.js} +8 -10
  58. package/dist/chunk-TPGASTFF.js.map +1 -0
  59. package/dist/{chunk-SC3FAFZN.js → chunk-UF4MZSLT.js} +2 -2
  60. package/dist/chunk-UF4MZSLT.js.map +1 -0
  61. package/dist/{chunk-PS23H6KQ.js → chunk-VBUCHVCV.js} +6 -5
  62. package/dist/chunk-VBUCHVCV.js.map +1 -0
  63. package/dist/{chunk-S3FQN4SL.js → chunk-WGGAMW7Y.js} +191 -178
  64. package/dist/chunk-WGGAMW7Y.js.map +1 -0
  65. package/dist/chunk-ZJ5AOYBH.js +8 -0
  66. package/dist/chunk-ZJ5AOYBH.js.map +1 -0
  67. package/dist/{chunk-LEC4U6CX.js → chunk-ZVJZ72HY.js} +3 -3
  68. package/dist/{chunk-LEC4U6CX.js.map → chunk-ZVJZ72HY.js.map} +1 -1
  69. package/dist/circuit-breaker/index.d.ts +1 -0
  70. package/dist/circuit-breaker/index.js +1 -1
  71. package/dist/{core-BoB6t7dB.d.ts → core-42kapW0n.d.ts} +105 -6
  72. package/dist/deadline/index.d.ts +77 -11
  73. package/dist/deadline/index.js +3 -3
  74. package/dist/devtools/index.js +8 -28
  75. package/dist/devtools/index.js.map +1 -1
  76. package/dist/do/index.d.ts +483 -339
  77. package/dist/do/index.js +244 -214
  78. package/dist/do/index.js.map +1 -1
  79. package/dist/{durable-effects-CO9Uh971.d.ts → durable-effects-CFRngTNA.d.ts} +3 -3
  80. package/dist/extension/index.d.ts +25 -7
  81. package/dist/extension/index.js +4 -3
  82. package/dist/extension/index.js.map +1 -1
  83. package/dist/extension/react.js +4 -3
  84. package/dist/extension/react.js.map +1 -1
  85. package/dist/extension/subs/index.d.ts +2 -2
  86. package/dist/extension/subs/index.js +7 -10
  87. package/dist/extension/subs/index.js.map +1 -1
  88. package/dist/fan-out/index.d.ts +10 -10
  89. package/dist/fan-out/index.js +3 -3
  90. package/dist/idempotent-intake/index.d.ts +2 -2
  91. package/dist/idempotent-intake/index.js +3 -3
  92. package/dist/index.d.ts +50 -472
  93. package/dist/index.js +2 -2
  94. package/dist/llm-call/index.d.ts +3 -2
  95. package/dist/llm-call/index.js +12 -10
  96. package/dist/machine-B_BF4jij.d.ts +804 -0
  97. package/dist/machine-viz/index.d.ts +1 -1
  98. package/dist/machine-viz/index.js +2 -2
  99. package/dist/mem/index.d.ts +3 -2
  100. package/dist/mem/index.js.map +1 -1
  101. package/dist/monitored-run/index.d.ts +54 -30
  102. package/dist/monitored-run/index.js +7 -7
  103. package/dist/node/index.d.ts +3 -2
  104. package/dist/node/index.js +2 -3
  105. package/dist/node/index.js.map +1 -1
  106. package/dist/paginated-walk/index.d.ts +2 -2
  107. package/dist/paginated-walk/index.js +11 -10
  108. package/dist/parity/index.d.ts +6 -5
  109. package/dist/parity/index.js +5 -4
  110. package/dist/parity/index.js.map +1 -1
  111. package/dist/pbt/arbitraries/index.d.ts +1 -1
  112. package/dist/pbt/index.d.ts +1 -1
  113. package/dist/pbt/index.js +3 -3
  114. package/dist/pbt/index.js.map +1 -1
  115. package/dist/pbt/runners/index.d.ts +1 -1
  116. package/dist/pbt/runners/index.js +3 -3
  117. package/dist/poller/index.d.ts +59 -17
  118. package/dist/poller/index.js +56 -20
  119. package/dist/poller/index.js.map +1 -1
  120. package/dist/prediction/index.d.ts +1 -1
  121. package/dist/prediction/index.js +2 -2
  122. package/dist/pure/index.d.ts +1 -1
  123. package/dist/pure/index.js +2 -2
  124. package/dist/rate-limit/index.d.ts +2 -2
  125. package/dist/rate-limit/index.js +1 -1
  126. package/dist/react/index.d.ts +3 -2
  127. package/dist/react/index.js +2 -2
  128. package/dist/react/index.js.map +1 -1
  129. package/dist/reconciler/index.d.ts +2 -2
  130. package/dist/reconciler/index.js +13 -15
  131. package/dist/reconciler/index.js.map +1 -1
  132. package/dist/recorder/index.d.ts +20 -20
  133. package/dist/recorder/index.js +1 -1
  134. package/dist/resilient-call/index.d.ts +31 -6
  135. package/dist/resilient-call/index.js +10 -9
  136. package/dist/retry-backoff/index.d.ts +191 -14
  137. package/dist/retry-backoff/index.js +1 -1
  138. package/dist/retry-to-success/index.js +1 -1
  139. package/dist/runtime-types-gsog27b6.d.ts +337 -0
  140. package/dist/saga/index.d.ts +3 -2
  141. package/dist/saga/index.js +2 -2
  142. package/dist/saga/index.js.map +1 -1
  143. package/dist/snapshot/index.d.ts +1 -1
  144. package/dist/snapshot/index.js +3 -3
  145. package/dist/subs/index.d.ts +372 -4
  146. package/dist/subs/index.js +4 -1
  147. package/dist/testing/index.d.ts +2 -2
  148. package/dist/testing/index.js +2 -2
  149. package/dist/throttled-input/index.d.ts +2 -2
  150. package/dist/throttled-input/index.js +14 -13
  151. package/dist/throttled-input/index.js.map +1 -1
  152. package/dist/token-refresh/index.d.ts +1 -1
  153. package/dist/token-refresh/index.js +3 -3
  154. package/dist/trace-replay/index.d.ts +12 -7
  155. package/dist/trace-replay/index.js +4 -3
  156. package/dist/{types-B-8bcAp8.d.ts → types-KbL3W1mj.d.ts} +1 -1
  157. package/dist/with-deadline/index.d.ts +1 -1
  158. package/dist/with-deadline/index.js +2 -2
  159. package/dist/with-resilience/index.d.ts +21 -2
  160. package/dist/with-resilience/index.js +12 -23
  161. package/dist/with-resilience/index.js.map +1 -1
  162. package/dist/with-telemetry/index.d.ts +1 -1
  163. package/dist/with-telemetry/index.js +2 -2
  164. package/dist/work-queue/adapter.d.ts +2 -2
  165. package/dist/work-queue/adapter.js +2 -2
  166. package/dist/work-queue/index.d.ts +3 -2
  167. package/dist/work-queue/index.js +1 -1
  168. package/dist/work-queue/index.js.map +1 -1
  169. package/dist/work-queue/ops.d.ts +2 -2
  170. package/dist/work-queue/ops.js +1 -1
  171. package/dist/workflow/index.d.ts +51 -19
  172. package/dist/workflow/index.js +71 -52
  173. package/dist/workflow/index.js.map +1 -1
  174. package/package.json +4 -19
  175. package/dist/chunk-27N2SPTN.js.map +0 -1
  176. package/dist/chunk-2YOE5PIS.js.map +0 -1
  177. package/dist/chunk-3545BOYL.js.map +0 -1
  178. package/dist/chunk-5DEQ5I3U.js.map +0 -1
  179. package/dist/chunk-5VNWZADP.js.map +0 -1
  180. package/dist/chunk-6RGBKODV.js +0 -268
  181. package/dist/chunk-6RGBKODV.js.map +0 -1
  182. package/dist/chunk-7W4LMPUW.js.map +0 -1
  183. package/dist/chunk-DILMKOZ7.js +0 -91
  184. package/dist/chunk-DILMKOZ7.js.map +0 -1
  185. package/dist/chunk-K7Q23EQ4.js +0 -20
  186. package/dist/chunk-K7Q23EQ4.js.map +0 -1
  187. package/dist/chunk-LP7VQBRG.js.map +0 -1
  188. package/dist/chunk-MMH7CW5K.js.map +0 -1
  189. package/dist/chunk-NSDFA6M6.js +0 -198
  190. package/dist/chunk-NSDFA6M6.js.map +0 -1
  191. package/dist/chunk-ON24RKSE.js.map +0 -1
  192. package/dist/chunk-PS23H6KQ.js.map +0 -1
  193. package/dist/chunk-QLA76GIT.js.map +0 -1
  194. package/dist/chunk-S3FQN4SL.js.map +0 -1
  195. package/dist/chunk-SC3FAFZN.js.map +0 -1
  196. package/dist/chunk-TGG26XMK.js.map +0 -1
  197. package/dist/chunk-UV6UWGEO.js.map +0 -1
  198. package/dist/chunk-UYWUVEP6.js.map +0 -1
  199. package/dist/chunk-VLGARN6H.js +0 -202
  200. package/dist/chunk-VLGARN6H.js.map +0 -1
  201. package/dist/raft/demo.d.ts +0 -105
  202. package/dist/raft/demo.js +0 -172
  203. package/dist/raft/demo.js.map +0 -1
  204. package/dist/raft/index.d.ts +0 -548
  205. package/dist/raft/index.js +0 -7
  206. package/dist/raft/index.js.map +0 -1
  207. package/dist/raft/sim.d.ts +0 -222
  208. package/dist/raft/sim.js +0 -8
  209. package/dist/raft/sim.js.map +0 -1
  210. package/dist/raft/timeline.d.ts +0 -46
  211. package/dist/raft/timeline.js +0 -62
  212. package/dist/raft/timeline.js.map +0 -1
@@ -1,21 +1,23 @@
1
- import { FanOutState } from '../fan-out/index.js';
2
- import { C as Cmd, I as Interpret, M as Machine } from '../core-BoB6t7dB.js';
3
- import { LlmCall, LlmOk, LlmSucceedMsg, LlmFailMsg, LlmErr, LlmTimerMsg, Schema, MessageLoader, ModelFactory, LlmRunCmd, LlmCallPorts } from '../llm-call/index.js';
4
- import { MonitoredRunState, RunFailure, MonitoredRunCmd } from '../monitored-run/index.js';
5
- import { M as MsgType } from '../protocol-B5YmJr0d.js';
6
- import { RetryPolicy } from '../retry-backoff/index.js';
7
- import { ResilientState } from '../resilient-call/index.js';
8
- import { DeadlineSub } from '../deadline/index.js';
9
- export { deadlineSub, subscribeDeadline } from '../deadline/index.js';
10
- import '../work-queue/index.js';
11
- import '../index.js';
12
- import '../snapshot/index.js';
1
+ import { C as Cmd } from '../core-42kapW0n.js';
2
+ export { LlmCall, LlmErr, LlmFailMsg, LlmOk, LlmRunCmd, LlmSucceedMsg, MessageLoader, ModelFactory, Schema } from '../llm-call/index.js';
3
+ import { A as AgentTurn, a as AgentConfigCore, C as CompactionPolicy, b as AgentKnob } from '../machine-B_BF4jij.js';
4
+ export { v as AgentBootMsg, o as AgentCmd, l as AgentCompactErrMsg, k as AgentCompactOkMsg, j as AgentCompactRunCmd, h as AgentCompactionConfig, L as AgentConfig, u as AgentDetachedHandlers, y as AgentEvent, M as AgentFailure, r as AgentLlmErrMsg, q as AgentLlmOkMsg, n as AgentLlmRunCmd, x as AgentMachineMsg, t as AgentPorts, K as AgentSnapshotConfig, N as AgentState, P as AgentStatus, O as AgentTerminalFailure, s as AgentTimerMsg, p as AgentToMachine, I as Awaiting, d as COMPACTION_PURPOSE, m as CompactInterpret, e as CompactionOutputs, c as CompactionPurpose, g as CompactionSummary, J as Conversation, S as SnapshotInterpret, T as ToolCall, G as ToolOutcome, H as ToolRecord, w as agentBootMsg, z as agentEvents, F as agentTurnSchema, f as compactionSummarySchema, E as isAgentTurn, i as isCompactionSummary, D as liftAgent, B as mergeInterpret, Q as status } from '../machine-B_BF4jij.js';
5
+ export { MonitoredRunCmd, RunFailure } from '../monitored-run/index.js';
6
+ export { DeadlineSub, deadlineSub, subscribeDeadline } from '../deadline/index.js';
7
+ import '../resilient-call/index.js';
13
8
  import '../cache/index.js';
14
- import '../types-B-8bcAp8.js';
9
+ import '../types-KbL3W1mj.js';
15
10
  import '../circuit-breaker/index.js';
11
+ import '../protocol-B5YmJr0d.js';
16
12
  import '../rate-limit/index.js';
13
+ import '../retry-backoff/index.js';
14
+ import '../fan-out/index.js';
15
+ import '../work-queue/index.js';
16
+ import '../runtime-types-gsog27b6.js';
17
+ import '../snapshot/index.js';
17
18
 
18
19
  /**
20
+ * @packageDocumentation
19
21
  * @demlik/tea/agent — THE headline Level-3 machine: a durable, crash-recoverable
20
22
  * AI agent that runs an ordered stage pipeline, and inside the agentic stage
21
23
  * drives the classic loop `llm → tools → fold → llm` until the model stops
@@ -110,630 +112,6 @@ import '../rate-limit/index.js';
110
112
  * const runtime = run(machine, { ctx, store });
111
113
  */
112
114
 
113
- /**
114
- * One tool the model asked to call this turn — the seed's `ToolCall`, stripped
115
- * of the audit-specific args typing. Plain data so it round-trips through the
116
- * durable fan-out ledger: a stable `callId` (the fan-out identity), the tool
117
- * `name`, and the opaque `args` the consumer's own interpret reads.
118
- */
119
- interface ToolCall {
120
- /** Stable id the model minted; the fan-out item identity (`idOf`). */
121
- readonly callId: string;
122
- /** The tool to invoke. The consumer's `toolOf` maps it to an effect Cmd. */
123
- readonly name: string;
124
- /** Args the model emitted, opaque to the agent. */
125
- readonly args: Readonly<Record<string, unknown>>;
126
- }
127
- /**
128
- * One model turn — the seed's `AiTurn`, generalized: the narration `content`
129
- * the model produced and the `toolCalls` it asked us to run. An empty
130
- * `toolCalls` means the model is done with this stage (advance the pipeline).
131
- * This is the parsed output of a brain call; the consumer's schema produces it.
132
- */
133
- interface AgentTurn {
134
- /** Free-text narration the model produced this turn (folded into the conversation). */
135
- readonly content: string;
136
- /** The tools the model asked us to run; empty = stage done. */
137
- readonly toolCalls: readonly ToolCall[];
138
- }
139
- /**
140
- * Narrow an unknown to an `AgentTurn` — the runtime witness for tea's own
141
- * structured-output type. A consumer's brain schema parses the model's output
142
- * into an `AgentTurn` (the agentic purpose's output); rather than every consumer
143
- * hand-rolling this guard + a `Schema<AgentTurn>` for a type the agent OWNS, the
144
- * agent exports both. Checks the two load-bearing fields: `content` is a string,
145
- * `toolCalls` is an array. PURE — allocates no Error.
146
- */
147
- declare function isAgentTurn(value: unknown): value is AgentTurn;
148
- /**
149
- * The `Schema<AgentTurn>` for tea's own turn type — the parse target a brain
150
- * call binds when the agentic purpose's output is a bare `AgentTurn` (the common
151
- * case). Throws on a non-`AgentTurn` (the zod-style `parse` contract the
152
- * llm-call handler relies on). Deletes the consumer's hand-rolled
153
- * `auditSchema` / `isAgentTurn` pair.
154
- *
155
- * A consumer whose turn type EXTENDS `AgentTurn` with extra fields still writes
156
- * its own schema (it must validate the extra fields); this is for the plain case.
157
- */
158
- declare const agentTurnSchema: Schema<AgentTurn>;
159
- /**
160
- * One settled tool outcome the consumer routes back into the loop — the seed's
161
- * `ToolOutcome`. `ok` carries the result the consumer's interpret produced;
162
- * `error` carries a reason the model sees (so it recovers rather than stalls —
163
- * "errors are data").
164
- */
165
- type ToolOutcome<R> = {
166
- readonly kind: "ok";
167
- readonly result: R;
168
- } | {
169
- readonly kind: "error";
170
- readonly reason: string;
171
- };
172
- /**
173
- * A folded tool record kept on the conversation once a tool settles — the
174
- * call + its outcome, in settle order. The consumer's message loader reads
175
- * these (plus `turns`) to assemble the next brain call's prompt.
176
- *
177
- * `turn` is the `turnCount` at the time the record was folded — the association
178
- * compaction needs to drop the RIGHT records (#85 / design A1). When compaction
179
- * folds `turns[0..N]` into a summary, it must also drop every tool record that
180
- * belonged to those turns; without a turn stamp on the record there is no honest
181
- * way to know which. It is the round-trip index, not a wall clock — small and
182
- * JSON-stable, preserving the durability invariant.
183
- */
184
- interface ToolRecord<R> {
185
- readonly call: ToolCall;
186
- readonly outcome: ToolOutcome<R>;
187
- /** The `turnCount` at fold time — which round-trip this record belongs to (#85, A1). */
188
- readonly turn: number;
189
- }
190
- /**
191
- * Whether the agentic stage is waiting on the model (`llm`), on tools
192
- * (`tools`), or on a compaction round-trip (`compacting`, #85). The in-flight
193
- * fan-out batch exists ONLY in the `tools` variant — "awaiting llm with tools
194
- * pending" is structurally impossible (the seed's canon §2.6 / Rule 1
195
- * impossible-states pin). Discriminated on `kind`.
196
- *
197
- * `compacting` is the honest state for the dedicated compaction round-trip
198
- * (design B1): the transcript grew, the policy asked to fold `folding` of the
199
- * OLDEST turns, and the summarize call is in flight INSTEAD of the next brain
200
- * call. `folding` is the count `planCompaction` returned — the fold-back
201
- * (`compact_ok`) drops exactly that many head turns + their tool records.
202
- */
203
- type Awaiting = {
204
- readonly kind: "llm";
205
- } | {
206
- readonly kind: "tools";
207
- readonly batchTurn: number;
208
- } | {
209
- readonly kind: "compacting";
210
- readonly folding: number;
211
- };
212
- /**
213
- * The agentic-stage conversation — durable inside the agent slice so an
214
- * eviction mid-loop resumes the exact turn. The model turns + folded tool
215
- * records are the consumer's prompt source (via the llm-call message loader);
216
- * `turnCount` drives the livelock guard; `awaiting` carries the ONE outstanding
217
- * effect for the agentic stage.
218
- *
219
- * Generic over the consumer's tool-result type `R` (what `toolOk` carries).
220
- */
221
- interface Conversation<R> {
222
- /** Model turns this stage has produced, in order. */
223
- readonly turns: readonly AgentTurn[];
224
- /** Settled tool records, in settle order — the model sees these next turn. */
225
- readonly toolRecords: readonly ToolRecord<R>[];
226
- /** Monotonic round-trip count; the livelock guard compares it to `maxTurns`. */
227
- readonly turnCount: number;
228
- /** What the loop is waiting for next. */
229
- readonly awaiting: Awaiting;
230
- }
231
- /**
232
- * The agent knob. Type parameters:
233
- * - `Stage` — the consumer's pipeline stage id (any JSON value).
234
- * - `P` — the brain-call purpose union (`"plan" | "act" | ...`).
235
- * - `O` — the purpose→output map. Every purpose drives the agentic loop,
236
- * so each output is pinned to `AgentTurn` (or a subtype) by the
237
- * `O extends Record<P, AgentTurn>` bound — that is what the loop
238
- * folds. An `Outputs` whose purpose output is NOT an `AgentTurn`
239
- * fails to compile here; the rule lives in the type, not a cast.
240
- * - `R` — the consumer's tool-result type (what `toolOk` carries).
241
- * - `TC` — the consumer's per-tool effect Cmd, the discriminated variant
242
- * `toolOf` produces. Kept PRECISE (a closed Cmd variant, not the
243
- * open `Cmd`) so `AgentCmd<P, TC>` stays a closed discriminated
244
- * union and the wired machine's interpret merge type-checks per
245
- * key — the brain cell maps to `resilient_run`, the tool cell to
246
- * `TC["type"]` — with no laundering cast. Defaults to `Cmd` for
247
- * the consumer that does not care to name its tool Cmd.
248
- * - `Msg` — the model's message shape (threaded through the llm-call loader).
249
- */
250
- /**
251
- * The snapshotting discriminant (#55). Checkpointing is either OFF — in which
252
- * case `snapshotEvery` is structurally absent and the monitored-run slice never
253
- * emits a `snapshot_write` Cmd — or ON, in which case `snapshotEvery` is a
254
- * `number`. A `{ snapshotEvery?: never }` member (rather than a bare optional)
255
- * makes the OFF case load-bearing: it forbids passing `snapshotEvery` at all, so
256
- * `toMachine` can config-derive whether the `snapshot_write` interpret cell is
257
- * REQUIRED (ON) or FORBIDDEN (OFF) instead of defaulting it to a silent no-op.
258
- *
259
- * This is what kills the type lie: with checkpointing off, `snapshot_write` is
260
- * absent from the consumer's interpret contract entirely — never a
261
- * `snapshot_write: async () => undefined` ceremony that masks a real wiring bug.
262
- */
263
- type AgentSnapshotConfig = {
264
- readonly snapshotEvery?: never;
265
- } | {
266
- readonly snapshotEvery: number;
267
- };
268
- /**
269
- * The reserved purpose the compaction round-trip runs under (#85). Compaction
270
- * is a DEDICATED resilient LLM call (design B1), NOT one of the consumer's brain
271
- * purposes `P` — so it carries its own purpose literal, kept in the agent's
272
- * private `$`-namespace (the same reserved-namespace discipline `with-resilience`
273
- * uses) so it never collides with a consumer purpose. A consumer never names it.
274
- */
275
- type CompactionPurpose = "$compact";
276
- /** The reserved compaction purpose's value — the single in-flight summarize call's key. */
277
- declare const COMPACTION_PURPOSE: CompactionPurpose;
278
- /**
279
- * The purpose→output map for the compaction LLM call — the single reserved
280
- * `$compact` purpose mapping to a {@link CompactionSummary}. Mirrors the brain
281
- * call's `O` map, scoped to the one compaction purpose, so the composed
282
- * `createLlmCall` parses the summarize output under the same structured-output
283
- * contract the brain call uses.
284
- */
285
- interface CompactionOutputs extends Record<CompactionPurpose, unknown> {
286
- readonly $compact: CompactionSummary;
287
- }
288
- /**
289
- * Narrow an unknown to a {@link CompactionSummary} — the runtime witness for the
290
- * compaction call's structured output. Checks the one load-bearing field
291
- * (`summary` is a string). PURE — allocates no Error.
292
- */
293
- declare function isCompactionSummary(value: unknown): value is CompactionSummary;
294
- /**
295
- * The `Schema<CompactionSummary>` the compaction call binds — tea's own parse
296
- * target for the summarize round-trip (it OWNS the `$compact` purpose's output).
297
- * Throws on a non-summary (the zod-style `parse` contract the llm-call handler
298
- * relies on), so a malformed summary is a `compact_err` (errors are data), never
299
- * a corrupt fold-back.
300
- */
301
- declare const compactionSummarySchema: Schema<CompactionSummary>;
302
- /**
303
- * The result a compaction round-trip produces — the model's summary of the
304
- * folded-away turns. Tea OWNS this shape (the `$compact` purpose's output): the
305
- * fold-back (`compact_ok`) writes `summary` into a synthetic head `AgentTurn`
306
- * (design A1), so a consumer's `loadMessages` reads it as a normal turn with no
307
- * watermark to learn. Generic-free — the summary is always plain text.
308
- */
309
- interface CompactionSummary {
310
- /** The model's summary of the folded-away (oldest) turns + their tool records. */
311
- readonly summary: string;
312
- }
313
- /**
314
- * The consumer's compaction policy (#85). One PURE trigger; the impure
315
- * summarize round-trip is composed by the agent (a dedicated resilient LLM call
316
- * under the reserved `$compact` purpose, inheriting retry/backoff — design B1),
317
- * so the policy never reaches the model itself.
318
- *
319
- * - `planCompaction` — PURE: given the live conversation ABOUT to fire a brain
320
- * call, return how many of the OLDEST turns to fold into a summary, or `0`
321
- * to skip. No clock, no RNG → replay re-decides identically (design D). A
322
- * char-length / turn-count / real deterministic-tokenizer heuristic all
323
- * qualify. Returning `>= turns.length` is clamped to "fold all but keep the
324
- * loop alive" by the trigger (it never folds the turn currently in flight).
325
- * - `payloadOf` — build the per-call prompt payload the compaction
326
- * `MessageLoader` reads (the turns being folded). Omit → `null` (the loader,
327
- * if any, reads the conversation off the agent's own state). Opaque to the
328
- * agent, exactly like the brain call's `payloadOf`.
329
- */
330
- interface CompactionPolicy<R, Msg = unknown> {
331
- /** PURE trigger: how many OLDEST turns to fold (`0` = skip). No clock/RNG. */
332
- readonly planCompaction: (conversation: Conversation<R>) => number;
333
- /** Build the summarize call's prompt payload from the turns being folded. Omit → `null`. */
334
- readonly payloadOf?: (conversation: Conversation<R>, folding: number) => unknown;
335
- /** DI port — the SDK / message loader for the summarize call. Omit → invoke with `[]`. */
336
- readonly loadMessages?: MessageLoader<CompactionPurpose, Msg>;
337
- }
338
- /**
339
- * The compaction discriminant (#85), shaped exactly like {@link
340
- * AgentSnapshotConfig}. Compaction is either OFF — `compaction` is structurally
341
- * absent and the agent never emits a `compact_run` Cmd — or ON, in which case
342
- * `compaction` is a {@link CompactionPolicy}. A `{ compaction?: never }` member
343
- * (rather than a bare optional) makes the OFF case load-bearing: it forbids
344
- * passing `compaction` at all, so `toMachine` config-derives whether the
345
- * `compact_run` interpret cell is REQUIRED (ON) or FORBIDDEN (OFF) — never a
346
- * silent no-op cell, the #55 type-lie-killer reused.
347
- */
348
- type AgentCompactionConfig<R, Msg> = {
349
- readonly compaction?: never;
350
- } | {
351
- readonly compaction: CompactionPolicy<R, Msg>;
352
- };
353
- /**
354
- * The core (non-snapshot, non-compaction) agent knob. The full `AgentConfig`
355
- * intersects this with the `AgentSnapshotConfig` + `AgentCompactionConfig`
356
- * discriminants — see those types for why the cadence / policy are discriminated
357
- * unions rather than bare optionals.
358
- */
359
- interface AgentConfigCore<Stage, P extends string, O extends Record<P, AgentTurn>, R, TC extends Cmd = Cmd, Msg = unknown> {
360
- /** The ordered stages. Omit / empty → a single-shot run (one agentic stage). */
361
- readonly stages?: readonly Stage[];
362
- /** No-progress watchdog budget, in ms. Omit → no watchdog. */
363
- readonly deadlineMs?: number;
364
- /** DI port — the model factory `(modelId) => Llm`. */
365
- readonly model: ModelFactory<Msg>;
366
- /** One structured-output schema per purpose; the parse target per brain call. */
367
- readonly schemas: {
368
- readonly [K in P]: Schema<O[K]>;
369
- };
370
- /** Backoff policy for brain calls, composed into `../llm-call`. Omit → no backoff. */
371
- readonly retry?: RetryPolicy;
372
- /** DI port — the SDK / message loader. Omit → brain calls invoke with `[]`. */
373
- readonly loadMessages?: MessageLoader<P, Msg>;
374
- /** Map one tool call to the effect Cmd the consumer's interpret performs. */
375
- readonly toolOf: (call: ToolCall) => TC;
376
- /** Max tools in flight at once. Omit / `1` → serial dispatch (the seed's behavior). */
377
- readonly toolConcurrency?: number;
378
- /**
379
- * Which brain-call purpose a given stage runs. The agent fires
380
- * `call_llm{ turnOf(stage) }` to drive the agentic stage's loop. The purpose's
381
- * schema output is an `AgentTurn` — enforced by the `O extends Record<P,
382
- * AgentTurn>` bound, not left to a doc-comment.
383
- */
384
- readonly turnOf: (stage: Stage | undefined) => P;
385
- /** Build the per-purpose brain-call payload from the conversation. Omit → `null`. */
386
- readonly payloadOf?: (stage: Stage | undefined, conversation: Conversation<R>) => unknown;
387
- /** The model id every brain call invokes. Omit → `null` (the host's default). */
388
- readonly modelId?: string | null;
389
- /**
390
- * Livelock guard: bound on model round-trips within one run. On
391
- * `turnCount >= maxTurns` the run fails `{ reason: "turn_limit" }`. Omit → no
392
- * turn guard (only the deadline watchdog bounds the loop).
393
- */
394
- readonly maxTurns?: number;
395
- /**
396
- * The impurity-injection seam for the inherited brain-call retry jitter — the
397
- * ONE place this otherwise-pure machine reads randomness. Pass a fixed
398
- * `() => 0` to pin backoff (tests, replay, durability proofs). Omit →
399
- * `Math.random`, read only at the resilient-call verb boundary.
400
- */
401
- readonly rng?: () => number;
402
- }
403
- /**
404
- * The agent knob — the core seams intersected with the snapshotting discriminant
405
- * (`AgentSnapshotConfig`). Type parameters are documented on `AgentConfigCore`;
406
- * the only addition here is that `snapshotEvery` is the discriminant that drives
407
- * whether `toMachine` requires (or forbids) the `snapshot_write` interpret cell.
408
- */
409
- type AgentConfig<Stage, P extends string, O extends Record<P, AgentTurn>, R, TC extends Cmd = Cmd, Msg = unknown> = AgentConfigCore<Stage, P, O, R, TC, Msg> & AgentSnapshotConfig & AgentCompactionConfig<R, Msg>;
410
- /**
411
- * Why a run terminated as `failed`, beyond monitored-run's own reasons. The
412
- * `turn_limit` reason is the agent's livelock guard; deadline / stage failures
413
- * surface through the monitored-run slice's own `failure`.
414
- */
415
- type AgentFailure = {
416
- readonly reason: "turn_limit";
417
- readonly at: number;
418
- } | {
419
- readonly reason: "llm";
420
- readonly error: unknown;
421
- readonly at: number;
422
- };
423
- /**
424
- * The agent slice — every composed brick's slice plus the loop's conversation
425
- * and the agent-specific failure annotation.
426
- *
427
- * - `run` — the `../monitored-run` slice (pipeline position +
428
- * lifecycle + watchdog). The OUTER lifecycle truth.
429
- * - `resilience` — the `../llm-call` (= resilient-call) slice (brain-call
430
- * retry / backoff). Per-purpose retry lives here.
431
- * - `tools` — the `../fan-out` ledger for the current turn's tools.
432
- * - `conversation` — the agentic-stage loop state. `null` until the loop is
433
- * entered (the consumer seeds it at the agentic stage).
434
- * - `failure` — the agent-specific terminal annotation (turn-limit /
435
- * llm), null otherwise. Distinct from `run.failure`.
436
- */
437
- interface AgentState<Stage, P extends string, O extends Record<P, unknown>, R> {
438
- readonly run: MonitoredRunState<Stage>;
439
- readonly resilience: ResilientState<LlmCall<P>, LlmOk<P, O>>;
440
- readonly tools: FanOutState<ToolCall, ToolOutcome<R>>;
441
- readonly conversation: Conversation<R> | null;
442
- /**
443
- * The compaction round-trip's resilient slice (#85, design B1) — a DEDICATED
444
- * resilient-call slice for the reserved `$compact` purpose, separate from the
445
- * brain `resilience` slice so a compaction retry/backoff never disturbs the
446
- * brain call's breaker or retry counter. Always present (empty `calls` when no
447
- * compaction is in flight, or when no policy is configured) so the slice stays
448
- * a flat plain-data record — durable + replayable like every composed brick.
449
- */
450
- readonly compaction: ResilientState<LlmCall<CompactionPurpose>, LlmOk<CompactionPurpose, CompactionOutputs>>;
451
- readonly failure: AgentFailure | null;
452
- /**
453
- * The run's terminal output — the FIRST-CLASS result (issue #46). `null`
454
- * until the pipeline finishes; set to the last model turn (the empty-tool
455
- * turn that retired the final stage) the instant `run.phase` becomes `"done"`.
456
- *
457
- * This survives the `conversation` clear on stage retire: clearing the
458
- * conversation is correct durability hygiene (a finished stage's transcript
459
- * is not live state), but the run's PRODUCT is, so it lives here on the
460
- * durable slice rather than being scraped off the `observe` firehose by
461
- * matching the private `resilient_ok` Msg and racing the clear (the old
462
- * `captureLastTurn` dance this field deletes). A consumer reads
463
- * `runtime.result()?.output` / `(await runtime.done()).output`.
464
- *
465
- * Typed `AgentTurn | null` (not `O[P]`): the run's output is always a model
466
- * turn — the `O extends Record<P, AgentTurn>` knob bound pins every purpose's
467
- * output to an `AgentTurn`, and the terminating turn is the one with no tool
468
- * calls. The wider `Record<P, unknown>` bound on `AgentState` itself does not
469
- * constrain `O[P]`, so naming the concrete `AgentTurn` keeps this field's type
470
- * total without a purpose-indexing narrow.
471
- */
472
- readonly output: AgentTurn | null;
473
- }
474
- /**
475
- * The unified terminal failure (issue #49). The agent terminates `failed`
476
- * through TWO independent slice channels:
477
- *
478
- * - `state.failure` (`AgentFailure`) — the AGENT'S OWN annotation
479
- * (`turn_limit` livelock guard / `llm` exhausted-retry). Set WITHOUT moving
480
- * `run.phase` (it stays `running`); `isSettled` treats a non-null `failure`
481
- * as terminal regardless of `run.phase`.
482
- * - `state.run.failure` (`RunFailure`) — the monitored-run channel
483
- * (`deadline` watchdog / `stage` failure), present iff `run.phase` is
484
- * `"failed"`.
485
- *
486
- * Callers used to union these by hand at every status question. `status`
487
- * collapses them into ONE `failure`, so a consumer reads `status(s).failure`
488
- * without knowing which channel produced it.
489
- */
490
- type AgentTerminalFailure<Stage> = AgentFailure | RunFailure<Stage>;
491
- /**
492
- * The agent's lifecycle status — THE single typed channel for "what is this run
493
- * doing?" (issue #49). A discriminated union on `kind` so any change to the
494
- * private slice shape (`Awaiting`, the failure channels, `run.phase`) forces a
495
- * compile error at the call sites that switch on it, instead of silently
496
- * breaking a hand-rolled re-derivation. Make-invalid-states-unrepresentable:
497
- *
498
- * - `running` — live, NOT awaiting tools (a brain call is in flight, or the
499
- * run is between stages). Not resumable on cold wake by
500
- * itself — the in-flight brain call re-fires from `boot`.
501
- * - `suspended` — the RESUMABLE case: running + a live conversation +
502
- * `awaiting.kind === "tools"`. `pending` is the outstanding
503
- * tool calls (`conversation.awaiting` … the in-flight batch),
504
- * read off `tools.running`. This is exactly the shape
505
- * `agentIsResumable` re-derived by hand.
506
- * - `done` — the pipeline finished; `output` is the terminal model turn
507
- * stamped on `state.output` (issue #46), `null` if the run
508
- * produced no turn.
509
- * - `failed` — terminal failure; `failure` is the UNIFIED channel
510
- * (`AgentTerminalFailure`), absorbing the `state.failure` vs
511
- * `state.run.failure` dual channel so callers stop unioning.
512
- */
513
- type AgentStatus<Stage> = {
514
- readonly kind: "running";
515
- } | {
516
- readonly kind: "suspended";
517
- readonly pending: readonly ToolCall[];
518
- } | {
519
- readonly kind: "done";
520
- readonly output: AgentTurn | null;
521
- } | {
522
- readonly kind: "failed";
523
- readonly failure: AgentTerminalFailure<Stage>;
524
- };
525
- /**
526
- * Derive the agent's lifecycle `status` from its durable slice — the pure
527
- * status function that REPLACES every caller's hand re-derivation of the private
528
- * shape (issue #49). PURE — reads no clock / RNG, allocates one small record.
529
- *
530
- * Ordering is terminal-first so a settled run never reports `running`:
531
- *
532
- * 1. `state.failure` (the agent's own annotation, set WITHOUT moving
533
- * `run.phase`) → `failed`. Checked first because `turn_limit` / `llm`
534
- * leave `run.phase === "running"`; reading `run.phase` first would
535
- * misreport such a run as `running`. This is the canonical failure source
536
- * when present.
537
- * 2. `run.phase === "failed"` → `failed`, carrying `run.failure` (deadline /
538
- * stage). The fallback channel.
539
- * 3. `run.phase === "done"` → `done` with `state.output` (#46).
540
- * 4. running + conversation + `awaiting.kind === "tools"` → `suspended` with
541
- * the outstanding tool calls (`tools.running`). THE resumability condition.
542
- * 5. otherwise → `running`.
543
- */
544
- declare function status<Stage, P extends string, O extends Record<P, unknown>, R>(s: AgentState<Stage, P, O, R>): AgentStatus<Stage>;
545
- /** The brain-call effect Cmd, inherited from `../llm-call`. */
546
- type AgentLlmRunCmd<P extends string> = LlmRunCmd<P>;
547
- /**
548
- * The "summarize the oldest N turns" effect Cmd — the compaction round-trip's
549
- * carrier (#85). It mirrors the brain `resilient_run` Cmd's shape (a `key` + the
550
- * plain `LlmCall<CompactionPurpose>` input, no closures) but under the dedicated
551
- * `compact_run` discriminant so it routes to the compaction interpret cell, not
552
- * the brain one. The cell composes the resilient brick (retry/backoff) and
553
- * returns the re-keyed `compact_ok` / `compact_err` settle for re-entry.
554
- */
555
- type AgentCompactRunCmd = Cmd<typeof MsgType.CompactRun> & {
556
- readonly key: CompactionPurpose;
557
- readonly input: LlmCall<CompactionPurpose>;
558
- };
559
- /** The compaction round-trip success settle Msg — carries the parsed {@link CompactionSummary}. */
560
- type AgentCompactOkMsg = {
561
- readonly type: typeof MsgType.CompactOk;
562
- readonly key: CompactionPurpose;
563
- readonly result: LlmOk<CompactionPurpose, CompactionOutputs>;
564
- readonly at: number;
565
- };
566
- /** The compaction round-trip failure settle Msg — carries the typed {@link LlmErr}. */
567
- type AgentCompactErrMsg = {
568
- readonly type: typeof MsgType.CompactErr;
569
- readonly key: CompactionPurpose;
570
- readonly error: LlmErr<CompactionPurpose>;
571
- readonly at: number;
572
- };
573
- /**
574
- * The Cmd union the agent emits, as a CLOSED discriminated union (precise `TC`,
575
- * not the open `Cmd`) so `Interpret<M, AgentCmd<P, TC>, Ctx>` maps each key
576
- * precisely and `toMachine` merges the interpret halves with no laundering cast:
577
- *
578
- * - `AgentLlmRunCmd<P>` — the brain-call run Cmd (`resilient_run`), folded
579
- * by the wired `brainHandlers` cell.
580
- * - `MonitoredRunCmd<unknown>` — the durable checkpoint write the monitored-run
581
- * slice emits, present in the union ONLY when
582
- * checkpointing is on (`Snap = true`). With
583
- * checkpointing off the monitored-run slice never
584
- * emits a `snapshot_write` Cmd, so it is config-derived
585
- * OUT of the emitted set — the consumer is never asked
586
- * to interpret a Cmd that can never fire (#55).
587
- * - `TC` — the consumer's per-tool effect, mapped to the
588
- * consumer's own tool interpret cell.
589
- *
590
- * `Snap` defaults to `true` so the verb-internal usage (which forwards whatever
591
- * monitored-run emits) and the published type stay a safe superset; the wired
592
- * machine `toMachine` returns is parametrized on the overload-fixed `Snap` so its
593
- * Cmd set is exact (`MonitoredRunCmd` present only when checkpointing is on).
594
- */
595
- type AgentCmd<P extends string, TC extends Cmd = Cmd, Snap extends boolean = true, Compact extends boolean = true> = AgentLlmRunCmd<P> | (Snap extends true ? MonitoredRunCmd<unknown> : never) | (Compact extends true ? AgentCompactRunCmd : never) | TC;
596
- /**
597
- * The CONFIG-DERIVED snapshot obligation on `toMachine`'s `toolInterpret` (#55).
598
- * Resolves on the `Snap` discriminant the snapshotting overload of `createAgent`
599
- * fixes (`true` checkpointing-on / `false` off):
600
- *
601
- * - checkpointing ON → a REQUIRED `snapshot_write` cell
602
- * (`Interpret<M, MonitoredRunCmd<unknown>, Ctx>`). A real checkpoint write
603
- * MUST be wired — the agent never defaults it to a no-op.
604
- * - checkpointing OFF → `{ snapshot_write?: never }`. The cell is FORBIDDEN:
605
- * the Cmd is config-derived out of the emitted set, so wiring it would be
606
- * dead code. The consumer cannot even mention `snapshot_write`.
607
- *
608
- * This is the type that kills the `snapshot_write: async () => undefined`
609
- * ceremony: the obligation is present in the contract EXACTLY when the Cmd can
610
- * fire, never as a silent gap the agent backfills.
611
- */
612
- type SnapshotInterpret<M extends {
613
- type: string;
614
- }, Snap extends boolean, Ctx> = Snap extends true ? Interpret<M, MonitoredRunCmd<unknown>, Ctx> : {
615
- readonly snapshot_write?: never;
616
- };
617
- /**
618
- * The CONFIG-DERIVED compaction obligation on `toMachine`'s `toolInterpret`
619
- * (#85), the exact twin of {@link SnapshotInterpret}. Resolves on the `Compact`
620
- * discriminant the compaction overload of `createAgent` fixes:
621
- *
622
- * - compaction ON → a REQUIRED `compact_run` cell
623
- * (`Interpret<M, AgentCompactRunCmd, Ctx>`). The summarize round-trip MUST be
624
- * wired — the agent never defaults it to a no-op.
625
- * - compaction OFF → `{ compact_run?: never }`. The cell is FORBIDDEN: with no
626
- * policy the agent never emits a `compact_run` Cmd, so wiring it would be
627
- * dead code. The consumer cannot even mention `compact_run`.
628
- *
629
- * Same type-lie-killer as the snapshot derivation: the obligation is present
630
- * EXACTLY when the Cmd can fire, never as a silent gap the agent backfills.
631
- */
632
- type CompactInterpret<M extends {
633
- type: string;
634
- }, Compact extends boolean, Ctx> = Compact extends true ? Interpret<M, AgentCompactRunCmd, Ctx> : {
635
- readonly compact_run?: never;
636
- };
637
- /**
638
- * The `toMachine` signature, parametrized on the `Snap` + `Compact` discriminants
639
- * so the snapshotting / compaction overloads of `createAgent` hand back the right
640
- * obligations. The `toolInterpret` requires (ON) or forbids (OFF) the
641
- * `snapshot_write` cell via {@link SnapshotInterpret} and the `compact_run` cell
642
- * via {@link CompactInterpret}, and the machine's Cmd type is the config-derived
643
- * `AgentCmd<P, TC, Snap, Compact>`.
644
- */
645
- type AgentToMachine<Stage, P extends string, O extends Record<P, AgentTurn>, R, TC extends Cmd, Snap extends boolean, Compact extends boolean> = <Ctx = object>(opts?: {
646
- readonly toolInterpret?: Interpret<AgentMachineMsg<P, O, R>, TC, Ctx> & SnapshotInterpret<AgentMachineMsg<P, O, R>, Snap, Ctx> & CompactInterpret<AgentMachineMsg<P, O, R>, Compact, Ctx>;
647
- }) => Machine<AgentState<Stage, P, O, R>, AgentMachineMsg<P, O, R>, AgentCmd<P, TC, Snap, Compact>, DeadlineSub, Ctx>;
648
- /**
649
- * The agent knob `createAgent` returns — the uniform verb contract every tea
650
- * composition exposes, plus the wired `toMachine` and the `unsafeDetachedHandlers`
651
- * escape hatch. `Snap` flows ONLY into `toMachine`'s `toolInterpret` obligation
652
- * (the snapshot derivation, #55); every verb is snapshot-agnostic. The model
653
- * message shape `Msg` does not appear on the knob surface (it is internal to the
654
- * brain call's loader), so it is not a type parameter here — only `createAgent`
655
- * carries it, to thread the config's `loadMessages` / `model` ports.
656
- */
657
- interface AgentKnob<Stage, P extends string, O extends Record<P, AgentTurn>, R, TC extends Cmd, Snap extends boolean, Compact extends boolean> {
658
- readonly init: () => AgentState<Stage, P, O, R>;
659
- readonly start: AgentVerb1<Stage, P, O, R, TC, [runId: string, at: number]>;
660
- readonly turn: AgentVerb1<Stage, P, O, R, TC, [
661
- result: AgentTurn,
662
- at: number
663
- ]>;
664
- readonly toolOk: AgentVerb1<Stage, P, O, R, TC, [
665
- callId: string,
666
- result: R,
667
- at: number
668
- ]>;
669
- readonly toolErr: AgentVerb1<Stage, P, O, R, TC, [
670
- callId: string,
671
- reason: string,
672
- at: number
673
- ]>;
674
- readonly succeed: AgentVerb1<Stage, P, O, R, TC, [
675
- key: string,
676
- msg: AgentLlmOkMsg<P, O>,
677
- at: number
678
- ]>;
679
- readonly fail: AgentVerb1<Stage, P, O, R, TC, [
680
- key: string,
681
- msg: AgentLlmErrMsg<P>,
682
- at: number
683
- ]>;
684
- readonly compactOk: AgentVerb1<Stage, P, O, R, TC, [
685
- key: string,
686
- msg: AgentCompactOkMsg,
687
- at: number
688
- ]>;
689
- readonly compactErr: AgentVerb1<Stage, P, O, R, TC, [
690
- key: string,
691
- msg: AgentCompactErrMsg,
692
- at: number
693
- ]>;
694
- readonly onTimer: AgentVerb1<Stage, P, O, R, TC, [msg: AgentTimerMsg]>;
695
- readonly boot: AgentVerb1<Stage, P, O, R, TC, [at: number]>;
696
- readonly isSettled: (s: AgentState<Stage, P, O, R>) => boolean;
697
- readonly currentStage: (s: AgentState<Stage, P, O, R>) => Stage | undefined;
698
- readonly brainCall: (s: AgentState<Stage, P, O, R>) => LlmCall<P>;
699
- readonly subs: (s: AgentState<Stage, P, O, R>) => readonly DeadlineSub[];
700
- readonly toMachine: AgentToMachine<Stage, P, O, R, TC, Snap, Compact>;
701
- readonly unsafeDetachedHandlers: <M>(ports: AgentPorts<P, O, M>) => AgentDetachedHandlers<P, M>;
702
- }
703
- /** A verb taking the state + `Args`, returning the knob's `[State, Cmd[]]` tuple. */
704
- type AgentVerb1<Stage, P extends string, O extends Record<P, AgentTurn>, R, TC extends Cmd, Args extends readonly unknown[]> = (s: AgentState<Stage, P, O, R>, ...args: Args) => readonly [AgentState<Stage, P, O, R>, readonly AgentCmd<P, TC>[]];
705
- /** The brain-call success / failure settle Msgs, inherited from `../llm-call`. */
706
- type AgentLlmOkMsg<P extends string, O extends Record<P, unknown>> = LlmSucceedMsg<P, O>;
707
- type AgentLlmErrMsg<P extends string> = LlmFailMsg<P>;
708
- /**
709
- * The timer Msg (retry + safety deadline) — `DeadlineExceeded`, the shared
710
- * shape of both bricks' timer Msgs (`LlmTimerMsg` and `MonitoredRunTimerMsg`
711
- * are both `DeadlineExceeded`). One Msg variant covers both timers; `onTimer`
712
- * disambiguates by Sub id. This is also the machine Msg the `subscribeDeadline`
713
- * cell dispatches directly (no wrapping), matching the sibling gold standard.
714
- */
715
- type AgentTimerMsg = LlmTimerMsg;
716
- /** Ports the consumer supplies to the llm-call handler — re-exported shape. */
717
- type AgentPorts<P extends string, O extends Record<P, unknown>, M> = LlmCallPorts<P, O, M>;
718
- /**
719
- * The LEGACY detached brain-call handler dictionary `handlers(ports)` returns —
720
- * the inherited `../llm-call` detached form's exact shape, NOT an `Interpret`.
721
- * The `resilient_run` cell runs the invoke inside `ctx.waitUntil` and dispatches
722
- * the consumer's `onOk` / `onErr` Msg directly (returning `void`), so it is a
723
- * fire-and-forget handler with a structural `{ waitUntil, dispatch }` ctx — it
724
- * does not re-enter the resilient settle Msg and so does not drive the retry
725
- * loop. Naming the type precisely (rather than laundering it through
726
- * `as unknown as Interpret<...>`) keeps `agent.unsafeDetachedHandlers(ports)` honest: the
727
- * consumer that wires the verbs by hand gets the real detached shape, and its
728
- * `resilient_run` is callable with a plain Cmd + a `{ waitUntil, dispatch }` ctx
729
- * with no `as never` at the call site.
730
- */
731
- type AgentDetachedHandlers<P extends string, M> = {
732
- readonly resilient_run: (cmd: AgentLlmRunCmd<P>, ctx: {
733
- waitUntil(p: Promise<unknown>): void;
734
- dispatch(msg: M): unknown;
735
- }) => void;
736
- };
737
115
  /**
738
116
  * Build an agent knob from `config`. The determinism seam — `config.rng`,
739
117
  * injected for the inherited brain-call retry jitter — lives as a named field
@@ -771,137 +149,5 @@ declare function createAgent<Stage, P extends string, O extends Record<P, AgentT
771
149
  readonly snapshotEvery?: never;
772
150
  readonly compaction?: never;
773
151
  }): AgentKnob<Stage, P, O, R, TC, false, false>;
774
- /** The Msg `do/host`'s `autoBoot` fires to re-enter the agent's `boot` verb on rehydrate. */
775
- type AgentBootMsg = {
776
- readonly type: typeof MsgType.AgentBoot;
777
- readonly at: number;
778
- };
779
- /**
780
- * The do↔agent boot port: construct the `agent_boot` Msg `autoBoot` dispatches
781
- * on a resumable rehydrate. The agent owns this constructor so the boot Msg
782
- * shape lives in ONE place — the host fires it through here, never as a raw
783
- * `{ type: "agent_boot" }` literal.
784
- */
785
- declare function agentBootMsg(at: number): AgentBootMsg;
786
- /**
787
- * The agent machine's Msg union — one variant per reducer entry point. A
788
- * consumer using `toMachine` dispatches `agent_start` to begin and `agent_tool_ok`
789
- * / `agent_tool_err` to route settled tools back; the brain-call settle Msgs
790
- * (`resilient_ok` / `resilient_err`) RE-ENTER from the FIXED `brainHandlers`
791
- * (the substrate enqueues an interpret handler's returned Msg as a follow-up),
792
- * driving `succeed` / `fail`. Time enters via `at` on every variant — the
793
- * reducer never reads the clock.
794
- *
795
- * There is deliberately NO `agent_turn` variant here. The wired loop folds a
796
- * model turn INSIDE `succeed` from the re-entered `resilient_ok` — a single
797
- * settle Msg advances both the retry slice and the conversation (the L3 fix).
798
- * Exposing `agent_turn` as a dispatchable Msg re-opened the stuck-`running` bug:
799
- * a hand-fed turn folds the conversation without ever re-entering `resilient_ok`,
800
- * so `succeed` never runs and the resilient slice stays `running` (#54). The
801
- * `turn` verb remains on the knob for the consumer that wires the verbs by hand
802
- * (manual wiring), but it is not part of the one wired machine's Msg surface.
803
- */
804
- type AgentMachineMsg<P extends string, O extends Record<P, unknown>, R> = {
805
- readonly type: typeof MsgType.AgentStart;
806
- readonly runId: string;
807
- readonly at: number;
808
- } | {
809
- readonly type: typeof MsgType.AgentToolOk;
810
- readonly callId: string;
811
- readonly result: R;
812
- readonly at: number;
813
- } | {
814
- readonly type: typeof MsgType.AgentToolErr;
815
- readonly callId: string;
816
- readonly reason: string;
817
- readonly at: number;
818
- } | AgentLlmOkMsg<P, O> | AgentLlmErrMsg<P> | AgentCompactOkMsg | AgentCompactErrMsg | AgentTimerMsg | AgentBootMsg;
819
- /**
820
- * The agent's PUBLIC lifecycle events — the semantic stream a consumer
821
- * subscribes to via `runtime.on(type, …)` (#47). This is the seam that
822
- * DECOUPLES observability/SSE code from the agent's PRIVATE retry/loop Msg
823
- * vocabulary: where the old code switched on `resilient_ok` / `agent_tool_ok`
824
- * (the inherited resilient-call / tool-fan-out plumbing) off the raw `observe`
825
- * firehose, a consumer now folds these named events. The private Msg names live
826
- * ONLY inside `agentEvents` (the projector) — they appear nowhere in this union
827
- * or any exported type, so a UI built on `TurnSettled` does not break the day
828
- * the retry plumbing is renamed.
829
- *
830
- * - `TurnSettled` — a brain turn settled (the model produced an `AgentTurn`).
831
- * Projected off the private `resilient_ok` settle Msg; carries the parsed
832
- * `turn` (the narration + tool calls the model asked for).
833
- * - `ToolSettled` — a tool call settled OK. Projected off the private
834
- * `agent_tool_ok` Msg; carries the `callId` and the tool `result`.
835
- * - `RunDone` — the run finished. Projected off the post-transition State
836
- * reaching `run.phase === "done"`; carries the run's `output` (the terminal
837
- * model turn, or `null`) — the same first-class result `Runtime.result()`
838
- * reads (#46), surfaced as an event for the streaming consumer.
839
- */
840
- type AgentEvent<R> = {
841
- readonly type: "TurnSettled";
842
- readonly turn: AgentTurn;
843
- } | {
844
- readonly type: "ToolSettled";
845
- readonly callId: string;
846
- readonly result: R;
847
- } | {
848
- readonly type: "RunDone";
849
- readonly output: AgentTurn | null;
850
- };
851
- /**
852
- * Project one APPLIED agent transition `(msg, state)` to its semantic
853
- * {@link AgentEvent}s (#47) — the `events` projector a consumer passes to
854
- * `run(machine, { events: agentEvents() })` to light up `runtime.on(...)`.
855
- *
856
- * This is the ONE place the agent's PRIVATE Msg names are read: it maps
857
- * `resilient_ok` → `TurnSettled` and `agent_tool_ok` → `ToolSettled`, and reads
858
- * the post-transition `run.phase` for `RunDone`. The mapping is total over the
859
- * Msg union (a `default`-free switch on the discriminant) and returns `[]` for
860
- * the transitions that carry no public event (start / boot / timer / the error
861
- * arms), so a private name never escapes into `AgentEvent`.
862
- *
863
- * A single transition may emit more than one event: the brain turn that retires
864
- * the final stage settles a turn (`TurnSettled`) AND finishes the run
865
- * (`RunDone`) — both are projected from that one `resilient_ok` transition.
866
- * `RunDone` is gated on `run.phase === "done"`, which the wired loop reaches
867
- * exactly once (the agent is terminal there and dispatches no further
868
- * transition), so the event fires once per run.
869
- *
870
- * PURE — reads only the passed `(msg, state)`; no clock, no RNG, no throw.
871
- *
872
- * @typeParam P Brain-call purposes.
873
- * @typeParam O Per-purpose outputs (bound to `AgentTurn`, the agentic shape).
874
- * @typeParam R Tool result type.
875
- * @typeParam Stage Pipeline stage type.
876
- */
877
- declare function agentEvents<Stage, P extends string, O extends Record<P, AgentTurn>, R>(): (msg: AgentMachineMsg<P, O, R>, state: AgentState<Stage, P, O, R>) => readonly AgentEvent<R>[];
878
- /**
879
- * Join two `Interpret` dictionaries over DISJOINT Cmd subsets `A` and `B` (over
880
- * the same Msg union `M` and Ctx) into the full `Interpret<M, A | B, Ctx>`. The
881
- * agent uses it to merge the consumer's per-tool / snapshot interpret (`A`) with
882
- * the agent-owned brain-call handler (`B = AgentLlmRunCmd`) into the wired
883
- * machine's single interpret table.
884
- *
885
- * The runtime result is exactly the spread of the two key-disjoint records. The
886
- * single `as` is a SOUND mapped-type identity, not a laundering cast: `Interpret`
887
- * is a homomorphic mapped type keyed by `Cmd["type"]`, so
888
- * `Interpret<M, A, Ctx> & Interpret<M, B, Ctx>` IS `Interpret<M, A | B, Ctx>`
889
- * (`(A | B)["type"] = A["type"] | B["type"]`). TypeScript does not reduce that
890
- * intersection of two GENERIC mapped types on its own, so the equality is
891
- * asserted ONCE here — preserving `M` and `Ctx` exactly — rather than smuggled
892
- * through `as unknown as Interpret<...>` at every wiring site. Pure.
893
- */
894
- declare function mergeInterpret<M extends {
895
- type: string;
896
- }, A extends Cmd, B extends Cmd, Ctx>(a: Interpret<M, A, Ctx> | undefined, b: Interpret<M, B, Ctx>): Interpret<M, A | B, Ctx>;
897
- /**
898
- * Lift a knob result `[slice, cmds]` into a host `[State, cmds]` where the slice
899
- * lives at `state.agent`. Convenience for a host that nests the agent slice
900
- * under a named field; the single-slice host uses the verbs' tuple directly.
901
- * PURE — a thin record rebuild, no clock / RNG.
902
- */
903
- declare function liftAgent<S extends {
904
- agent: AgentState<Stage, P, O, R>;
905
- }, Stage, P extends string, O extends Record<P, unknown>, R, C extends Cmd>(state: S, [slice, cmds]: readonly [AgentState<Stage, P, O, R>, readonly C[]]): readonly [S, readonly C[]];
906
152
 
907
- export { type AgentBootMsg, type AgentCmd, type AgentCompactErrMsg, type AgentCompactOkMsg, type AgentCompactRunCmd, type AgentCompactionConfig, type AgentConfig, type AgentConfigCore, type AgentDetachedHandlers, type AgentEvent, type AgentFailure, type AgentKnob, type AgentLlmErrMsg, type AgentLlmOkMsg, type AgentLlmRunCmd, type AgentMachineMsg, type AgentPorts, type AgentSnapshotConfig, type AgentState, type AgentStatus, type AgentTerminalFailure, type AgentTimerMsg, type AgentToMachine, type AgentTurn, type Awaiting, COMPACTION_PURPOSE, type CompactInterpret, type CompactionOutputs, type CompactionPolicy, type CompactionPurpose, type CompactionSummary, type Conversation, DeadlineSub, LlmCall, LlmErr, LlmFailMsg, LlmOk, LlmRunCmd, LlmSucceedMsg, MessageLoader, ModelFactory, MonitoredRunCmd, RunFailure, Schema, type SnapshotInterpret, type ToolCall, type ToolOutcome, type ToolRecord, agentBootMsg, agentEvents, agentTurnSchema, compactionSummarySchema, createAgent, isAgentTurn, isCompactionSummary, liftAgent, mergeInterpret, status };
153
+ export { AgentConfigCore, AgentKnob, AgentTurn, CompactionPolicy, createAgent };