@demlik/tea 0.1.0 → 0.1.2

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 (243) hide show
  1. package/LICENSE +21 -0
  2. package/dist/agent/index.d.ts +907 -0
  3. package/dist/agent/index.js +20 -0
  4. package/dist/agent/index.js.map +1 -0
  5. package/dist/authed-call/index.d.ts +119 -0
  6. package/dist/authed-call/index.js +148 -0
  7. package/dist/authed-call/index.js.map +1 -0
  8. package/dist/await-terminal/index.d.ts +99 -0
  9. package/dist/await-terminal/index.js +75 -0
  10. package/dist/await-terminal/index.js.map +1 -0
  11. package/dist/batch-window/index.d.ts +259 -0
  12. package/dist/batch-window/index.js +43 -0
  13. package/dist/batch-window/index.js.map +1 -0
  14. package/dist/cache/index.d.ts +2 -2
  15. package/dist/cache/index.js +2 -50
  16. package/dist/cache/index.js.map +1 -1
  17. package/dist/chunk-27N2SPTN.js +222 -0
  18. package/dist/chunk-27N2SPTN.js.map +1 -0
  19. package/dist/chunk-2YOE5PIS.js +45 -0
  20. package/dist/chunk-2YOE5PIS.js.map +1 -0
  21. package/dist/chunk-3545BOYL.js +65 -0
  22. package/dist/chunk-3545BOYL.js.map +1 -0
  23. package/dist/chunk-3XJWC7VW.js +61 -0
  24. package/dist/chunk-3XJWC7VW.js.map +1 -0
  25. package/dist/chunk-5DEQ5I3U.js +132 -0
  26. package/dist/chunk-5DEQ5I3U.js.map +1 -0
  27. package/dist/chunk-5VNWZADP.js +49 -0
  28. package/dist/chunk-5VNWZADP.js.map +1 -0
  29. package/dist/chunk-6RGBKODV.js +268 -0
  30. package/dist/chunk-6RGBKODV.js.map +1 -0
  31. package/dist/{chunk-ZRUST6BK.js → chunk-7FYQGDMF.js} +2 -2
  32. package/dist/chunk-7FYQGDMF.js.map +1 -0
  33. package/dist/chunk-7W4LMPUW.js +186 -0
  34. package/dist/chunk-7W4LMPUW.js.map +1 -0
  35. package/dist/chunk-BYQUGDD3.js +16 -0
  36. package/dist/chunk-BYQUGDD3.js.map +1 -0
  37. package/dist/{chunk-PYBQREFU.js → chunk-DILMKOZ7.js} +22 -26
  38. package/dist/chunk-DILMKOZ7.js.map +1 -0
  39. package/dist/chunk-EHIX7NYZ.js +93 -0
  40. package/dist/chunk-EHIX7NYZ.js.map +1 -0
  41. package/dist/chunk-HCEVHFJ7.js +54 -0
  42. package/dist/chunk-HCEVHFJ7.js.map +1 -0
  43. package/dist/chunk-HJO6VNQI.js +15 -0
  44. package/dist/chunk-HJO6VNQI.js.map +1 -0
  45. package/dist/chunk-IN33Q4VJ.js +52 -0
  46. package/dist/chunk-IN33Q4VJ.js.map +1 -0
  47. package/dist/chunk-J6527VRQ.js +56 -0
  48. package/dist/chunk-J6527VRQ.js.map +1 -0
  49. package/dist/chunk-JELSZN25.js +47 -0
  50. package/dist/chunk-JELSZN25.js.map +1 -0
  51. package/dist/chunk-K575PT4S.js +58 -0
  52. package/dist/chunk-K575PT4S.js.map +1 -0
  53. package/dist/chunk-K7Q23EQ4.js +20 -0
  54. package/dist/chunk-K7Q23EQ4.js.map +1 -0
  55. package/dist/chunk-LEC4U6CX.js +91 -0
  56. package/dist/chunk-LEC4U6CX.js.map +1 -0
  57. package/dist/{chunk-PYOCUBQJ.js → chunk-LP7VQBRG.js} +22 -15
  58. package/dist/chunk-LP7VQBRG.js.map +1 -0
  59. package/dist/{chunk-CMG2KMWX.js → chunk-MMH7CW5K.js} +220 -189
  60. package/dist/chunk-MMH7CW5K.js.map +1 -0
  61. package/dist/{chunk-Y5JM3UUH.js → chunk-NSDFA6M6.js} +75 -3
  62. package/dist/chunk-NSDFA6M6.js.map +1 -0
  63. package/dist/chunk-ON24RKSE.js +60 -0
  64. package/dist/chunk-ON24RKSE.js.map +1 -0
  65. package/dist/chunk-PS23H6KQ.js +87 -0
  66. package/dist/chunk-PS23H6KQ.js.map +1 -0
  67. package/dist/chunk-QLA76GIT.js +162 -0
  68. package/dist/chunk-QLA76GIT.js.map +1 -0
  69. package/dist/chunk-S3FQN4SL.js +506 -0
  70. package/dist/chunk-S3FQN4SL.js.map +1 -0
  71. package/dist/chunk-SC3FAFZN.js +53 -0
  72. package/dist/chunk-SC3FAFZN.js.map +1 -0
  73. package/dist/chunk-SINXE47Y.js +55 -0
  74. package/dist/chunk-SINXE47Y.js.map +1 -0
  75. package/dist/chunk-SQTCS44W.js +33 -0
  76. package/dist/chunk-SQTCS44W.js.map +1 -0
  77. package/dist/chunk-TGG26XMK.js +52 -0
  78. package/dist/chunk-TGG26XMK.js.map +1 -0
  79. package/dist/chunk-UV6UWGEO.js +147 -0
  80. package/dist/chunk-UV6UWGEO.js.map +1 -0
  81. package/dist/chunk-UYWUVEP6.js +158 -0
  82. package/dist/chunk-UYWUVEP6.js.map +1 -0
  83. package/dist/chunk-VLGARN6H.js +202 -0
  84. package/dist/chunk-VLGARN6H.js.map +1 -0
  85. package/dist/circuit-breaker/index.js +1 -51
  86. package/dist/circuit-breaker/index.js.map +1 -1
  87. package/dist/core-BoB6t7dB.d.ts +188 -0
  88. package/dist/deadline/index.d.ts +24 -5
  89. package/dist/deadline/index.js +4 -18
  90. package/dist/deadline/index.js.map +1 -1
  91. package/dist/debounce/index.d.ts +6 -0
  92. package/dist/debounce/index.js +1 -54
  93. package/dist/debounce/index.js.map +1 -1
  94. package/dist/devtools/index.d.ts +1 -1
  95. package/dist/devtools/index.js +18 -6
  96. package/dist/devtools/index.js.map +1 -1
  97. package/dist/do/index.d.ts +1723 -92
  98. package/dist/do/index.js +673 -31
  99. package/dist/do/index.js.map +1 -1
  100. package/dist/durable-effects-CO9Uh971.d.ts +180 -0
  101. package/dist/extension/index.d.ts +31 -13
  102. package/dist/extension/index.js +5 -3
  103. package/dist/extension/index.js.map +1 -1
  104. package/dist/extension/react.js +8 -3
  105. package/dist/extension/react.js.map +1 -1
  106. package/dist/extension/subs/index.d.ts +2 -2
  107. package/dist/extension/subs/index.js.map +1 -1
  108. package/dist/extension/test-utils.js +11 -3
  109. package/dist/extension/test-utils.js.map +1 -1
  110. package/dist/fan-out/index.d.ts +239 -0
  111. package/dist/fan-out/index.js +5 -0
  112. package/dist/fan-out/index.js.map +1 -0
  113. package/dist/idempotency/adapter.d.ts +62 -0
  114. package/dist/idempotency/adapter.js +4 -0
  115. package/dist/idempotency/adapter.js.map +1 -0
  116. package/dist/idempotency/index.js +1 -56
  117. package/dist/idempotency/index.js.map +1 -1
  118. package/dist/idempotent-intake/index.d.ts +186 -0
  119. package/dist/idempotent-intake/index.js +7 -0
  120. package/dist/idempotent-intake/index.js.map +1 -0
  121. package/dist/index.d.ts +341 -191
  122. package/dist/index.js +2 -1
  123. package/dist/llm-call/index.d.ts +309 -0
  124. package/dist/llm-call/index.js +14 -0
  125. package/dist/llm-call/index.js.map +1 -0
  126. package/dist/machine-viz/index.d.ts +4 -4
  127. package/dist/machine-viz/index.js +5 -9
  128. package/dist/machine-viz/index.js.map +1 -1
  129. package/dist/mem/index.d.ts +1 -0
  130. package/dist/monitored-run/index.d.ts +253 -0
  131. package/dist/monitored-run/index.js +10 -0
  132. package/dist/monitored-run/index.js.map +1 -0
  133. package/dist/node/index.d.ts +5 -5
  134. package/dist/node/index.js.map +1 -1
  135. package/dist/paginated-walk/index.d.ts +234 -0
  136. package/dist/paginated-walk/index.js +15 -0
  137. package/dist/paginated-walk/index.js.map +1 -0
  138. package/dist/paginator/index.d.ts +271 -0
  139. package/dist/paginator/index.js +3 -0
  140. package/dist/paginator/index.js.map +1 -0
  141. package/dist/parity/index.d.ts +92 -0
  142. package/dist/parity/index.js +78 -0
  143. package/dist/parity/index.js.map +1 -0
  144. package/dist/pbt/arbitraries/index.d.ts +1 -1
  145. package/dist/pbt/arbitraries/index.js +1 -1
  146. package/dist/pbt/index.d.ts +15 -8
  147. package/dist/pbt/index.js +6 -11
  148. package/dist/pbt/index.js.map +1 -1
  149. package/dist/pbt/runners/index.d.ts +1 -1
  150. package/dist/pbt/runners/index.js +3 -2
  151. package/dist/poller/index.d.ts +288 -0
  152. package/dist/poller/index.js +79 -0
  153. package/dist/poller/index.js.map +1 -0
  154. package/dist/prediction/index.d.ts +130 -0
  155. package/dist/prediction/index.js +4 -0
  156. package/dist/prediction/index.js.map +1 -0
  157. package/dist/protocol-B5YmJr0d.d.ts +45 -0
  158. package/dist/pure/index.d.ts +2 -0
  159. package/dist/pure/index.js +4 -0
  160. package/dist/pure/index.js.map +1 -0
  161. package/dist/raft/demo.d.ts +105 -0
  162. package/dist/raft/demo.js +172 -0
  163. package/dist/raft/demo.js.map +1 -0
  164. package/dist/raft/index.d.ts +548 -0
  165. package/dist/raft/index.js +7 -0
  166. package/dist/raft/index.js.map +1 -0
  167. package/dist/raft/sim.d.ts +222 -0
  168. package/dist/raft/sim.js +8 -0
  169. package/dist/raft/sim.js.map +1 -0
  170. package/dist/raft/timeline.d.ts +46 -0
  171. package/dist/raft/timeline.js +62 -0
  172. package/dist/raft/timeline.js.map +1 -0
  173. package/dist/rate-limit/index.js +1 -43
  174. package/dist/rate-limit/index.js.map +1 -1
  175. package/dist/react/index.d.ts +2 -1
  176. package/dist/react/index.js +43 -20
  177. package/dist/react/index.js.map +1 -1
  178. package/dist/reconciler/index.d.ts +192 -0
  179. package/dist/reconciler/index.js +166 -0
  180. package/dist/reconciler/index.js.map +1 -0
  181. package/dist/recorder/index.d.ts +7 -3
  182. package/dist/recorder/index.js +1 -155
  183. package/dist/recorder/index.js.map +1 -1
  184. package/dist/resilient-call/index.d.ts +294 -0
  185. package/dist/resilient-call/index.js +13 -0
  186. package/dist/resilient-call/index.js.map +1 -0
  187. package/dist/retry-backoff/index.d.ts +42 -5
  188. package/dist/retry-backoff/index.js +1 -35
  189. package/dist/retry-backoff/index.js.map +1 -1
  190. package/dist/retry-to-success/index.d.ts +109 -0
  191. package/dist/retry-to-success/index.js +35 -0
  192. package/dist/retry-to-success/index.js.map +1 -0
  193. package/dist/saga/index.d.ts +238 -0
  194. package/dist/saga/index.js +150 -0
  195. package/dist/saga/index.js.map +1 -0
  196. package/dist/snapshot/index.d.ts +334 -0
  197. package/dist/snapshot/index.js +5 -0
  198. package/dist/snapshot/index.js.map +1 -0
  199. package/dist/subs/index.d.ts +48 -10
  200. package/dist/subs/index.js +1 -1
  201. package/dist/testing/index.d.ts +107 -2
  202. package/dist/testing/index.js +204 -6
  203. package/dist/testing/index.js.map +1 -1
  204. package/dist/throttle/index.d.ts +9 -0
  205. package/dist/throttle/index.js +1 -52
  206. package/dist/throttle/index.js.map +1 -1
  207. package/dist/throttled-input/index.d.ts +380 -0
  208. package/dist/throttled-input/index.js +88 -0
  209. package/dist/throttled-input/index.js.map +1 -0
  210. package/dist/token-refresh/index.d.ts +215 -0
  211. package/dist/token-refresh/index.js +6 -0
  212. package/dist/token-refresh/index.js.map +1 -0
  213. package/dist/trace-replay/index.d.ts +11 -2
  214. package/dist/trace-replay/index.js +3 -55
  215. package/dist/trace-replay/index.js.map +1 -1
  216. package/dist/{types-CwBC5wMn.d.ts → types-B-8bcAp8.d.ts} +1 -1
  217. package/dist/with-deadline/index.d.ts +196 -0
  218. package/dist/with-deadline/index.js +111 -0
  219. package/dist/with-deadline/index.js.map +1 -0
  220. package/dist/with-resilience/index.d.ts +205 -0
  221. package/dist/with-resilience/index.js +251 -0
  222. package/dist/with-resilience/index.js.map +1 -0
  223. package/dist/with-telemetry/index.d.ts +149 -0
  224. package/dist/with-telemetry/index.js +70 -0
  225. package/dist/with-telemetry/index.js.map +1 -0
  226. package/dist/work-queue/adapter.d.ts +82 -0
  227. package/dist/work-queue/adapter.js +4 -0
  228. package/dist/work-queue/adapter.js.map +1 -0
  229. package/dist/work-queue/index.d.ts +25 -11
  230. package/dist/work-queue/index.js +1 -46
  231. package/dist/work-queue/index.js.map +1 -1
  232. package/dist/work-queue/ops.d.ts +69 -0
  233. package/dist/work-queue/ops.js +3 -0
  234. package/dist/work-queue/ops.js.map +1 -0
  235. package/dist/workflow/index.d.ts +450 -0
  236. package/dist/workflow/index.js +225 -0
  237. package/dist/workflow/index.js.map +1 -0
  238. package/package.json +168 -25
  239. package/dist/chunk-CMG2KMWX.js.map +0 -1
  240. package/dist/chunk-PYBQREFU.js.map +0 -1
  241. package/dist/chunk-PYOCUBQJ.js.map +0 -1
  242. package/dist/chunk-Y5JM3UUH.js.map +0 -1
  243. package/dist/chunk-ZRUST6BK.js.map +0 -1
@@ -0,0 +1,506 @@
1
+ import { createMonitoredRun } from './chunk-7W4LMPUW.js';
2
+ import { createLlmCall } from './chunk-PS23H6KQ.js';
3
+ import { createResilientCall } from './chunk-27N2SPTN.js';
4
+ import { MsgType } from './chunk-JELSZN25.js';
5
+ import { createFanOut, initFanOut } from './chunk-UV6UWGEO.js';
6
+ import { subscribeDeadline } from './chunk-K7Q23EQ4.js';
7
+ import { defineMachine } from './chunk-MMH7CW5K.js';
8
+
9
+ // src/agent/index.ts
10
+ function isAgentTurn(value) {
11
+ if (value === null || typeof value !== "object") return false;
12
+ const t = value;
13
+ return typeof t.content === "string" && Array.isArray(t.toolCalls);
14
+ }
15
+ var agentTurnSchema = {
16
+ parse: (value) => {
17
+ if (!isAgentTurn(value)) {
18
+ throw new Error("structured-output parse failed: not an AgentTurn");
19
+ }
20
+ return value;
21
+ }
22
+ };
23
+ var COMPACTION_PURPOSE = "$compact";
24
+ function isCompactionSummary(value) {
25
+ if (value === null || typeof value !== "object") return false;
26
+ return typeof value.summary === "string";
27
+ }
28
+ var compactionSummarySchema = {
29
+ parse: (value) => {
30
+ if (!isCompactionSummary(value)) {
31
+ throw new Error(
32
+ "structured-output parse failed: not a CompactionSummary"
33
+ );
34
+ }
35
+ return value;
36
+ }
37
+ };
38
+ function status(s) {
39
+ if (s.failure !== null) {
40
+ return { kind: "failed", failure: s.failure };
41
+ }
42
+ if (s.run.phase === "failed" && s.run.failure !== null) {
43
+ return { kind: "failed", failure: s.run.failure };
44
+ }
45
+ if (s.run.phase === "done") {
46
+ return { kind: "done", output: s.output };
47
+ }
48
+ if (s.conversation !== null && s.conversation.awaiting.kind === "tools") {
49
+ return { kind: "suspended", pending: s.tools.running };
50
+ }
51
+ return { kind: "running" };
52
+ }
53
+ function createAgent(config) {
54
+ const rng = config.rng ?? Math.random;
55
+ const run = createMonitoredRun({
56
+ ...config.stages !== void 0 ? { stages: config.stages } : {},
57
+ ...config.deadlineMs !== void 0 ? { deadlineMs: config.deadlineMs } : {},
58
+ ...config.snapshotEvery !== void 0 ? { snapshotEvery: config.snapshotEvery } : {}
59
+ });
60
+ const llm = createLlmCall(
61
+ {
62
+ model: config.model,
63
+ schemas: config.schemas,
64
+ ...config.retry !== void 0 ? { retry: config.retry } : {},
65
+ ...config.loadMessages !== void 0 ? { loadMessages: config.loadMessages } : {}
66
+ },
67
+ rng
68
+ );
69
+ const compactRc = createResilientCall({ ...config.retry !== void 0 ? { retry: config.retry } : {} }, rng);
70
+ const fan = createFanOut({
71
+ concurrency: config.toolConcurrency ?? 1,
72
+ idOf: (call) => call.callId,
73
+ of: (call) => config.toolOf(call)
74
+ });
75
+ function init() {
76
+ return {
77
+ run: run.init(),
78
+ resilience: llm.init(),
79
+ tools: initFanOut(),
80
+ conversation: null,
81
+ compaction: compactRc.init(),
82
+ failure: null,
83
+ output: null
84
+ };
85
+ }
86
+ function freshConversation() {
87
+ return {
88
+ turns: [],
89
+ toolRecords: [],
90
+ turnCount: 0,
91
+ awaiting: { kind: "llm" }
92
+ };
93
+ }
94
+ function dedupeByCallId(calls) {
95
+ const seen = /* @__PURE__ */ new Set();
96
+ const out = [];
97
+ for (const call of calls) {
98
+ if (seen.has(call.callId)) continue;
99
+ seen.add(call.callId);
100
+ out.push(call);
101
+ }
102
+ return out;
103
+ }
104
+ function foldSummary(conv, folding, summaryTurn) {
105
+ const shift = folding - 1;
106
+ const survivingTurns = conv.turns.slice(folding);
107
+ const survivingRecords = conv.toolRecords.filter((rec) => rec.turn >= folding).map((rec) => ({ ...rec, turn: rec.turn - shift }));
108
+ return {
109
+ ...conv,
110
+ turns: [summaryTurn, ...survivingTurns],
111
+ toolRecords: survivingRecords,
112
+ awaiting: { kind: "llm" }
113
+ };
114
+ }
115
+ function currentStage(s) {
116
+ return s.run.stepStates.find((i) => i.status === "running")?.input;
117
+ }
118
+ function brainCall(s) {
119
+ const stage = currentStage(s);
120
+ const conversation = s.conversation ?? freshConversation();
121
+ return {
122
+ purpose: config.turnOf(stage),
123
+ model: config.modelId ?? null,
124
+ payload: config.payloadOf ? config.payloadOf(stage, conversation) : null
125
+ };
126
+ }
127
+ function start(s, runId, at) {
128
+ const [runSlice] = run.start(s.run, runId, at);
129
+ const conversation = freshConversation();
130
+ const withRun = {
131
+ ...s,
132
+ run: runSlice,
133
+ conversation,
134
+ failure: null,
135
+ // A restart clears the prior run's terminal output — `result()` reads
136
+ // `undefined` again until THIS run finishes (#46).
137
+ output: null,
138
+ tools: initFanOut(),
139
+ // A restart also clears any prior compaction slice — a fresh run never
140
+ // inherits the previous run's summarize retry bookkeeping (#85).
141
+ compaction: compactRc.init()
142
+ };
143
+ const call = brainCall(withRun);
144
+ const [resilience, cmds] = llm.attempt(withRun.resilience, call, at);
145
+ return [{ ...withRun, resilience }, cmds];
146
+ }
147
+ function turn(s, result, at) {
148
+ if (isSettled(s)) return [s, []];
149
+ const conv = s.conversation;
150
+ if (conv === null || conv.awaiting.kind !== "llm") return [s, []];
151
+ const withTurn = {
152
+ ...conv,
153
+ turns: [...conv.turns, result]
154
+ };
155
+ if (result.toolCalls.length === 0) {
156
+ return advanceStage({ ...s, conversation: withTurn }, result, at);
157
+ }
158
+ const batch = dedupeByCallId(result.toolCalls);
159
+ const [tools, launchCmds] = fan.scatter(
160
+ initFanOut(),
161
+ batch
162
+ );
163
+ const nextConv = {
164
+ ...withTurn,
165
+ awaiting: { kind: "tools", batchTurn: withTurn.turnCount }
166
+ };
167
+ const [runSlice] = run.progress(s.run, void 0, at);
168
+ return [{ ...s, run: runSlice, tools, conversation: nextConv }, launchCmds];
169
+ }
170
+ function advanceStage(s, terminatingTurn, at) {
171
+ const [runSlice, runCmds] = run.advance(
172
+ s.run,
173
+ void 0,
174
+ { kind: "ok" },
175
+ at
176
+ );
177
+ if (runSlice.phase === "done") {
178
+ return [
179
+ { ...s, run: runSlice, conversation: null, output: terminatingTurn },
180
+ runCmds
181
+ ];
182
+ }
183
+ const conversation = freshConversation();
184
+ const moved = {
185
+ ...s,
186
+ run: runSlice,
187
+ conversation,
188
+ tools: initFanOut()
189
+ };
190
+ const call = brainCall(moved);
191
+ const [resilience, llmCmds] = llm.attempt(moved.resilience, call, at);
192
+ return [{ ...moved, resilience }, [...runCmds, ...llmCmds]];
193
+ }
194
+ function toolOk(s, callId, result, at) {
195
+ return settleTool(s, callId, { kind: "ok", result }, at);
196
+ }
197
+ function toolErr(s, callId, reason, at) {
198
+ return settleTool(s, callId, { kind: "error", reason }, at);
199
+ }
200
+ function settleTool(s, callId, outcome, at) {
201
+ if (isSettled(s)) return [s, []];
202
+ const conv = s.conversation;
203
+ if (conv === null || conv.awaiting.kind !== "tools") return [s, []];
204
+ const call = s.tools.running.find((c) => c.callId === callId);
205
+ if (call === void 0) return [s, []];
206
+ const [tools, launchCmds] = outcome.kind === "ok" ? fan.itemOk(s.tools, callId, outcome) : fan.itemErr(s.tools, callId, outcome);
207
+ const foldedConv = {
208
+ ...conv,
209
+ // Stamp the producing-turn index on the record (#85, A1). At settle time
210
+ // `conv.turnCount` equals the index in `turns` of the turn that scattered
211
+ // this batch (each prior drained batch bumped `turnCount` exactly once, and
212
+ // each tool-bearing turn appended exactly one entry to `turns`), so a record
213
+ // carrying `turn: conv.turnCount` is dropped iff its producing turn is folded
214
+ // (`turn < N`) — the association the fold-back relies on.
215
+ toolRecords: [
216
+ ...conv.toolRecords,
217
+ { call, outcome, turn: conv.turnCount }
218
+ ]
219
+ };
220
+ if (!fan.isComplete(tools)) {
221
+ const [runSlice2] = run.progress(s.run, void 0, at);
222
+ return [
223
+ { ...s, run: runSlice2, tools, conversation: foldedConv },
224
+ launchCmds
225
+ ];
226
+ }
227
+ const turnedConv = {
228
+ ...foldedConv,
229
+ turnCount: foldedConv.turnCount + 1,
230
+ awaiting: { kind: "llm" }
231
+ };
232
+ if (config.maxTurns !== void 0 && turnedConv.turnCount >= config.maxTurns) {
233
+ return failTurnLimit({ ...s, tools, conversation: turnedConv }, at);
234
+ }
235
+ const drained = {
236
+ ...s,
237
+ tools: initFanOut(),
238
+ conversation: turnedConv
239
+ };
240
+ const compacting = maybeCompact(drained, at);
241
+ if (compacting !== null) return compacting;
242
+ const [runSlice] = run.progress(drained.run, void 0, at);
243
+ const fired = { ...drained, run: runSlice };
244
+ const nextCall = brainCall(fired);
245
+ const [resilience, llmCmds] = llm.attempt(fired.resilience, nextCall, at);
246
+ return [{ ...fired, resilience }, [...launchCmds, ...llmCmds]];
247
+ }
248
+ function maybeCompact(s, at) {
249
+ const policy = config.compaction;
250
+ const conv = s.conversation;
251
+ if (policy === void 0 || conv === null) return null;
252
+ const requested = policy.planCompaction(conv);
253
+ const folding = Math.min(requested, conv.turns.length);
254
+ if (folding < 2) return null;
255
+ const compactConv = {
256
+ ...conv,
257
+ awaiting: { kind: "compacting", folding }
258
+ };
259
+ const [runSlice] = run.progress(s.run, void 0, at);
260
+ const input = {
261
+ purpose: COMPACTION_PURPOSE,
262
+ model: config.modelId ?? null,
263
+ payload: policy.payloadOf ? policy.payloadOf(conv, folding) : null
264
+ };
265
+ const [compaction, runCmds] = compactRc.attempt(
266
+ s.compaction,
267
+ COMPACTION_PURPOSE,
268
+ input,
269
+ at
270
+ );
271
+ const cmds = runCmds.map(toCompactRunCmd);
272
+ return [
273
+ { ...s, run: runSlice, conversation: compactConv, compaction },
274
+ cmds
275
+ ];
276
+ }
277
+ function toCompactRunCmd(cmd) {
278
+ return {
279
+ type: MsgType.CompactRun,
280
+ key: COMPACTION_PURPOSE,
281
+ input: cmd.input
282
+ };
283
+ }
284
+ function failTurnLimit(s, at) {
285
+ return [{ ...s, failure: { reason: "turn_limit", at } }, []];
286
+ }
287
+ function succeed(s, key, msg, at) {
288
+ const [resilience, retryCmds] = llm.succeed(s.resilience, key, msg);
289
+ const settled = { ...s, resilience };
290
+ const [withTurn, turnCmds] = turn(settled, msg.result.output, at);
291
+ return [withTurn, [...retryCmds, ...turnCmds]];
292
+ }
293
+ function fail(s, key, msg, at) {
294
+ const [resilience, cmds] = llm.fail(s.resilience, key, msg);
295
+ const call = resilience.calls[key];
296
+ const failure = call?.phase === "failed" ? { reason: "llm", error: msg.error, at } : s.failure;
297
+ return [{ ...s, resilience, failure }, cmds];
298
+ }
299
+ function compactOk(s, key, msg, at) {
300
+ const [compaction, retryCmds] = compactRc.succeed(s.compaction, key, {
301
+ type: MsgType.ResilientOk,
302
+ key: msg.key,
303
+ result: msg.result,
304
+ at: msg.at
305
+ });
306
+ const settledRetry = { ...s, compaction };
307
+ if (isSettled(settledRetry)) return [settledRetry, []];
308
+ const conv = settledRetry.conversation;
309
+ if (conv === null || conv.awaiting.kind !== "compacting") {
310
+ return [settledRetry, retryCmds.map(toCompactRunCmd)];
311
+ }
312
+ const folding = conv.awaiting.folding;
313
+ const summaryTurn = {
314
+ content: msg.result.output.summary,
315
+ toolCalls: []
316
+ };
317
+ const foldedConv = foldSummary(conv, folding, summaryTurn);
318
+ const fired = { ...settledRetry, conversation: foldedConv };
319
+ const nextCall = brainCall(fired);
320
+ const [resilience, llmCmds] = llm.attempt(fired.resilience, nextCall, at);
321
+ return [
322
+ { ...fired, resilience },
323
+ [...retryCmds.map(toCompactRunCmd), ...llmCmds]
324
+ ];
325
+ }
326
+ function compactErr(s, key, msg, at) {
327
+ const [compaction, cmds] = compactRc.fail(s.compaction, key, {
328
+ type: MsgType.ResilientErr,
329
+ key: msg.key,
330
+ error: msg.error,
331
+ at: msg.at
332
+ });
333
+ const settledRetry = { ...s, compaction };
334
+ const call = compaction.calls[key];
335
+ if (call?.phase === "waiting_retry") {
336
+ return [settledRetry, cmds.map(toCompactRunCmd)];
337
+ }
338
+ if (isSettled(settledRetry)) return [settledRetry, []];
339
+ const conv = settledRetry.conversation;
340
+ if (conv === null || conv.awaiting.kind !== "compacting") {
341
+ return [settledRetry, cmds.map(toCompactRunCmd)];
342
+ }
343
+ const resumedConv = { ...conv, awaiting: { kind: "llm" } };
344
+ const fired = { ...settledRetry, conversation: resumedConv };
345
+ const nextCall = brainCall(fired);
346
+ const [resilience, llmCmds] = llm.attempt(fired.resilience, nextCall, at);
347
+ return [
348
+ { ...fired, resilience },
349
+ [...cmds.map(toCompactRunCmd), ...llmCmds]
350
+ ];
351
+ }
352
+ function onTimer(s, msg) {
353
+ if (msg.id.startsWith("monitored:")) {
354
+ const [runSlice] = run.onDeadline(s.run, msg);
355
+ return [{ ...s, run: runSlice }, []];
356
+ }
357
+ if (msg.id.endsWith(`:${COMPACTION_PURPOSE}`)) {
358
+ const [compaction, cmds2] = compactRc.onTimer(s.compaction, msg);
359
+ return [{ ...s, compaction }, cmds2.map(toCompactRunCmd)];
360
+ }
361
+ const [resilience, cmds] = llm.onTimer(s.resilience, msg);
362
+ return [{ ...s, resilience }, cmds];
363
+ }
364
+ function boot(s, at) {
365
+ const [runSlice] = run.boot(s.run, at);
366
+ const rebooted = { ...s, run: runSlice };
367
+ if (isSettled(rebooted)) return [rebooted, []];
368
+ const conv = rebooted.conversation;
369
+ if (conv === null) return [rebooted, []];
370
+ if (conv.awaiting.kind === "llm") {
371
+ const call = brainCall(rebooted);
372
+ const [resilience, cmds2] = llm.attempt(rebooted.resilience, call, at);
373
+ return [{ ...rebooted, resilience }, cmds2];
374
+ }
375
+ if (conv.awaiting.kind === "compacting") {
376
+ const input = {
377
+ purpose: COMPACTION_PURPOSE,
378
+ model: config.modelId ?? null,
379
+ payload: config.compaction?.payloadOf ? config.compaction.payloadOf(conv, conv.awaiting.folding) : null
380
+ };
381
+ const [compaction, cmds2] = compactRc.attempt(
382
+ rebooted.compaction,
383
+ COMPACTION_PURPOSE,
384
+ input,
385
+ at
386
+ );
387
+ return [{ ...rebooted, compaction }, cmds2.map(toCompactRunCmd)];
388
+ }
389
+ const cmds = rebooted.tools.running.map((call) => config.toolOf(call));
390
+ return [rebooted, cmds];
391
+ }
392
+ function isSettled(s) {
393
+ return s.run.phase === "done" || s.run.phase === "failed" || s.failure !== null;
394
+ }
395
+ function subs(s) {
396
+ return [
397
+ ...llm.subs(s.resilience),
398
+ ...compactRc.subs(s.compaction),
399
+ ...run.subs(s.run)
400
+ ];
401
+ }
402
+ function unsafeDetachedHandlers(ports) {
403
+ return llm.handlers(ports);
404
+ }
405
+ function brainHandlers() {
406
+ return llm.handlers();
407
+ }
408
+ function toMachine(opts) {
409
+ const consumerInterpret = opts?.toolInterpret ?? {};
410
+ const interpret = mergeInterpret(consumerInterpret, brainHandlers());
411
+ const update = {
412
+ [MsgType.AgentStart]: (s, m) => start(s, m.runId, m.at),
413
+ [MsgType.AgentToolOk]: (s, m) => toolOk(s, m.callId, m.result, m.at),
414
+ [MsgType.AgentToolErr]: (s, m) => toolErr(s, m.callId, m.reason, m.at),
415
+ // The re-entered brain-call settle Msgs (from `brainHandlers`): success
416
+ // runs `succeed` (reset retry + fold the turn), failure runs `fail`.
417
+ [MsgType.ResilientOk]: (s, m) => succeed(s, m.key, m, m.at),
418
+ [MsgType.ResilientErr]: (s, m) => fail(s, m.key, m, m.at),
419
+ // The re-entered compaction settle Msgs (from the consumer's `compact_run`
420
+ // cell, #85): `compact_ok` folds the summary back (drop oldest turns +
421
+ // their records, fire the next brain call), `compact_err` backs off via the
422
+ // compaction retry or proceeds without compacting.
423
+ [MsgType.CompactOk]: (s, m) => compactOk(s, m.key, m, m.at),
424
+ [MsgType.CompactErr]: (s, m) => compactErr(s, m.key, m, m.at),
425
+ deadline_exceeded: (s, m) => onTimer(s, m),
426
+ [MsgType.AgentBoot]: (s, m) => boot(s, m.at)
427
+ };
428
+ const machine = {
429
+ init: (loaded) => loaded !== null ? [loaded, []] : [init(), []],
430
+ update,
431
+ subscriptions: (s) => subs(s),
432
+ subscribe: { deadline: subscribeDeadline },
433
+ interpret
434
+ };
435
+ return defineMachine(machine);
436
+ }
437
+ return {
438
+ init,
439
+ start,
440
+ turn,
441
+ toolOk,
442
+ toolErr,
443
+ succeed,
444
+ fail,
445
+ compactOk,
446
+ compactErr,
447
+ onTimer,
448
+ boot,
449
+ isSettled,
450
+ currentStage,
451
+ brainCall,
452
+ subs,
453
+ // `toMachine` is THE wired path. `unsafeDetachedHandlers` is the
454
+ // hand-wiring escape hatch — named to advertise the retry-loop gap so it is
455
+ // never mistaken for the loop driver (#54).
456
+ toMachine,
457
+ unsafeDetachedHandlers
458
+ };
459
+ }
460
+ function agentBootMsg(at) {
461
+ return { type: MsgType.AgentBoot, at };
462
+ }
463
+ function agentEvents() {
464
+ return (msg, state) => {
465
+ const events = [];
466
+ switch (msg.type) {
467
+ case MsgType.ResilientOk:
468
+ events.push({ type: "TurnSettled", turn: msg.result.output });
469
+ break;
470
+ case MsgType.AgentToolOk:
471
+ events.push({
472
+ type: "ToolSettled",
473
+ callId: msg.callId,
474
+ result: msg.result
475
+ });
476
+ break;
477
+ // start / boot / timer / the *_err arms / the compaction settles carry no
478
+ // public event — return []. (No `default`: the switch is exhaustive over
479
+ // the Msg discriminant, so a new Msg variant forces a decision here at
480
+ // compile time.) Compaction is an internal optimization, not a semantic
481
+ // lifecycle moment a UI folds — its settles are deliberately silent here.
482
+ case MsgType.AgentStart:
483
+ case MsgType.AgentToolErr:
484
+ case MsgType.ResilientErr:
485
+ case MsgType.CompactOk:
486
+ case MsgType.CompactErr:
487
+ case "deadline_exceeded":
488
+ case MsgType.AgentBoot:
489
+ break;
490
+ }
491
+ if (state.run.phase === "done") {
492
+ events.push({ type: "RunDone", output: state.output });
493
+ }
494
+ return events;
495
+ };
496
+ }
497
+ function mergeInterpret(a, b) {
498
+ return { ...a ?? {}, ...b };
499
+ }
500
+ function liftAgent(state, [slice, cmds]) {
501
+ return [{ ...state, agent: slice }, cmds];
502
+ }
503
+
504
+ export { COMPACTION_PURPOSE, agentBootMsg, agentEvents, agentTurnSchema, compactionSummarySchema, createAgent, isAgentTurn, isCompactionSummary, liftAgent, mergeInterpret, status };
505
+ //# sourceMappingURL=chunk-S3FQN4SL.js.map
506
+ //# sourceMappingURL=chunk-S3FQN4SL.js.map