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