@demlik/tea 0.13.0 → 0.15.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 (373) hide show
  1. package/README.md +11 -9
  2. package/dist/agent/index.d.ts +638 -45
  3. package/dist/agent/index.js +9 -19
  4. package/dist/{chunk-RH5EFRVJ.js → chunk-22POWGFA.js} +31 -5
  5. package/dist/chunk-22POWGFA.js.map +1 -0
  6. package/dist/{chunk-DMYGQB4O.js → chunk-3B5X7SBB.js} +23 -6
  7. package/dist/chunk-3B5X7SBB.js.map +1 -0
  8. package/dist/chunk-66PY5WYF.js +1816 -0
  9. package/dist/chunk-66PY5WYF.js.map +1 -0
  10. package/dist/{chunk-25LBDCBC.js → chunk-6IQPODUF.js} +2 -2
  11. package/dist/{chunk-25LBDCBC.js.map → chunk-6IQPODUF.js.map} +1 -1
  12. package/dist/chunk-AYS5N6WY.js +505 -0
  13. package/dist/chunk-AYS5N6WY.js.map +1 -0
  14. package/dist/{chunk-EWJP3YYP.js → chunk-HWVW4AXC.js} +3 -3
  15. package/dist/chunk-HWVW4AXC.js.map +1 -0
  16. package/dist/{chunk-O4MVQTEJ.js → chunk-L3TND7LA.js} +20 -16
  17. package/dist/chunk-L3TND7LA.js.map +1 -0
  18. package/dist/{chunk-J6527VRQ.js → chunk-LFZUK6J2.js} +3 -3
  19. package/dist/chunk-LFZUK6J2.js.map +1 -0
  20. package/dist/{chunk-D736QUGF.js → chunk-MYXFNWAJ.js} +4 -5
  21. package/dist/chunk-MYXFNWAJ.js.map +1 -0
  22. package/dist/{chunk-K575PT4S.js → chunk-PR6TB3BL.js} +15 -4
  23. package/dist/chunk-PR6TB3BL.js.map +1 -0
  24. package/dist/{chunk-YUXP55T2.js → chunk-Q5CQTBFA.js} +57 -7
  25. package/dist/chunk-Q5CQTBFA.js.map +1 -0
  26. package/dist/{batch-window/index.js → chunk-QPEVCJ5Q.js} +4 -8
  27. package/dist/chunk-QPEVCJ5Q.js.map +1 -0
  28. package/dist/chunk-TCLBCERH.js +1480 -0
  29. package/dist/chunk-TCLBCERH.js.map +1 -0
  30. package/dist/{chunk-FV3Z5MBE.js → chunk-TXN2KFHF.js} +14 -4
  31. package/dist/chunk-TXN2KFHF.js.map +1 -0
  32. package/dist/{chunk-MUUROGIH.js → chunk-V46HSVCK.js} +62 -12
  33. package/dist/chunk-V46HSVCK.js.map +1 -0
  34. package/dist/{chunk-Q2UM7BXU.js → chunk-VBDU4JL6.js} +2 -2
  35. package/dist/chunk-VBDU4JL6.js.map +1 -0
  36. package/dist/{chunk-ZVJZ72HY.js → chunk-VTQI2NHP.js} +25 -11
  37. package/dist/chunk-VTQI2NHP.js.map +1 -0
  38. package/dist/{core-Co0LWkIA.d.ts → core-DnzqWy6u.d.ts} +72 -23
  39. package/dist/devtools/index.d.ts +2 -2
  40. package/dist/devtools/index.js +207 -2
  41. package/dist/devtools/index.js.map +1 -1
  42. package/dist/do/index.d.ts +43 -29
  43. package/dist/do/index.js +36 -25
  44. package/dist/do/index.js.map +1 -1
  45. package/dist/{durable-effects-C6uwzjb5.d.ts → durable-effects-CWzA-o2B.d.ts} +2 -2
  46. package/dist/extension/index.d.ts +300 -3
  47. package/dist/extension/index.js +596 -5
  48. package/dist/extension/index.js.map +1 -1
  49. package/dist/flow/index.d.ts +1284 -0
  50. package/dist/flow/index.js +732 -0
  51. package/dist/flow/index.js.map +1 -0
  52. package/dist/idempotency/index.d.ts +90 -116
  53. package/dist/idempotency/index.js +4 -1
  54. package/dist/index-Bc40JWVl.d.ts +131 -0
  55. package/dist/{batch-window/index.d.ts → index-C2DwkjlP.d.ts} +7 -12
  56. package/dist/index-CA_7I5g9.d.ts +806 -0
  57. package/dist/index-CSyMYDAB.d.ts +69 -0
  58. package/dist/{fan-out/index.d.ts → index-CuNO9m8i.d.ts} +7 -9
  59. package/dist/{debounce/index.d.ts → index-DHSUmQTR.d.ts} +7 -7
  60. package/dist/{recorder/index.d.ts → index-DrIRb_Ch.d.ts} +4 -7
  61. package/dist/index-HSYgG2Yt.d.ts +380 -0
  62. package/dist/{monitored-run/index.d.ts → index-KXqTRJyb.d.ts} +37 -13
  63. package/dist/{snapshot/index.d.ts → index-ZCMhnVKN.d.ts} +15 -78
  64. package/dist/index.d.ts +771 -6
  65. package/dist/index.js +1 -2
  66. package/dist/jev/index.d.ts +646 -0
  67. package/dist/jev/index.js +485 -0
  68. package/dist/jev/index.js.map +1 -0
  69. package/dist/machine-DGlPWCWI.d.ts +1781 -0
  70. package/dist/machine-viz/index.d.ts +1 -1
  71. package/dist/machine-viz/index.js +12 -5
  72. package/dist/machine-viz/index.js.map +1 -1
  73. package/dist/mem/index.d.ts +18 -3
  74. package/dist/mem/index.js +22 -2
  75. package/dist/mem/index.js.map +1 -1
  76. package/dist/node/index.d.ts +104 -6
  77. package/dist/node/index.js +132 -9
  78. package/dist/node/index.js.map +1 -1
  79. package/dist/{paginator → paginate}/index.d.ts +140 -6
  80. package/dist/paginate/index.js +7 -0
  81. package/dist/parity/index.d.ts +4 -10
  82. package/dist/parity/index.js +4 -7
  83. package/dist/parity/index.js.map +1 -1
  84. package/dist/pbt/index.d.ts +247 -5
  85. package/dist/pbt/index.js +124 -5
  86. package/dist/pbt/index.js.map +1 -1
  87. package/dist/{trace-replay → persistence}/index.d.ts +7 -5
  88. package/dist/persistence/index.js +6 -0
  89. package/dist/{protocol-B5YmJr0d.d.ts → protocol-D8VbH-VH.d.ts} +10 -1
  90. package/dist/react/index.d.ts +2 -2
  91. package/dist/react/index.js +1 -2
  92. package/dist/react/index.js.map +1 -1
  93. package/dist/resilience/index.d.ts +744 -0
  94. package/dist/resilience/index.js +657 -0
  95. package/dist/resilience/index.js.map +1 -0
  96. package/dist/retry-backoff/index.d.ts +3 -2
  97. package/dist/retry-backoff/index.js +1 -1
  98. package/dist/runtime-types-CMF13BBh.d.ts +998 -0
  99. package/dist/testing/index.d.ts +147 -3
  100. package/dist/testing/index.js +95 -3
  101. package/dist/testing/index.js.map +1 -1
  102. package/dist/{throttled-input → timing}/index.d.ts +143 -12
  103. package/dist/{throttled-input → timing}/index.js +57 -12
  104. package/dist/timing/index.js.map +1 -0
  105. package/dist/{types-XS_miRnB.d.ts → types-BseNPIhr.d.ts} +1 -1
  106. package/dist/work-queue/index.d.ts +130 -54
  107. package/dist/work-queue/index.js +3 -2
  108. package/dist/work-queue/index.js.map +1 -1
  109. package/package.json +45 -218
  110. package/dist/authed-call/index.d.ts +0 -120
  111. package/dist/authed-call/index.js +0 -134
  112. package/dist/authed-call/index.js.map +0 -1
  113. package/dist/await-terminal/index.d.ts +0 -101
  114. package/dist/await-terminal/index.js +0 -76
  115. package/dist/await-terminal/index.js.map +0 -1
  116. package/dist/batch-window/index.js.map +0 -1
  117. package/dist/cache/index.d.ts +0 -152
  118. package/dist/cache/index.js +0 -8
  119. package/dist/chart/index.d.ts +0 -218
  120. package/dist/chart/index.js +0 -16
  121. package/dist/chart/index.js.map +0 -1
  122. package/dist/chart/inspect/index.d.ts +0 -86
  123. package/dist/chart/inspect/index.js +0 -5
  124. package/dist/chart/inspect/react.d.ts +0 -113
  125. package/dist/chart/inspect/react.js +0 -11
  126. package/dist/chart/inspect/react.js.map +0 -1
  127. package/dist/chart/inspect/styles.css +0 -286
  128. package/dist/chart/lane/index.d.ts +0 -362
  129. package/dist/chart/lane/index.js +0 -9
  130. package/dist/chart/lane/index.js.map +0 -1
  131. package/dist/chart/lane/react.d.ts +0 -84
  132. package/dist/chart/lane/react.js +0 -559
  133. package/dist/chart/lane/react.js.map +0 -1
  134. package/dist/chart/lane/server.d.ts +0 -148
  135. package/dist/chart/lane/server.js +0 -209
  136. package/dist/chart/lane/server.js.map +0 -1
  137. package/dist/chart/lane/styles.css +0 -498
  138. package/dist/chart/lane/viewer/assets/abnfDiagram-N423BO3Z-C729LI31.js +0 -1
  139. package/dist/chart/lane/viewer/assets/architectureDiagram-T3A2C74G-C729LI31.js +0 -1
  140. package/dist/chart/lane/viewer/assets/blockDiagram-VBNYF7ZC-C729LI31.js +0 -1
  141. package/dist/chart/lane/viewer/assets/c4Diagram-5PPSVZJV-C729LI31.js +0 -1
  142. package/dist/chart/lane/viewer/assets/chunk-2GRJ4B5K-HdDf8SI3.js +0 -1
  143. package/dist/chart/lane/viewer/assets/chunk-5RXB4S5H-CcNtpUd7.js +0 -231
  144. package/dist/chart/lane/viewer/assets/chunk-5VM5RSS4-BP4fRS_5.js +0 -15
  145. package/dist/chart/lane/viewer/assets/chunk-KBJHAD2P-DZOw7xU6.js +0 -1
  146. package/dist/chart/lane/viewer/assets/chunk-NSK5VX7P-CBCyTZMs.js +0 -128
  147. package/dist/chart/lane/viewer/assets/classDiagram-JCYQIIEL-C729LI31.js +0 -1
  148. package/dist/chart/lane/viewer/assets/classDiagram-v2-OCEON4UE-D4uAiFr8.js +0 -206
  149. package/dist/chart/lane/viewer/assets/cose-bilkent-JH36ORCC-DOwCrGXH.js +0 -1
  150. package/dist/chart/lane/viewer/assets/cynefinDiagram-MW4NZA55-C729LI31.js +0 -1
  151. package/dist/chart/lane/viewer/assets/dagre-K_PewWfS.js +0 -1
  152. package/dist/chart/lane/viewer/assets/dagre-VZM6K2ZE-831qZcA8.js +0 -4
  153. package/dist/chart/lane/viewer/assets/diagram-7IWD3JNH-C729LI31.js +0 -1
  154. package/dist/chart/lane/viewer/assets/diagram-B4RE2ZJO-C729LI31.js +0 -1
  155. package/dist/chart/lane/viewer/assets/diagram-LBJQPF4R-C729LI31.js +0 -1
  156. package/dist/chart/lane/viewer/assets/diagram-Q27KOJAE-C729LI31.js +0 -1
  157. package/dist/chart/lane/viewer/assets/diagram-UB23O5K3-C729LI31.js +0 -1
  158. package/dist/chart/lane/viewer/assets/ebnfDiagram-BXEA7PRR-C729LI31.js +0 -1
  159. package/dist/chart/lane/viewer/assets/erDiagram-JOGREHBK-C729LI31.js +0 -1
  160. package/dist/chart/lane/viewer/assets/flowDiagram-UKHOOZJN-C729LI31.js +0 -1
  161. package/dist/chart/lane/viewer/assets/ganttDiagram-PKOTCBZU-C729LI31.js +0 -1
  162. package/dist/chart/lane/viewer/assets/gitGraphDiagram-DS77QQ5N-C729LI31.js +0 -1
  163. package/dist/chart/lane/viewer/assets/index-9SkH5NA3.css +0 -1
  164. package/dist/chart/lane/viewer/assets/index-Bgt4sXpW.js +0 -195
  165. package/dist/chart/lane/viewer/assets/infoDiagram-6WML65LV-C729LI31.js +0 -1
  166. package/dist/chart/lane/viewer/assets/ishikawaDiagram-WSZJBQD7-C729LI31.js +0 -1
  167. package/dist/chart/lane/viewer/assets/journeyDiagram-NVQOT4AX-C729LI31.js +0 -1
  168. package/dist/chart/lane/viewer/assets/kanban-definition-27J2QSJJ-G7PaPzy-.js +0 -89
  169. package/dist/chart/lane/viewer/assets/katex-DOwCrGXH.js +0 -1
  170. package/dist/chart/lane/viewer/assets/mindmap-definition-FAOFIHXS-CGj9nrVk.js +0 -96
  171. package/dist/chart/lane/viewer/assets/path-fybaL0A-.js +0 -1
  172. package/dist/chart/lane/viewer/assets/pegDiagram-VL7TDLO6-C729LI31.js +0 -1
  173. package/dist/chart/lane/viewer/assets/pieDiagram-7S7Q4E2Y-C729LI31.js +0 -1
  174. package/dist/chart/lane/viewer/assets/quadrantDiagram-CIZ2JOQS-C729LI31.js +0 -1
  175. package/dist/chart/lane/viewer/assets/railroadDiagram-AXF67PYL-C729LI31.js +0 -1
  176. package/dist/chart/lane/viewer/assets/requirementDiagram-LRYGKXZP-C729LI31.js +0 -1
  177. package/dist/chart/lane/viewer/assets/sankeyDiagram-W5VNT64P-C729LI31.js +0 -1
  178. package/dist/chart/lane/viewer/assets/sequenceDiagram-SI44F4Z6-C729LI31.js +0 -1
  179. package/dist/chart/lane/viewer/assets/stateDiagram-OKZ733FA-B_88AzBS.js +0 -1
  180. package/dist/chart/lane/viewer/assets/stateDiagram-v2-UEYNNEHI-CR5gcgq6.js +0 -1
  181. package/dist/chart/lane/viewer/assets/swimlanes-SLNWSIFB-B4xK-rwg.js +0 -1
  182. package/dist/chart/lane/viewer/assets/swimlanesDiagram-ULZ7WXOC-C729LI31.js +0 -1
  183. package/dist/chart/lane/viewer/assets/timeline-definition-Z64GVDOM-CCv52MfY.js +0 -120
  184. package/dist/chart/lane/viewer/assets/vennDiagram-T6HMQDX7-C729LI31.js +0 -1
  185. package/dist/chart/lane/viewer/assets/wardleyDiagram-T6FBY63Y-C729LI31.js +0 -1
  186. package/dist/chart/lane/viewer/assets/xychartDiagram-ELKLHX3M-C729LI31.js +0 -1
  187. package/dist/chart/lane/viewer/index.html +0 -15
  188. package/dist/chart/report/index.d.ts +0 -117
  189. package/dist/chart/report/index.js +0 -32
  190. package/dist/chart/report/index.js.map +0 -1
  191. package/dist/chunk-2YFLOCWX.js +0 -15
  192. package/dist/chunk-2YFLOCWX.js.map +0 -1
  193. package/dist/chunk-3I52QZZ5.js +0 -519
  194. package/dist/chunk-3I52QZZ5.js.map +0 -1
  195. package/dist/chunk-3ZAFFRRB.js +0 -457
  196. package/dist/chunk-3ZAFFRRB.js.map +0 -1
  197. package/dist/chunk-4EQZ76JC.js +0 -33
  198. package/dist/chunk-4EQZ76JC.js.map +0 -1
  199. package/dist/chunk-4KLG43GY.js +0 -223
  200. package/dist/chunk-4KLG43GY.js.map +0 -1
  201. package/dist/chunk-7FRZ2CT2.js +0 -424
  202. package/dist/chunk-7FRZ2CT2.js.map +0 -1
  203. package/dist/chunk-AZZLE7XR.js +0 -62
  204. package/dist/chunk-AZZLE7XR.js.map +0 -1
  205. package/dist/chunk-BYQUGDD3.js +0 -16
  206. package/dist/chunk-BYQUGDD3.js.map +0 -1
  207. package/dist/chunk-CIQG5L42.js +0 -685
  208. package/dist/chunk-CIQG5L42.js.map +0 -1
  209. package/dist/chunk-CLM6ERNO.js +0 -61
  210. package/dist/chunk-CLM6ERNO.js.map +0 -1
  211. package/dist/chunk-COS5MSTO.js +0 -88
  212. package/dist/chunk-COS5MSTO.js.map +0 -1
  213. package/dist/chunk-CRPZJVD2.js +0 -71
  214. package/dist/chunk-CRPZJVD2.js.map +0 -1
  215. package/dist/chunk-D62FDQKE.js +0 -53
  216. package/dist/chunk-D62FDQKE.js.map +0 -1
  217. package/dist/chunk-D736QUGF.js.map +0 -1
  218. package/dist/chunk-DGE4PV4A.js +0 -26
  219. package/dist/chunk-DGE4PV4A.js.map +0 -1
  220. package/dist/chunk-DMYGQB4O.js.map +0 -1
  221. package/dist/chunk-EWJP3YYP.js.map +0 -1
  222. package/dist/chunk-FV3Z5MBE.js.map +0 -1
  223. package/dist/chunk-HCEVHFJ7.js +0 -54
  224. package/dist/chunk-HCEVHFJ7.js.map +0 -1
  225. package/dist/chunk-J6527VRQ.js.map +0 -1
  226. package/dist/chunk-JELSZN25.js +0 -47
  227. package/dist/chunk-JELSZN25.js.map +0 -1
  228. package/dist/chunk-K575PT4S.js.map +0 -1
  229. package/dist/chunk-L57ZOT5K.js +0 -184
  230. package/dist/chunk-L57ZOT5K.js.map +0 -1
  231. package/dist/chunk-MU6MCIAC.js +0 -15
  232. package/dist/chunk-MU6MCIAC.js.map +0 -1
  233. package/dist/chunk-MUUROGIH.js.map +0 -1
  234. package/dist/chunk-NR7BU22N.js +0 -758
  235. package/dist/chunk-NR7BU22N.js.map +0 -1
  236. package/dist/chunk-O4MVQTEJ.js.map +0 -1
  237. package/dist/chunk-OOYD44JI.js +0 -317
  238. package/dist/chunk-OOYD44JI.js.map +0 -1
  239. package/dist/chunk-Q2UM7BXU.js.map +0 -1
  240. package/dist/chunk-RH5EFRVJ.js.map +0 -1
  241. package/dist/chunk-S2EGRPCM.js +0 -47
  242. package/dist/chunk-S2EGRPCM.js.map +0 -1
  243. package/dist/chunk-SINXE47Y.js +0 -55
  244. package/dist/chunk-SINXE47Y.js.map +0 -1
  245. package/dist/chunk-UF4MZSLT.js +0 -53
  246. package/dist/chunk-UF4MZSLT.js.map +0 -1
  247. package/dist/chunk-UOC2PL46.js +0 -13
  248. package/dist/chunk-UOC2PL46.js.map +0 -1
  249. package/dist/chunk-VYFAZN3F.js +0 -372
  250. package/dist/chunk-VYFAZN3F.js.map +0 -1
  251. package/dist/chunk-WRAA7GVZ.js +0 -209
  252. package/dist/chunk-WRAA7GVZ.js.map +0 -1
  253. package/dist/chunk-XGELA764.js +0 -163
  254. package/dist/chunk-XGELA764.js.map +0 -1
  255. package/dist/chunk-YUXP55T2.js.map +0 -1
  256. package/dist/chunk-YWIKDKHY.js +0 -307
  257. package/dist/chunk-YWIKDKHY.js.map +0 -1
  258. package/dist/chunk-ZJ5AOYBH.js +0 -8
  259. package/dist/chunk-ZJ5AOYBH.js.map +0 -1
  260. package/dist/chunk-ZSUUOEPL.js +0 -731
  261. package/dist/chunk-ZSUUOEPL.js.map +0 -1
  262. package/dist/chunk-ZVJZ72HY.js.map +0 -1
  263. package/dist/circuit-breaker/index.d.ts +0 -197
  264. package/dist/circuit-breaker/index.js +0 -3
  265. package/dist/circuit-breaker/index.js.map +0 -1
  266. package/dist/deadline/index.d.ts +0 -199
  267. package/dist/deadline/index.js +0 -6
  268. package/dist/deadline/index.js.map +0 -1
  269. package/dist/debounce/index.js +0 -3
  270. package/dist/debounce/index.js.map +0 -1
  271. package/dist/extension/react.d.ts +0 -121
  272. package/dist/extension/react.js +0 -75
  273. package/dist/extension/react.js.map +0 -1
  274. package/dist/extension/subs/index.d.ts +0 -45
  275. package/dist/extension/subs/index.js +0 -80
  276. package/dist/extension/subs/index.js.map +0 -1
  277. package/dist/extension/test-utils.d.ts +0 -128
  278. package/dist/extension/test-utils.js +0 -277
  279. package/dist/extension/test-utils.js.map +0 -1
  280. package/dist/fan-out/index.js +0 -5
  281. package/dist/fan-out/index.js.map +0 -1
  282. package/dist/fold-BJPdjc9w.d.ts +0 -435
  283. package/dist/graph-B3L5e0N1.d.ts +0 -923
  284. package/dist/idempotency/adapter.d.ts +0 -62
  285. package/dist/idempotency/adapter.js +0 -4
  286. package/dist/idempotency/adapter.js.map +0 -1
  287. package/dist/idempotent-intake/index.d.ts +0 -188
  288. package/dist/idempotent-intake/index.js +0 -7
  289. package/dist/idempotent-intake/index.js.map +0 -1
  290. package/dist/journal/index.d.ts +0 -373
  291. package/dist/journal/index.js +0 -3
  292. package/dist/journal/index.js.map +0 -1
  293. package/dist/llm-call/index.d.ts +0 -311
  294. package/dist/llm-call/index.js +0 -16
  295. package/dist/llm-call/index.js.map +0 -1
  296. package/dist/machine-BtFWQmmq.d.ts +0 -804
  297. package/dist/monitored-run/index.js +0 -10
  298. package/dist/monitored-run/index.js.map +0 -1
  299. package/dist/paginated-walk/index.d.ts +0 -235
  300. package/dist/paginated-walk/index.js +0 -16
  301. package/dist/paginated-walk/index.js.map +0 -1
  302. package/dist/paginator/index.js +0 -3
  303. package/dist/paginator/index.js.map +0 -1
  304. package/dist/pbt/arbitraries/index.d.ts +0 -136
  305. package/dist/pbt/arbitraries/index.js +0 -3
  306. package/dist/pbt/arbitraries/index.js.map +0 -1
  307. package/dist/pbt/runners/index.d.ts +0 -118
  308. package/dist/pbt/runners/index.js +0 -5
  309. package/dist/pbt/runners/index.js.map +0 -1
  310. package/dist/poller/index.d.ts +0 -352
  311. package/dist/poller/index.js +0 -115
  312. package/dist/poller/index.js.map +0 -1
  313. package/dist/prediction/index.d.ts +0 -131
  314. package/dist/prediction/index.js +0 -4
  315. package/dist/prediction/index.js.map +0 -1
  316. package/dist/pure/index.d.ts +0 -3
  317. package/dist/pure/index.js +0 -4
  318. package/dist/pure/index.js.map +0 -1
  319. package/dist/rate-limit/index.d.ts +0 -115
  320. package/dist/rate-limit/index.js +0 -3
  321. package/dist/rate-limit/index.js.map +0 -1
  322. package/dist/reconciler/index.d.ts +0 -193
  323. package/dist/reconciler/index.js +0 -164
  324. package/dist/reconciler/index.js.map +0 -1
  325. package/dist/recorder/index.js +0 -3
  326. package/dist/recorder/index.js.map +0 -1
  327. package/dist/reducer-4GNR6b8B.d.ts +0 -447
  328. package/dist/resilient-call/index.d.ts +0 -320
  329. package/dist/resilient-call/index.js +0 -14
  330. package/dist/resilient-call/index.js.map +0 -1
  331. package/dist/retry-to-success/index.d.ts +0 -109
  332. package/dist/retry-to-success/index.js +0 -37
  333. package/dist/retry-to-success/index.js.map +0 -1
  334. package/dist/run-pAcmBpah.d.ts +0 -713
  335. package/dist/runtime-types-CNLmhWif.d.ts +0 -517
  336. package/dist/saga/index.d.ts +0 -241
  337. package/dist/saga/index.js +0 -150
  338. package/dist/saga/index.js.map +0 -1
  339. package/dist/samples-B3My5oh2.d.ts +0 -59
  340. package/dist/snapshot/index.js +0 -5
  341. package/dist/snapshot/index.js.map +0 -1
  342. package/dist/subs/index.d.ts +0 -472
  343. package/dist/subs/index.js +0 -7
  344. package/dist/subs/index.js.map +0 -1
  345. package/dist/throttle/index.d.ts +0 -134
  346. package/dist/throttle/index.js +0 -3
  347. package/dist/throttle/index.js.map +0 -1
  348. package/dist/throttled-input/index.js.map +0 -1
  349. package/dist/token-refresh/index.d.ts +0 -216
  350. package/dist/token-refresh/index.js +0 -6
  351. package/dist/token-refresh/index.js.map +0 -1
  352. package/dist/trace-replay/index.js +0 -6
  353. package/dist/trace-replay/index.js.map +0 -1
  354. package/dist/with-deadline/index.d.ts +0 -197
  355. package/dist/with-deadline/index.js +0 -111
  356. package/dist/with-deadline/index.js.map +0 -1
  357. package/dist/with-resilience/index.d.ts +0 -225
  358. package/dist/with-resilience/index.js +0 -240
  359. package/dist/with-resilience/index.js.map +0 -1
  360. package/dist/with-telemetry/index.d.ts +0 -150
  361. package/dist/with-telemetry/index.js +0 -70
  362. package/dist/with-telemetry/index.js.map +0 -1
  363. package/dist/work-queue/adapter.d.ts +0 -84
  364. package/dist/work-queue/adapter.js +0 -4
  365. package/dist/work-queue/adapter.js.map +0 -1
  366. package/dist/work-queue/ops.d.ts +0 -71
  367. package/dist/work-queue/ops.js +0 -3
  368. package/dist/work-queue/ops.js.map +0 -1
  369. package/dist/workflow/index.d.ts +0 -485
  370. package/dist/workflow/index.js +0 -244
  371. package/dist/workflow/index.js.map +0 -1
  372. /package/dist/{cache → paginate}/index.js.map +0 -0
  373. /package/dist/{chart/inspect → persistence}/index.js.map +0 -0
@@ -0,0 +1,1480 @@
1
+ import { createMonitoredRun } from './chunk-3B5X7SBB.js';
2
+ import { createFanOut, initFanOut } from './chunk-MYXFNWAJ.js';
3
+ import { MsgType, createResilientCall } from './chunk-AYS5N6WY.js';
4
+ import { subscribeDeadline } from './chunk-22POWGFA.js';
5
+ import { describeError } from './chunk-G5E74IJB.js';
6
+ import { Cmd, cmdEdgeOf, detachWorkOf, absurd, defineMachine, malformedResult, run, driveToDone } from './chunk-66PY5WYF.js';
7
+ import { Result } from 'better-result';
8
+ import { z } from 'zod';
9
+
10
+ // src/internal/llm-call/index.ts
11
+ function plainModel(fn) {
12
+ return () => ({
13
+ withStructuredOutput(schema) {
14
+ return {
15
+ invoke: async (messages) => schema.parse(await fn(messages))
16
+ };
17
+ }
18
+ });
19
+ }
20
+ function isPlainModel(model) {
21
+ return Object.prototype.toString.call(model) === "[object AsyncFunction]";
22
+ }
23
+ var PLAIN_MODEL_MISROUTE_REASON = "model: a sync function returned a Promise where an Llm was expected \u2014 a promise-returning model that is not declared `async` must be wrapped in plainModel(fn) (see the llm-call module)";
24
+ function isThenable(value) {
25
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
26
+ }
27
+ function asModelFactory(model) {
28
+ if (isPlainModel(model)) return plainModel(model);
29
+ return (modelId) => {
30
+ const llm = model(modelId);
31
+ if (isThenable(llm)) {
32
+ llm.then(void 0, () => void 0);
33
+ throw new Error(PLAIN_MODEL_MISROUTE_REASON);
34
+ }
35
+ return llm;
36
+ };
37
+ }
38
+ function createLlmCall(config, rng = Math.random) {
39
+ const resilientConfig = {
40
+ ...config.retry === void 0 ? {} : { retry: config.retry }
41
+ };
42
+ const rc = createResilientCall(resilientConfig, rng);
43
+ const modelOf = asModelFactory(config.model);
44
+ function init() {
45
+ return rc.init();
46
+ }
47
+ function attempt(s, input, at, key = input.purpose) {
48
+ return rc.attempt(s, key, input, at);
49
+ }
50
+ function succeed(s, key, msg) {
51
+ return rc.succeed(s, key, msg);
52
+ }
53
+ function fail(s, key, msg) {
54
+ return rc.fail(s, key, msg);
55
+ }
56
+ function onTimer(s, msg) {
57
+ return rc.onTimer(s, msg);
58
+ }
59
+ function subs(s) {
60
+ return rc.subs(s);
61
+ }
62
+ async function invokeOne(input) {
63
+ const model = modelOf(input.model);
64
+ const messages = config.loadMessages ? await config.loadMessages(input) : [];
65
+ const schema = config.schemas[input.purpose];
66
+ const structured = model.withStructuredOutput(schema);
67
+ const raw = await structured.invoke(messages);
68
+ const output = schema.parse(raw);
69
+ return { key: input.purpose, purpose: input.purpose, output };
70
+ }
71
+ const resilientRunHandler = rc.handlers({
72
+ run: (input) => invokeOne(input)
73
+ }).resilient_run;
74
+ async function settleOf(cmd) {
75
+ const settle = await resilientRunHandler(cmd, {});
76
+ if (settle.type === MsgType.ResilientOk) {
77
+ return { ...settle, result: { ...settle.result, key: cmd.key } };
78
+ }
79
+ const rawError = settle.error;
80
+ const err = {
81
+ key: cmd.key,
82
+ purpose: cmd.input.purpose,
83
+ reason: describeError(rawError),
84
+ error: rawError
85
+ };
86
+ return {
87
+ type: MsgType.ResilientErr,
88
+ key: settle.key,
89
+ error: err,
90
+ at: settle.at
91
+ };
92
+ }
93
+ function handlers(ports) {
94
+ if (ports === void 0) {
95
+ return { resilient_run: (cmd) => settleOf(cmd) };
96
+ }
97
+ return {
98
+ resilient_run: (cmd, ctx) => {
99
+ const fired = (async () => {
100
+ const settle = await settleOf(cmd);
101
+ if (settle.type === MsgType.ResilientOk) {
102
+ const msg2 = ports.onOk(settle.result);
103
+ if (msg2 !== void 0) await ctx.dispatch(msg2);
104
+ return;
105
+ }
106
+ const msg = ports.onErr(settle.error);
107
+ if (msg !== void 0) await ctx.dispatch(msg);
108
+ })();
109
+ ctx.waitUntil(fired);
110
+ }
111
+ };
112
+ }
113
+ return {
114
+ name: rc.name,
115
+ init,
116
+ attempt,
117
+ succeed,
118
+ fail,
119
+ onTimer,
120
+ subs,
121
+ handlers,
122
+ invokeOne
123
+ };
124
+ }
125
+
126
+ // src/agent/schema.ts
127
+ function schemaFromGuard(guard, name) {
128
+ return {
129
+ parse: (value) => {
130
+ if (!guard(value)) {
131
+ throw new Error(`structured-output parse failed: not ${name}`);
132
+ }
133
+ return value;
134
+ }
135
+ };
136
+ }
137
+
138
+ // src/agent/compaction.ts
139
+ var COMPACTION_PURPOSE = "$compact";
140
+ function isCompactionSummary(value) {
141
+ if (value === null || typeof value !== "object") return false;
142
+ return typeof value.summary === "string";
143
+ }
144
+ var compactionSummarySchema = schemaFromGuard(isCompactionSummary, "a CompactionSummary");
145
+
146
+ // src/agent/internal.ts
147
+ function freshConversation() {
148
+ return {
149
+ turns: [],
150
+ toolRecords: [],
151
+ turnCount: 0,
152
+ awaiting: { kind: "llm" }
153
+ };
154
+ }
155
+ function dedupeByCallId(calls) {
156
+ const seen = /* @__PURE__ */ new Set();
157
+ const out = [];
158
+ for (const call of calls) {
159
+ if (seen.has(call.callId)) continue;
160
+ seen.add(call.callId);
161
+ out.push(call);
162
+ }
163
+ return out;
164
+ }
165
+ function foldSummary(conv, folding, summaryTurn) {
166
+ const shift = folding - 1;
167
+ const survivingTurns = conv.turns.slice(folding);
168
+ const survivingRecords = conv.toolRecords.filter((rec) => rec.turn >= folding).map((rec) => ({ ...rec, turn: rec.turn - shift }));
169
+ return {
170
+ ...conv,
171
+ turns: [summaryTurn, ...survivingTurns],
172
+ toolRecords: survivingRecords,
173
+ awaiting: { kind: "llm" }
174
+ };
175
+ }
176
+ function currentStage(s) {
177
+ return s.run.stepStates.find((i) => i.status === "running")?.input;
178
+ }
179
+ function isSettled(s) {
180
+ return s.run.phase === "done" || s.run.phase === "failed" || s.run.phase === "cancelled" || s.failure !== null;
181
+ }
182
+ function requireAwaiting(s, kind) {
183
+ if (isSettled(s)) return null;
184
+ const conv = s.conversation;
185
+ if (conv === null || conv.awaiting.kind !== kind) return null;
186
+ return conv;
187
+ }
188
+ function toCompactRunCmd(cmd) {
189
+ return {
190
+ type: MsgType.CompactRun,
191
+ key: COMPACTION_PURPOSE,
192
+ input: cmd.input
193
+ };
194
+ }
195
+
196
+ // src/agent/machine.ts
197
+ function agentBootMsg(at) {
198
+ return { type: MsgType.AgentBoot, at };
199
+ }
200
+ function agentCancelMsg(at) {
201
+ return { type: MsgType.AgentCancel, at };
202
+ }
203
+ function agentEvents(opts) {
204
+ const tools = opts?.tools;
205
+ return (msg, state) => {
206
+ const events = [];
207
+ if (state.run.phase === "cancelled") return events;
208
+ const refused = new Set(state.refusedCalls ?? []);
209
+ const routed = tools === void 0 ? null : tools.outcomeOf(msg);
210
+ if (routed !== null) {
211
+ if (routed.outcome.kind === "ok" && !refused.has(routed.callId)) {
212
+ events.push({
213
+ type: "ToolSettled",
214
+ callId: routed.callId,
215
+ result: routed.outcome.result
216
+ });
217
+ }
218
+ } else {
219
+ projectOwn(msg, events, refused);
220
+ }
221
+ if (state.run.phase === "done") {
222
+ events.push({ type: "RunDone", output: state.output });
223
+ }
224
+ return events;
225
+ };
226
+ }
227
+ function projectOwn(msg, events, refused) {
228
+ switch (msg.type) {
229
+ case MsgType.ResilientOk:
230
+ events.push({ type: "TurnSettled", turn: msg.result.output });
231
+ break;
232
+ case MsgType.AgentToolOk:
233
+ if (!refused.has(msg.callId)) {
234
+ events.push({
235
+ type: "ToolSettled",
236
+ callId: msg.callId,
237
+ result: msg.result
238
+ });
239
+ }
240
+ break;
241
+ // start / boot / cancel / timer / the *_err arms / the compaction settles
242
+ // carry no public event. (No `default`: the switch is exhaustive over the Msg
243
+ // discriminant, so a new Msg variant forces a decision here at compile
244
+ // time.) Compaction is an internal optimization, not a semantic lifecycle
245
+ // moment a UI folds — its settles are deliberately silent here. Cancel is
246
+ // silent for a stronger reason: the run the caller stopped owes the public
247
+ // channel nothing after the stop, so a `RunCancelled` would be one more
248
+ // late thing to have to ignore.
249
+ case MsgType.AgentStart:
250
+ case MsgType.AgentCancel:
251
+ case MsgType.AgentToolErr:
252
+ case MsgType.ResilientErr:
253
+ case MsgType.CompactOk:
254
+ case MsgType.CompactErr:
255
+ case "deadline_exceeded":
256
+ case MsgType.AgentBoot:
257
+ break;
258
+ }
259
+ }
260
+ function mergeInterpret(a, b) {
261
+ return { ...a ?? {}, ...b };
262
+ }
263
+ function liftAgent(state, [slice, cmds]) {
264
+ return [{ ...state, agent: slice }, cmds];
265
+ }
266
+ var REJECTED_TYPE = "tool_rejected";
267
+ var SNAPSHOT_WRITE_TYPE = "snapshot_write";
268
+ var SETTLE_SUFFIX = /_(?:ok|err|run)$/;
269
+ var reservedToolNames = /* @__PURE__ */ new Set([
270
+ ...Object.values(MsgType),
271
+ ...Object.values(MsgType).flatMap((t) => {
272
+ const suffix = SETTLE_SUFFIX.exec(t);
273
+ return suffix === null ? [] : [t.slice(0, suffix.index)];
274
+ }),
275
+ REJECTED_TYPE,
276
+ SNAPSHOT_WRITE_TYPE
277
+ ]);
278
+ function isReservedToolName(name) {
279
+ return reservedToolNames.has(name);
280
+ }
281
+ function tool(name, spec, handler) {
282
+ if (isReservedToolName(name)) {
283
+ throw new Error(
284
+ `tool: "${name}" is reserved \u2014 it is an agent-owned Msg prefix`
285
+ );
286
+ }
287
+ const def = Cmd.define(name, {
288
+ input: z.object({
289
+ callId: z.string(),
290
+ args: spec.input
291
+ }),
292
+ ok: spec.ok,
293
+ err: [...spec.err, "thrown"],
294
+ requirements: spec.requirements
295
+ });
296
+ const declared = new Set(spec.err);
297
+ const settle = {
298
+ ok: (value) => Result.ok(value),
299
+ fail: (error) => Result.err(error)
300
+ };
301
+ const asDeclared = (thrown) => {
302
+ if (isTagged(thrown) && declared.has(thrown._tag)) return thrown;
303
+ return { _tag: "thrown", message: describeError(thrown) };
304
+ };
305
+ const interpret = async (cmd, ctx) => {
306
+ let result;
307
+ try {
308
+ result = await handler(cmd.args, ctx, settle);
309
+ } catch (thrown) {
310
+ return def.err(cmd, asDeclared(thrown));
311
+ }
312
+ return result.match({
313
+ ok: (value) => {
314
+ const parsed = spec.ok.safeParse(value);
315
+ return parsed.success ? def.ok(cmd, parsed.data) : {
316
+ type: def.errType,
317
+ cmd,
318
+ error: malformedResult(parsed.error.issues)
319
+ };
320
+ },
321
+ err: (error) => def.err(cmd, error)
322
+ });
323
+ };
324
+ return Object.assign(def, {
325
+ description: spec.description,
326
+ args: spec.input,
327
+ resilience: resilienceOf(spec),
328
+ interpret
329
+ });
330
+ }
331
+ function resilienceOf(spec) {
332
+ if (spec.timeoutMs === void 0 && spec.retry === void 0) return null;
333
+ return {
334
+ ...spec.timeoutMs !== void 0 ? { timeoutMs: spec.timeoutMs } : {},
335
+ ...spec.retry !== void 0 ? { retry: spec.retry } : {}
336
+ };
337
+ }
338
+ function isTagged(value) {
339
+ return typeof value === "object" && value !== null && typeof value._tag === "string";
340
+ }
341
+ var rejected = Cmd.define(REJECTED_TYPE, {
342
+ input: z.custom(
343
+ () => true
344
+ ),
345
+ ok: z.never(),
346
+ err: ["unknown_tool", "malformed_args"]
347
+ });
348
+ function toolRouter(tools) {
349
+ const byName = /* @__PURE__ */ new Map();
350
+ for (const t of tools) {
351
+ if (byName.has(t.cmdType)) {
352
+ throw new Error(`toolRouter: tool "${t.cmdType}" is declared twice`);
353
+ }
354
+ byName.set(t.cmdType, t);
355
+ }
356
+ const defs = [...tools, rejected];
357
+ const okTypes = new Map(defs.map((d) => [d.okType, d]));
358
+ const errTypes = new Map(defs.map((d) => [d.errType, d]));
359
+ const toolOf = (call) => {
360
+ const t = byName.get(call.name);
361
+ if (t === void 0) {
362
+ return rejected({
363
+ callId: call.callId,
364
+ error: { _tag: "unknown_tool", name: call.name }
365
+ });
366
+ }
367
+ const parsed = t.args.safeParse(call.args);
368
+ if (!parsed.success) {
369
+ return rejected({
370
+ callId: call.callId,
371
+ error: {
372
+ _tag: "malformed_args",
373
+ name: call.name,
374
+ issues: malformedResult(parsed.error.issues).issues
375
+ }
376
+ });
377
+ }
378
+ const build = t;
379
+ return build({ callId: call.callId, args: parsed.data });
380
+ };
381
+ const handlers = {
382
+ [rejected.cmdType]: async (cmd) => rejected.err(cmd, cmd.error)
383
+ };
384
+ for (const t of tools) handlers[t.cmdType] = t.interpret;
385
+ const interpret = handlers;
386
+ const outcomeOf = (msg) => {
387
+ if (okTypes.has(msg.type)) {
388
+ const ok = msg;
389
+ return {
390
+ callId: ok.cmd.callId,
391
+ outcome: { kind: "ok", result: ok.value }
392
+ };
393
+ }
394
+ if (errTypes.has(msg.type)) {
395
+ const err = msg;
396
+ return {
397
+ callId: err.cmd.callId,
398
+ // The tag and its payload spread FIRST, so `kind` and `reason` are
399
+ // written over anything a payload field of those names carries: the
400
+ // discriminant and the model's channel are the router's to state, and a
401
+ // tool that fails with `{ _tag, kind: "ok" }` must not be able to say
402
+ // otherwise.
403
+ outcome: {
404
+ ...err.error,
405
+ reason: toolErrorReason(err.error),
406
+ kind: "error"
407
+ }
408
+ };
409
+ }
410
+ return null;
411
+ };
412
+ const resilienceOf2 = (call) => byName.get(call.name)?.resilience ?? null;
413
+ return { defs, toolOf, interpret, outcomeOf, resilienceOf: resilienceOf2 };
414
+ }
415
+ function fanOutInterpret(interpret) {
416
+ let release = Promise.resolve();
417
+ const fanned = {};
418
+ for (const [type, cell] of Object.entries(
419
+ interpret
420
+ )) {
421
+ fanned[type] = async (cmd, ctx, dispatch) => {
422
+ const edge = cmdEdgeOf(ctx);
423
+ const detach = detachWorkOf(ctx);
424
+ const work = (async () => cell(cmd, ctx, dispatch))();
425
+ const prior = release;
426
+ const settled = work.then(async (follow) => {
427
+ await prior;
428
+ const msg = edge(cmd, follow);
429
+ if (msg === void 0 || msg === null) return;
430
+ dispatch?.(msg);
431
+ });
432
+ release = settled.then(swallow, swallow);
433
+ detach(settled);
434
+ return void 0;
435
+ };
436
+ }
437
+ return fanned;
438
+ }
439
+ function swallow() {
440
+ }
441
+ function toolErrorReason(error) {
442
+ const { _tag, ...detail } = error;
443
+ return Object.keys(detail).length === 0 ? _tag : `${_tag} ${JSON.stringify(detail)}`;
444
+ }
445
+
446
+ // src/agent/types.ts
447
+ function isStreamingModel(model) {
448
+ return model.length >= 2;
449
+ }
450
+ function isToolCall(value) {
451
+ if (value === null || typeof value !== "object") return false;
452
+ const t = value;
453
+ return typeof t.callId === "string" && typeof t.name === "string" && t.args !== null && typeof t.args === "object";
454
+ }
455
+ function isAgentTurn(value) {
456
+ if (value === null || typeof value !== "object") return false;
457
+ const t = value;
458
+ return typeof t.content === "string" && Array.isArray(t.toolCalls) && t.toolCalls.every(isToolCall);
459
+ }
460
+ var agentTurnSchema = schemaFromGuard(
461
+ isAgentTurn,
462
+ "an AgentTurn"
463
+ );
464
+ var TOOL_TIMEOUT_TAG = "timeout";
465
+ var TOOL_RETRY_EXHAUSTED_TAG = "retry_exhausted";
466
+ function status(s) {
467
+ if (s.failure !== null) {
468
+ return { kind: "failed", failure: s.failure };
469
+ }
470
+ const run2 = s.run;
471
+ switch (run2.phase) {
472
+ // 2) Never started — monitored-run's `idle` phase is exactly the "has this
473
+ // actually started?" guard, and the status channel keeps that distinction.
474
+ case "idle":
475
+ return { kind: "idle" };
476
+ // 3) The monitored-run terminal failure (deadline / stage). `run.failure`
477
+ // rides ONLY the `failed` arm of the discriminated union, so narrowing on
478
+ // `phase === "failed"` surfaces it with no nullable side field and no
479
+ // fabricated fallback — the old "failed-yet-failure-null" state is
480
+ // unrepresentable.
481
+ case "failed":
482
+ return { kind: "failed", failure: run2.failure };
483
+ // 4) The pipeline finished — the terminal output landed on `state.output`.
484
+ case "done":
485
+ return { kind: "done", output: s.output };
486
+ // 5) Stopped from outside. Terminal, and deliberately NOT folded into
487
+ // `failed`: the unified failure channel answers "what went wrong", and
488
+ // nothing did.
489
+ case "cancelled":
490
+ return { kind: "cancelled", at: run2.at };
491
+ // 6) Live. Awaiting tools is the resumable shape — the outstanding calls are
492
+ // the in-flight fan-out batch (`tools.running`); anything else is plain
493
+ // `running`, which is also where `stale` reads (a soft mark the next
494
+ // progress clears, not an outcome).
495
+ case "running":
496
+ case "stale":
497
+ return s.conversation !== null && s.conversation.awaiting.kind === "tools" ? { kind: "suspended", pending: s.tools.running } : { kind: "running" };
498
+ }
499
+ return absurd(run2);
500
+ }
501
+
502
+ // src/agent/tool-resilience.ts
503
+ var TOOL_KEY_PREFIX = "$tool:";
504
+ var NAME_CALL_SEP = "#";
505
+ function toolCallKey(name, callId) {
506
+ return `${TOOL_KEY_PREFIX}${name}${NAME_CALL_SEP}${callId}`;
507
+ }
508
+ function readToolCallKey(key) {
509
+ if (!key.startsWith(TOOL_KEY_PREFIX)) return null;
510
+ const body = key.slice(TOOL_KEY_PREFIX.length);
511
+ const at = body.indexOf(NAME_CALL_SEP);
512
+ if (at <= 0) return null;
513
+ return { name: body.slice(0, at), callId: body.slice(at + 1) };
514
+ }
515
+ function isToolTimerId(id) {
516
+ return keyOfTimerId(id) !== null;
517
+ }
518
+ function keyOfTimerId(id) {
519
+ for (const prefix of ["resilient:retry:", "resilient:deadline:"]) {
520
+ if (id.startsWith(prefix)) {
521
+ const key = id.slice(prefix.length);
522
+ return key.startsWith(TOOL_KEY_PREFIX) ? key : null;
523
+ }
524
+ }
525
+ return null;
526
+ }
527
+ function createToolLadder(resilienceOf2, toolOf, rng) {
528
+ const instances = /* @__PURE__ */ new Map();
529
+ function rcFor(call) {
530
+ const policy = resilienceOf2(call);
531
+ if (policy === null) return null;
532
+ if (policy.timeoutMs === void 0 && policy.retry === void 0) {
533
+ return null;
534
+ }
535
+ const cached = instances.get(call.name);
536
+ if (cached !== void 0) return cached;
537
+ const made = createResilientCall(
538
+ {
539
+ ...policy.retry !== void 0 ? { retry: policy.retry } : {},
540
+ ...policy.timeoutMs !== void 0 ? { deadline: { ms: policy.timeoutMs } } : {}
541
+ },
542
+ rng
543
+ );
544
+ instances.set(call.name, made);
545
+ return made;
546
+ }
547
+ function sliceOf(s, name, rc) {
548
+ return s[name] ?? rc.init();
549
+ }
550
+ function toLaunchCmds(runCmds) {
551
+ return runCmds.map((cmd) => toolOf(cmd.input));
552
+ }
553
+ const launch = (s, calls, at) => {
554
+ let next = s;
555
+ const cmds = [];
556
+ for (const call of calls) {
557
+ const rc = rcFor(call);
558
+ if (rc === null) {
559
+ cmds.push(toolOf(call));
560
+ continue;
561
+ }
562
+ const [slice, runCmds] = rc.attempt(
563
+ sliceOf(next, call.name, rc),
564
+ toolCallKey(call.name, call.callId),
565
+ call,
566
+ at
567
+ );
568
+ next = { ...next, [call.name]: slice };
569
+ cmds.push(...toLaunchCmds(runCmds));
570
+ }
571
+ return [next, cmds];
572
+ };
573
+ const ok = (s, call, at) => {
574
+ const rc = rcFor(call);
575
+ if (rc === null) return s;
576
+ const key = toolCallKey(call.name, call.callId);
577
+ const [slice] = rc.succeed(sliceOf(s, call.name, rc), key, {
578
+ type: MsgType.ResilientOk,
579
+ key,
580
+ result: null,
581
+ at
582
+ });
583
+ return { ...s, [call.name]: forget(slice, key) };
584
+ };
585
+ const err = (s, call, failure, at) => {
586
+ const rc = rcFor(call);
587
+ if (rc === null) return [s, failure];
588
+ const key = toolCallKey(call.name, call.callId);
589
+ const before = sliceOf(s, call.name, rc);
590
+ const [slice] = rc.fail(before, key, {
591
+ type: MsgType.ResilientErr,
592
+ key,
593
+ error: failure,
594
+ at
595
+ });
596
+ if (slice.calls[key]?.phase === "waiting_retry") {
597
+ return [{ ...s, [call.name]: slice }, null];
598
+ }
599
+ const attempts = before.retry[key]?.attempt;
600
+ const settled = resilienceOf2(call)?.retry === void 0 ? failure : exhaustedFailure((attempts ?? 0) + 1, failure);
601
+ return [{ ...s, [call.name]: forget(slice, key) }, settled];
602
+ };
603
+ const onTimer = (s, msg) => {
604
+ const key = keyOfTimerId(msg.id);
605
+ const parsed = key === null ? null : readToolCallKey(key);
606
+ if (key === null || parsed === null) return [s, { cmds: [], settle: [] }];
607
+ const slice = s[parsed.name];
608
+ if (slice === void 0) return [s, { cmds: [], settle: [] }];
609
+ const remembered = inputOf(slice, key);
610
+ const rc = remembered === null ? null : rcFor(remembered);
611
+ if (rc === null) return [s, { cmds: [], settle: [] }];
612
+ const [next, runCmds] = rc.onTimer(slice, msg);
613
+ const phase = next.calls[key];
614
+ if (phase?.phase === "failed" && isDeadline(phase.error)) {
615
+ return [
616
+ { ...s, [parsed.name]: forget(next, key) },
617
+ {
618
+ cmds: [],
619
+ settle: [{ callId: parsed.callId, failure: timeoutFailure() }]
620
+ }
621
+ ];
622
+ }
623
+ return [
624
+ { ...s, [parsed.name]: next },
625
+ { cmds: toLaunchCmds(runCmds), settle: [] }
626
+ ];
627
+ };
628
+ const boot = (s, calls, at) => {
629
+ let next = s;
630
+ const cmds = [];
631
+ const settle = [];
632
+ for (const call of calls) {
633
+ const rc = rcFor(call);
634
+ if (rc === null) {
635
+ cmds.push(toolOf(call));
636
+ continue;
637
+ }
638
+ const key = toolCallKey(call.name, call.callId);
639
+ next = {
640
+ ...next,
641
+ [call.name]: rc.resume(sliceOf(next, call.name, rc), at)
642
+ };
643
+ const phase = sliceOf(next, call.name, rc).calls[key]?.phase;
644
+ if (phase === "waiting_retry") continue;
645
+ const [slice, runCmds] = rc.attempt(
646
+ sliceOf(next, call.name, rc),
647
+ key,
648
+ call,
649
+ at
650
+ );
651
+ const settled = slice.calls[key];
652
+ if (settled?.phase === "failed" && isDeadline(settled.error)) {
653
+ next = { ...next, [call.name]: forget(slice, key) };
654
+ settle.push({ callId: call.callId, failure: timeoutFailure() });
655
+ continue;
656
+ }
657
+ next = { ...next, [call.name]: slice };
658
+ cmds.push(...toLaunchCmds(runCmds));
659
+ }
660
+ return [next, { cmds, settle }];
661
+ };
662
+ const subs = (s) => {
663
+ const out = [];
664
+ for (const slice of Object.values(s)) {
665
+ const sample = firstInput(slice);
666
+ const rc = sample === null ? null : rcFor(sample);
667
+ if (rc !== null) out.push(...rc.subs(slice));
668
+ }
669
+ return out;
670
+ };
671
+ return { init: () => ({}), launch, ok, err, onTimer, boot, subs };
672
+ }
673
+ function forget(s, key) {
674
+ const { [key]: _settled, ...calls } = s.calls;
675
+ const { [key]: _spent, ...retry } = s.retry;
676
+ return { ...s, calls, retry };
677
+ }
678
+ function inputOf(s, key) {
679
+ const call = s.calls[key];
680
+ if (call === void 0) return null;
681
+ return call.phase === "running" || call.phase === "waiting_retry" ? call.input : null;
682
+ }
683
+ function firstInput(s) {
684
+ for (const key of Object.keys(s.calls)) {
685
+ const input = inputOf(s, key);
686
+ if (input !== null) return input;
687
+ }
688
+ return null;
689
+ }
690
+ function isDeadline(error) {
691
+ return typeof error === "object" && error !== null && error._tag === "deadline_exceeded";
692
+ }
693
+ function exhaustedFailure(attempts, last) {
694
+ return taggedFailure({
695
+ _tag: TOOL_RETRY_EXHAUSTED_TAG,
696
+ attempts,
697
+ last: last.reason
698
+ });
699
+ }
700
+ function timeoutFailure() {
701
+ return taggedFailure({ _tag: TOOL_TIMEOUT_TAG });
702
+ }
703
+ function taggedFailure(tagged) {
704
+ return { ...tagged, reason: toolErrorReason(tagged), kind: "error" };
705
+ }
706
+
707
+ // src/agent/define-agent.ts
708
+ function defineAgent(config) {
709
+ const router = toolRouter(config.tools);
710
+ const { onToolError } = config;
711
+ const tools = onToolError === void 0 ? router : withToolErrorHook(router, onToolError);
712
+ return definedAgent(config, { router, tools }, []);
713
+ }
714
+ function definedAgent(config, wiring, overlays) {
715
+ const { router, tools } = wiring;
716
+ const { onToolError } = config;
717
+ const machineWith = (input, onChunk) => {
718
+ const brain = brainOf(config.model, onChunk);
719
+ const core = {
720
+ stages: [input],
721
+ turnOf: () => "act",
722
+ schemas: { act: agentTurnSchema },
723
+ model: brain,
724
+ instructions: config.instructions,
725
+ payloadOf: promptOf,
726
+ loadMessages: messagesOf,
727
+ toolOf: tools.toolOf,
728
+ // The per-tool timeout / retry knob (#117). The lid grows no option for
729
+ // it: the policy is declared on the `tool()` that needs it, and the
730
+ // router is what carries it down to the reducer that runs it.
731
+ toolResilienceOf: tools.resilienceOf,
732
+ // The BRAIN-call ladder (#146), which does grow one, because a bare
733
+ // `model` function has nowhere else to declare it. Forwarded only when
734
+ // set, so an omitted lid option leaves `AgentConfigCore.retry` unset
735
+ // and the brain call unbackedoff, byte for byte as before.
736
+ ...config.retry !== void 0 ? { retry: config.retry } : {},
737
+ // Forwarded only when set, for the same reason: an omitted knob leaves
738
+ // `AgentConfigCore.toolConcurrency` unset and the fan-out at its serial
739
+ // default.
740
+ ...config.toolConcurrency !== void 0 ? { toolConcurrency: config.toolConcurrency } : {},
741
+ maxTurns: config.maxTurns,
742
+ deadlineMs: config.deadlineMs,
743
+ maxElapsedMs: config.maxElapsedMs,
744
+ stopWhen: config.stopWhen
745
+ };
746
+ const compaction = config.compaction;
747
+ const agent = compaction === void 0 ? (
748
+ // The one assertion in the pair, and it widens the Cmd union rather
749
+ // than the interpret obligation: this machine's `AgentCmd` fixes
750
+ // compaction OFF, `DefinedAgentMachine` names the ON superset, and the
751
+ // gap is the `compact_run` Cmd a policy-less reducer provably never
752
+ // emits. Widening a union nothing can produce is sound; the reverse —
753
+ // claiming a cell that is not wired — is what the discriminant refuses.
754
+ createAgent(core).toMachine({
755
+ tools
756
+ })
757
+ ) : compactingMachine(core, compaction, brain, tools);
758
+ return overlaid(agent, overlays);
759
+ };
760
+ const machine = (input) => machineWith(input, void 0);
761
+ const drive = (input, ...[opts = noHost()]) => {
762
+ const { onEvent, onChunk } = opts;
763
+ const handle = run(machineWith(input, onChunk), {
764
+ ...opts,
765
+ terminal: isEnded,
766
+ events: onEvent === void 0 ? void 0 : agentEvents({
767
+ tools
768
+ })
769
+ });
770
+ if (onEvent !== void 0) forwardEvents(handle, onEvent);
771
+ if (onToolError !== void 0) {
772
+ forwardLadderErrors(handle, router, onToolError);
773
+ }
774
+ const clock = opts.clock ?? Date.now;
775
+ const begin = (booted) => {
776
+ const at = clock();
777
+ return isMidRun(booted) ? agentBootMsg(at) : startMsg(opts.runId ?? crypto.randomUUID(), at);
778
+ };
779
+ const signal = opts.signal;
780
+ if (signal === void 0) {
781
+ return ended(driveToDone(handle, begin, isEnded, { failed: isFailed }));
782
+ }
783
+ return ended(
784
+ driveToDone(handle, begin, isEnded, {
785
+ failed: isFailed,
786
+ signal,
787
+ cancel: () => agentCancelMsg(clock())
788
+ })
789
+ );
790
+ };
791
+ return {
792
+ machine,
793
+ run: drive,
794
+ with: (overlay) => definedAgent(config, wiring, [...overlays, overlay.interpret])
795
+ };
796
+ }
797
+ function overlaid(machine, overlays) {
798
+ if (overlays.length === 0) return machine;
799
+ const cells = { ...machine.interpret };
800
+ for (const overlay of overlays) {
801
+ const wrappers = overlay;
802
+ for (const [type, wrap] of Object.entries(wrappers)) {
803
+ const cell = cells[type];
804
+ if (cell === void 0) {
805
+ throw new Error(
806
+ `@demlik/tea: defineAgent(...).with named the interpret cell "${type}", which this agent's machine has none of. Its cells are: ${Object.keys(cells).sort().join(", ")}.`
807
+ );
808
+ }
809
+ cells[type] = wrap(cell);
810
+ }
811
+ }
812
+ return defineMachine({
813
+ ...machine,
814
+ interpret: cells
815
+ });
816
+ }
817
+ function brainOf(model, onChunk) {
818
+ if (!isStreamingModel(model)) {
819
+ return model;
820
+ }
821
+ const streaming = model;
822
+ const stream = {
823
+ onChunk: onChunk === void 0 ? dropChunk : contained("onChunk", onChunk)
824
+ };
825
+ return async (messages) => streaming(messages, stream);
826
+ }
827
+ function dropChunk() {
828
+ }
829
+ function contained(what, listener) {
830
+ return (event) => {
831
+ try {
832
+ listener(event);
833
+ } catch (err) {
834
+ console.warn(`@demlik/tea: a run's ${what} listener threw`, err);
835
+ }
836
+ };
837
+ }
838
+ function compactingMachine(core, knob, brain, tools) {
839
+ const agent = createAgent({ ...core, compaction: compactionPolicyOf(knob) });
840
+ const wiring = {
841
+ tools,
842
+ toolInterpret: { compact_run: summarizeWith(brain) }
843
+ };
844
+ return agent.toMachine(wiring);
845
+ }
846
+ var SUMMARIZE_INSTRUCTION = "Summarize the conversation so far. Preserve the facts, decisions and tool results a continuation would need, and drop everything else. Reply with the summary as your message content and request no tools.";
847
+ function compactionPolicyOf(knob) {
848
+ const keep = knob.keepTurns ?? 0;
849
+ return {
850
+ planCompaction: (conversation) => conversation.turns.length >= knob.afterTurns ? Math.max(0, conversation.turns.length - keep) : 0,
851
+ payloadOf: (conversation, folding) => ({
852
+ instructions: SUMMARIZE_INSTRUCTION,
853
+ input: null,
854
+ conversation: {
855
+ ...conversation,
856
+ turns: conversation.turns.slice(0, folding),
857
+ toolRecords: conversation.toolRecords.filter((r) => r.turn < folding)
858
+ }
859
+ })
860
+ };
861
+ }
862
+ function summarizeWith(model) {
863
+ return async (cmd) => {
864
+ const payload = cmd.input.payload;
865
+ const turn = await model(renderPrompt(payload));
866
+ return {
867
+ type: MsgType.CompactOk,
868
+ key: COMPACTION_PURPOSE,
869
+ result: {
870
+ key: COMPACTION_PURPOSE,
871
+ purpose: COMPACTION_PURPOSE,
872
+ output: { summary: turn.content }
873
+ },
874
+ at: Date.now()
875
+ };
876
+ };
877
+ }
878
+ function promptOf(stage, conversation, instructions) {
879
+ return { instructions, input: stage ?? null, conversation };
880
+ }
881
+ var messagesOf = async (call) => renderPrompt(call.payload);
882
+ function renderPrompt(prompt) {
883
+ const head = [];
884
+ if (prompt.instructions !== null) {
885
+ head.push({ role: "system", content: prompt.instructions });
886
+ }
887
+ if (prompt.input !== null) {
888
+ head.push({ role: "user", content: prompt.input });
889
+ }
890
+ const { turns, toolRecords } = prompt.conversation;
891
+ const transcript2 = turns.flatMap((turn, i) => [
892
+ assistantOf(turn),
893
+ ...toolRecords.filter((r) => r.turn === i).map((r) => ({
894
+ role: "tool",
895
+ callId: r.call.callId,
896
+ name: r.call.name,
897
+ outcome: r.outcome
898
+ }))
899
+ ]);
900
+ return [...head, ...transcript2];
901
+ }
902
+ function assistantOf(turn) {
903
+ const { content, toolCalls } = turn;
904
+ return "provider" in turn ? { role: "assistant", content, toolCalls, provider: turn.provider } : { role: "assistant", content, toolCalls };
905
+ }
906
+ function noHost() {
907
+ return {};
908
+ }
909
+ var AGENT_EVENT_TYPES = ["TurnSettled", "ToolSettled", "RunDone"];
910
+ function forwardEvents(handle, onEvent) {
911
+ const deliver = contained("onEvent", onEvent);
912
+ for (const type of AGENT_EVENT_TYPES) {
913
+ handle.on(type, deliver);
914
+ }
915
+ }
916
+ function forwardLadderErrors(handle, router, onToolError) {
917
+ const fired = /* @__PURE__ */ new Set();
918
+ handle.observe((msg, state) => {
919
+ const seeding = msg.type === MsgType.AgentStart || msg.type === MsgType.AgentBoot;
920
+ for (const record of state.conversation?.toolRecords ?? []) {
921
+ const { outcome, call } = record;
922
+ if (outcome.kind !== "error") continue;
923
+ if (fired.has(call.callId)) continue;
924
+ fired.add(call.callId);
925
+ if (seeding) continue;
926
+ if (router.resilienceOf(call) === null) continue;
927
+ void Promise.resolve(
928
+ onToolError(outcome, {
929
+ callId: call.callId,
930
+ name: call.name
931
+ })
932
+ ).catch((err) => {
933
+ console.warn("@demlik/tea: a run's onToolError hook threw", err);
934
+ });
935
+ }
936
+ });
937
+ }
938
+ function withToolErrorHook(router, onToolError) {
939
+ const handlers = router.interpret;
940
+ const wrapped = {};
941
+ for (const [type, handler] of Object.entries(handlers)) {
942
+ wrapped[type] = async (cmd, ctx) => {
943
+ const msg = await handler(cmd, ctx);
944
+ if (msg === void 0) return msg;
945
+ const settled = router.outcomeOf(msg);
946
+ if (settled === null || settled.outcome.kind === "ok") return msg;
947
+ if (ownedByLadder(router, cmd, settled.callId)) return msg;
948
+ try {
949
+ await onToolError(settled.outcome, {
950
+ callId: settled.callId,
951
+ name: calledName(cmd)
952
+ });
953
+ } catch (err) {
954
+ console.warn("@demlik/tea: a run's onToolError hook threw", err);
955
+ }
956
+ return msg;
957
+ };
958
+ }
959
+ return {
960
+ ...router,
961
+ interpret: wrapped
962
+ };
963
+ }
964
+ function ownedByLadder(router, cmd, callId) {
965
+ return router.resilienceOf({ name: cmd.type, callId, args: {} }) !== null;
966
+ }
967
+ function calledName(cmd) {
968
+ const rejection = cmd.error;
969
+ return typeof rejection?.name === "string" ? rejection.name : cmd.type;
970
+ }
971
+ function startMsg(runId, at) {
972
+ return { type: MsgType.AgentStart, runId, at };
973
+ }
974
+ function isMidRun(s) {
975
+ const { kind } = status(s);
976
+ return kind === "running" || kind === "suspended";
977
+ }
978
+ function isEnded(s) {
979
+ return s.run.phase === "done" || s.run.phase === "cancelled";
980
+ }
981
+ function ended(drive) {
982
+ return drive;
983
+ }
984
+ function isFailed(s) {
985
+ return status(s).kind === "failed";
986
+ }
987
+
988
+ // src/agent/transcript.ts
989
+ function transcript(seed) {
990
+ const turns = [...seed?.conversation?.turns ?? []];
991
+ const tools = (seed?.conversation?.toolRecords ?? []).flatMap(
992
+ (record) => record.outcome.kind === "ok" ? [{ callId: record.call.callId, result: record.outcome.result }] : []
993
+ );
994
+ let outcome = { kind: "running" };
995
+ return {
996
+ onEvent: (event) => {
997
+ switch (event.type) {
998
+ case "TurnSettled":
999
+ turns.push(event.turn);
1000
+ return;
1001
+ case "ToolSettled":
1002
+ tools.push({ callId: event.callId, result: event.result });
1003
+ return;
1004
+ case "RunDone":
1005
+ outcome = { kind: "done", output: event.output };
1006
+ return;
1007
+ }
1008
+ },
1009
+ read: () => ({ turns: [...turns], tools: [...tools], outcome })
1010
+ };
1011
+ }
1012
+
1013
+ // src/agent/index.ts
1014
+ function createAgent(config) {
1015
+ const rng = config.rng ?? Math.random;
1016
+ const run2 = createMonitoredRun({
1017
+ ...config.stages !== void 0 ? { stages: config.stages } : {},
1018
+ ...config.deadlineMs !== void 0 ? { deadlineMs: config.deadlineMs } : {},
1019
+ ...config.snapshotEvery !== void 0 ? { snapshotEvery: config.snapshotEvery } : {}
1020
+ });
1021
+ const llm = createLlmCall(
1022
+ {
1023
+ model: config.model,
1024
+ schemas: config.schemas,
1025
+ ...config.retry !== void 0 ? { retry: config.retry } : {},
1026
+ ...config.loadMessages !== void 0 ? { loadMessages: config.loadMessages } : {}
1027
+ },
1028
+ rng
1029
+ );
1030
+ const compactRc = createResilientCall({ ...config.retry !== void 0 ? { retry: config.retry } : {} }, rng);
1031
+ const fan = createFanOut({
1032
+ concurrency: config.toolConcurrency ?? 1,
1033
+ idOf: (call) => call.callId,
1034
+ of: (call) => config.toolOf(call)
1035
+ });
1036
+ const ladder = createToolLadder(
1037
+ config.toolResilienceOf ?? (() => null),
1038
+ config.toolOf,
1039
+ rng
1040
+ );
1041
+ function init() {
1042
+ return {
1043
+ run: run2.init(),
1044
+ resilience: llm.init(),
1045
+ tools: initFanOut(),
1046
+ conversation: null,
1047
+ compaction: compactRc.init(),
1048
+ toolResilience: ladder.init(),
1049
+ refusedCalls: [],
1050
+ failure: null,
1051
+ output: null,
1052
+ instructions: config.instructions ?? null
1053
+ };
1054
+ }
1055
+ function brainCall(s) {
1056
+ const stage = currentStage(s);
1057
+ const conversation = s.conversation ?? freshConversation();
1058
+ const instructions = s.instructions ?? null;
1059
+ return {
1060
+ purpose: config.turnOf(stage),
1061
+ model: config.modelId ?? null,
1062
+ payload: config.payloadOf ? config.payloadOf(stage, conversation, instructions) : null
1063
+ };
1064
+ }
1065
+ function fireBrainCall(s, at) {
1066
+ const call = brainCall(s);
1067
+ const [resilience, cmds] = llm.attempt(s.resilience, call, at);
1068
+ return [{ ...s, resilience }, cmds];
1069
+ }
1070
+ function compactionCall(conv, folding) {
1071
+ const payloadOf = config.compaction?.payloadOf;
1072
+ return {
1073
+ purpose: COMPACTION_PURPOSE,
1074
+ model: config.modelId ?? null,
1075
+ payload: payloadOf ? payloadOf(conv, folding) : null
1076
+ };
1077
+ }
1078
+ function reKeyCompactCmds(result) {
1079
+ const [slice, cmds] = result;
1080
+ return [slice, cmds.map(toCompactRunCmd)];
1081
+ }
1082
+ const compact = {
1083
+ attempt: (slice, key, input, at) => reKeyCompactCmds(compactRc.attempt(slice, key, input, at)),
1084
+ succeed: (slice, key, msg) => reKeyCompactCmds(compactRc.succeed(slice, key, msg)),
1085
+ fail: (slice, key, msg) => reKeyCompactCmds(compactRc.fail(slice, key, msg)),
1086
+ onTimer: (slice, msg) => reKeyCompactCmds(compactRc.onTimer(slice, msg))
1087
+ };
1088
+ function start(s, runId, at) {
1089
+ const [runSlice] = run2.start(s.run, runId, at);
1090
+ const conversation = freshConversation();
1091
+ const withRun = {
1092
+ ...s,
1093
+ run: runSlice,
1094
+ conversation,
1095
+ failure: null,
1096
+ // A restart clears the prior run's terminal output — `result()` reads
1097
+ // `undefined` again until THIS run finishes (#46).
1098
+ output: null,
1099
+ tools: initFanOut(),
1100
+ // A restart also clears any prior compaction slice — a fresh run never
1101
+ // inherits the previous run's summarize retry bookkeeping (#85).
1102
+ compaction: compactRc.init(),
1103
+ // …and the prior run's refusals: those `callId`s belong to a batch this
1104
+ // run will never settle, so carrying them would only grow the Model (#145).
1105
+ refusedCalls: []
1106
+ };
1107
+ return fireBrainCall(withRun, at);
1108
+ }
1109
+ function turn(s, result, at) {
1110
+ const conv = requireAwaiting(s, "llm");
1111
+ if (conv === null) return [s, []];
1112
+ const withTurn = {
1113
+ ...conv,
1114
+ turns: [...conv.turns, result]
1115
+ };
1116
+ if (result.toolCalls.length === 0) {
1117
+ return advanceStage({ ...s, conversation: withTurn }, result, at);
1118
+ }
1119
+ const batch = dedupeByCallId(result.toolCalls);
1120
+ const [tools] = fan.scatter(initFanOut(), batch);
1121
+ const nextConv = {
1122
+ ...withTurn,
1123
+ awaiting: { kind: "tools", batchTurn: withTurn.turnCount }
1124
+ };
1125
+ const [runSlice] = run2.progress(s.run, void 0, at);
1126
+ const [toolResilience, launchCmds] = armLaunch(s, [], tools.running, at);
1127
+ return [
1128
+ { ...s, run: runSlice, tools, toolResilience, conversation: nextConv },
1129
+ launchCmds
1130
+ ];
1131
+ }
1132
+ function advanceStage(s, terminatingTurn, at) {
1133
+ const [runSlice, runCmds] = run2.advance(
1134
+ s.run,
1135
+ void 0,
1136
+ { kind: "ok" },
1137
+ at
1138
+ );
1139
+ if (runSlice.phase === "done") {
1140
+ return [
1141
+ { ...s, run: runSlice, conversation: null, output: terminatingTurn },
1142
+ runCmds
1143
+ ];
1144
+ }
1145
+ const conversation = freshConversation();
1146
+ const moved = {
1147
+ ...s,
1148
+ run: runSlice,
1149
+ conversation,
1150
+ tools: initFanOut()
1151
+ };
1152
+ const [fired, llmCmds] = fireBrainCall(moved, at);
1153
+ return [fired, [...runCmds, ...llmCmds]];
1154
+ }
1155
+ function toolOk(s, callId, result, at) {
1156
+ const call = inFlight(s, callId);
1157
+ const laddered = call === null ? s : { ...s, toolResilience: ladder.ok(toolSlice(s), call, at) };
1158
+ return settleTool(laddered, callId, { kind: "ok", result }, at);
1159
+ }
1160
+ function toolErr(s, callId, reported, at) {
1161
+ const failure = typeof reported === "string" ? { kind: "error", reason: reported } : reported;
1162
+ const call = inFlight(s, callId);
1163
+ if (call === null) return settleTool(s, callId, failure, at);
1164
+ const [toolResilience, settled] = ladder.err(
1165
+ toolSlice(s),
1166
+ call,
1167
+ failure,
1168
+ at
1169
+ );
1170
+ const next = { ...s, toolResilience };
1171
+ if (settled === null) return [next, []];
1172
+ return settleTool(next, callId, settled, at);
1173
+ }
1174
+ function inFlight(s, callId) {
1175
+ return s.tools.running.find((c) => c.callId === callId) ?? null;
1176
+ }
1177
+ function toolSlice(s) {
1178
+ return s.toolResilience ?? {};
1179
+ }
1180
+ function refusedOf(s) {
1181
+ return s.refusedCalls ?? [];
1182
+ }
1183
+ function armLaunch(s, before, after, at) {
1184
+ const known = new Set(before.map((c) => c.callId));
1185
+ return ladder.launch(
1186
+ toolSlice(s),
1187
+ after.filter((c) => !known.has(c.callId)),
1188
+ at
1189
+ );
1190
+ }
1191
+ function settleTool(prev, callId, outcome, at) {
1192
+ const conv = requireAwaiting(prev, "tools");
1193
+ if (conv === null) return [prev, []];
1194
+ const call = prev.tools.running.find((c) => c.callId === callId);
1195
+ if (call === void 0) return [prev, []];
1196
+ const [tools] = outcome.kind === "ok" ? fan.itemOk(prev.tools, callId, outcome) : fan.itemErr(prev.tools, callId, outcome);
1197
+ const [toolResilience, launchCmds] = armLaunch(
1198
+ prev,
1199
+ prev.tools.running,
1200
+ tools.running,
1201
+ at
1202
+ );
1203
+ const refusedCalls = outcome.kind === "ok" ? refusedOf(prev) : [...refusedOf(prev), callId];
1204
+ const s = { ...prev, toolResilience, refusedCalls };
1205
+ const foldedConv = {
1206
+ ...conv,
1207
+ // Stamp the producing-turn index on the record (#85, A1). At settle time
1208
+ // `conv.turnCount` equals the index in `turns` of the turn that scattered
1209
+ // this batch (each prior drained batch bumped `turnCount` exactly once, and
1210
+ // each tool-bearing turn appended exactly one entry to `turns`), so a record
1211
+ // carrying `turn: conv.turnCount` is dropped iff its producing turn is folded
1212
+ // (`turn < N`) — the association the fold-back relies on.
1213
+ toolRecords: [
1214
+ ...conv.toolRecords,
1215
+ { call, outcome, turn: conv.turnCount }
1216
+ ]
1217
+ };
1218
+ if (!fan.isComplete(tools)) {
1219
+ const [runSlice2] = run2.progress(s.run, void 0, at);
1220
+ return [
1221
+ { ...s, run: runSlice2, tools, conversation: foldedConv },
1222
+ launchCmds
1223
+ ];
1224
+ }
1225
+ const turnedConv = {
1226
+ ...foldedConv,
1227
+ turnCount: foldedConv.turnCount + 1,
1228
+ awaiting: { kind: "llm" }
1229
+ };
1230
+ const turned = { ...s, tools, conversation: turnedConv };
1231
+ const stopped = stopConditions(turned, at);
1232
+ if (stopped !== null) return stopped;
1233
+ const drained = {
1234
+ ...turned,
1235
+ tools: initFanOut()
1236
+ };
1237
+ const compacting = maybeCompact(drained, at);
1238
+ if (compacting !== null) return compacting;
1239
+ const [runSlice] = run2.progress(drained.run, void 0, at);
1240
+ const [fired, llmCmds] = fireBrainCall({ ...drained, run: runSlice }, at);
1241
+ return [fired, [...launchCmds, ...llmCmds]];
1242
+ }
1243
+ function maybeCompact(s, at) {
1244
+ const policy = config.compaction;
1245
+ const conv = s.conversation;
1246
+ if (policy === void 0 || conv === null) return null;
1247
+ const requested = policy.planCompaction(conv);
1248
+ const folding = Math.min(requested, conv.turns.length);
1249
+ if (folding < 2) return null;
1250
+ const compactConv = {
1251
+ ...conv,
1252
+ awaiting: { kind: "compacting", folding }
1253
+ };
1254
+ const [runSlice] = run2.progress(s.run, void 0, at);
1255
+ const input = compactionCall(conv, folding);
1256
+ const [compaction, cmds] = compact.attempt(
1257
+ s.compaction,
1258
+ COMPACTION_PURPOSE,
1259
+ input,
1260
+ at
1261
+ );
1262
+ return [
1263
+ { ...s, run: runSlice, conversation: compactConv, compaction },
1264
+ cmds
1265
+ ];
1266
+ }
1267
+ function stopConditions(s, at) {
1268
+ const turnCount = s.conversation?.turnCount ?? 0;
1269
+ if (config.maxTurns !== void 0 && turnCount >= config.maxTurns) {
1270
+ return [{ ...s, failure: { reason: "turn_limit", at } }, []];
1271
+ }
1272
+ if (config.maxElapsedMs !== void 0 && at - s.run.startedAt >= config.maxElapsedMs) {
1273
+ return [{ ...s, failure: { reason: "elapsed_limit", at } }, []];
1274
+ }
1275
+ if (config.stopWhen?.(s) === true) return cancel(s, at);
1276
+ return null;
1277
+ }
1278
+ function succeed(s, key, msg, at) {
1279
+ const [resilience, retryCmds] = llm.succeed(s.resilience, key, msg);
1280
+ const settled = { ...s, resilience };
1281
+ const [withTurn, turnCmds] = turn(settled, msg.result.output, at);
1282
+ return [withTurn, [...retryCmds, ...turnCmds]];
1283
+ }
1284
+ function fail(s, key, msg, at) {
1285
+ const [resilience, cmds] = llm.fail(s.resilience, key, msg);
1286
+ const call = resilience.calls[key];
1287
+ const failure = call?.phase === "failed" ? { reason: "llm", error: msg.error, at } : s.failure;
1288
+ return [{ ...s, resilience, failure }, cmds];
1289
+ }
1290
+ function compactOk(s, key, msg, at) {
1291
+ const [compaction, retryCmds] = compact.succeed(s.compaction, key, {
1292
+ type: MsgType.ResilientOk,
1293
+ key: msg.key,
1294
+ result: msg.result,
1295
+ at: msg.at
1296
+ });
1297
+ const settledRetry = { ...s, compaction };
1298
+ const conv = requireAwaiting(settledRetry, "compacting");
1299
+ if (conv === null) return [settledRetry, retryCmds];
1300
+ const folding = conv.awaiting.folding;
1301
+ const summaryTurn = {
1302
+ content: msg.result.output.summary,
1303
+ toolCalls: []
1304
+ };
1305
+ const foldedConv = foldSummary(conv, folding, summaryTurn);
1306
+ const [fired, llmCmds] = fireBrainCall(
1307
+ { ...settledRetry, conversation: foldedConv },
1308
+ at
1309
+ );
1310
+ return [fired, [...retryCmds, ...llmCmds]];
1311
+ }
1312
+ function compactErr(s, key, msg, at) {
1313
+ const [compaction, cmds] = compact.fail(s.compaction, key, {
1314
+ type: MsgType.ResilientErr,
1315
+ key: msg.key,
1316
+ error: msg.error,
1317
+ at: msg.at
1318
+ });
1319
+ const settledRetry = { ...s, compaction };
1320
+ const call = compaction.calls[key];
1321
+ if (call?.phase === "waiting_retry") {
1322
+ return [settledRetry, cmds];
1323
+ }
1324
+ const conv = requireAwaiting(settledRetry, "compacting");
1325
+ if (conv === null) return [settledRetry, cmds];
1326
+ const resumedConv = { ...conv, awaiting: { kind: "llm" } };
1327
+ const [fired, llmCmds] = fireBrainCall(
1328
+ { ...settledRetry, conversation: resumedConv },
1329
+ at
1330
+ );
1331
+ return [fired, [...cmds, ...llmCmds]];
1332
+ }
1333
+ function onTimer(s, msg) {
1334
+ if (msg.id.startsWith("monitored:")) {
1335
+ const [runSlice] = run2.onDeadline(s.run, msg);
1336
+ return [{ ...s, run: runSlice }, []];
1337
+ }
1338
+ if (msg.id.endsWith(`:${COMPACTION_PURPOSE}`)) {
1339
+ const [compaction, cmds2] = compact.onTimer(s.compaction, msg);
1340
+ return [{ ...s, compaction }, cmds2];
1341
+ }
1342
+ if (isToolTimerId(msg.id)) return toolTimer(s, msg);
1343
+ const [resilience, cmds] = llm.onTimer(s.resilience, msg);
1344
+ return [{ ...s, resilience }, cmds];
1345
+ }
1346
+ function toolTimer(s, msg) {
1347
+ const [toolResilience, outcome] = ladder.onTimer(toolSlice(s), msg);
1348
+ return applyLadder(s, toolResilience, outcome, msg.atMs);
1349
+ }
1350
+ function applyLadder(s, toolResilience, outcome, at) {
1351
+ let next = { ...s, toolResilience };
1352
+ const cmds = [...outcome.cmds];
1353
+ for (const order of outcome.settle) {
1354
+ const [settled, more] = settleTool(next, order.callId, order.failure, at);
1355
+ next = settled;
1356
+ cmds.push(...more);
1357
+ }
1358
+ return [next, cmds];
1359
+ }
1360
+ function boot(s, at) {
1361
+ const [runSlice] = run2.boot(s.run, at);
1362
+ const rebooted = { ...s, run: runSlice };
1363
+ if (isSettled(rebooted)) return [rebooted, []];
1364
+ const conv = rebooted.conversation;
1365
+ if (conv === null) return [rebooted, []];
1366
+ if (conv.awaiting.kind === "llm") {
1367
+ return fireBrainCall(rebooted, at);
1368
+ }
1369
+ if (conv.awaiting.kind === "compacting") {
1370
+ const input = compactionCall(conv, conv.awaiting.folding);
1371
+ const [compaction, cmds] = compact.attempt(
1372
+ rebooted.compaction,
1373
+ COMPACTION_PURPOSE,
1374
+ input,
1375
+ at
1376
+ );
1377
+ return [{ ...rebooted, compaction }, cmds];
1378
+ }
1379
+ const [toolResilience, outcome] = ladder.boot(
1380
+ toolSlice(rebooted),
1381
+ rebooted.tools.running,
1382
+ at
1383
+ );
1384
+ return applyLadder(rebooted, toolResilience, outcome, at);
1385
+ }
1386
+ function cancel(s, at) {
1387
+ const [runSlice] = run2.cancel(s.run, at);
1388
+ return [{ ...s, run: runSlice }, []];
1389
+ }
1390
+ function subs(s) {
1391
+ return [
1392
+ ...llm.subs(s.resilience),
1393
+ ...compactRc.subs(s.compaction),
1394
+ ...ladder.subs(toolSlice(s)),
1395
+ ...run2.subs(s.run)
1396
+ ];
1397
+ }
1398
+ function unsafeDetachedHandlers(ports) {
1399
+ return llm.handlers(ports);
1400
+ }
1401
+ function brainHandlers() {
1402
+ return llm.handlers();
1403
+ }
1404
+ function toMachine(opts) {
1405
+ const tools = opts?.tools;
1406
+ const toolCellsInterpret = tools === void 0 ? void 0 : (config.toolConcurrency ?? 1) > 1 ? fanOutInterpret(tools.interpret) : tools.interpret;
1407
+ const consumerInterpret = {
1408
+ ...toolCellsInterpret,
1409
+ ...opts?.toolInterpret
1410
+ };
1411
+ const interpret = mergeInterpret(consumerInterpret, brainHandlers());
1412
+ const foldTool = (s, m) => {
1413
+ const settled = tools?.outcomeOf(m);
1414
+ if (settled === void 0 || settled === null) return [s, []];
1415
+ return settled.outcome.kind === "ok" ? toolOk(s, settled.callId, settled.outcome.result, m.at) : toolErr(s, settled.callId, settled.outcome, m.at);
1416
+ };
1417
+ const toolCells = {};
1418
+ for (const def of tools?.defs ?? []) {
1419
+ toolCells[def.okType] = foldTool;
1420
+ toolCells[def.errType] = foldTool;
1421
+ }
1422
+ const ownUpdate = {
1423
+ [MsgType.AgentStart]: (s, m) => start(s, m.runId, m.at),
1424
+ [MsgType.AgentToolOk]: (s, m) => toolOk(s, m.callId, m.result, m.at),
1425
+ // `agent_tool_err` is `createAgent`'s own raw settle Msg and its wire
1426
+ // shape is a bare `reason` string — a consumer routing their own interpret
1427
+ // through it never declared a tag, so the failure it mints carries none.
1428
+ [MsgType.AgentToolErr]: (s, m) => toolErr(s, m.callId, m.reason, m.at),
1429
+ // The re-entered brain-call settle Msgs (from `brainHandlers`): success
1430
+ // runs `succeed` (reset retry + fold the turn), failure runs `fail`.
1431
+ [MsgType.ResilientOk]: (s, m) => succeed(s, m.key, m, m.at),
1432
+ [MsgType.ResilientErr]: (s, m) => fail(s, m.key, m, m.at),
1433
+ // The re-entered compaction settle Msgs (from the consumer's `compact_run`
1434
+ // cell, #85): `compact_ok` folds the summary back (drop oldest turns +
1435
+ // their records, fire the next brain call), `compact_err` backs off via the
1436
+ // compaction retry or proceeds without compacting.
1437
+ [MsgType.CompactOk]: (s, m) => compactOk(s, m.key, m, m.at),
1438
+ [MsgType.CompactErr]: (s, m) => compactErr(s, m.key, m, m.at),
1439
+ deadline_exceeded: (s, m) => onTimer(s, m),
1440
+ [MsgType.AgentBoot]: (s, m) => boot(s, m.at),
1441
+ [MsgType.AgentCancel]: (s, m) => cancel(s, m.at)
1442
+ };
1443
+ const update = { ...ownUpdate, ...toolCells };
1444
+ const machine = {
1445
+ init: (loaded) => loaded !== null ? [loaded, []] : [init(), []],
1446
+ update,
1447
+ subscriptions: (s) => subs(s),
1448
+ subscribe: { deadline: subscribeDeadline },
1449
+ interpret,
1450
+ ...tools !== void 0 ? { cmds: tools.defs } : {}
1451
+ };
1452
+ return defineMachine(machine);
1453
+ }
1454
+ return {
1455
+ init,
1456
+ start,
1457
+ turn,
1458
+ toolOk,
1459
+ toolErr,
1460
+ succeed,
1461
+ fail,
1462
+ compactOk,
1463
+ compactErr,
1464
+ onTimer,
1465
+ boot,
1466
+ isSettled,
1467
+ currentStage,
1468
+ brainCall,
1469
+ subs,
1470
+ // `toMachine` is THE wired path. `unsafeDetachedHandlers` is the
1471
+ // hand-wiring escape hatch — named to advertise the retry-loop gap so it is
1472
+ // never mistaken for the loop driver (#54).
1473
+ toMachine,
1474
+ unsafeDetachedHandlers
1475
+ };
1476
+ }
1477
+
1478
+ export { COMPACTION_PURPOSE, PLAIN_MODEL_MISROUTE_REASON, TOOL_RETRY_EXHAUSTED_TAG, TOOL_TIMEOUT_TAG, agentBootMsg, agentCancelMsg, agentEvents, agentTurnSchema, compactionSummarySchema, createAgent, defineAgent, fanOutInterpret, isAgentTurn, isCompactionSummary, isReservedToolName, isStreamingModel, liftAgent, mergeInterpret, plainModel, renderPrompt, status, tool, toolErrorReason, toolRouter, transcript };
1479
+ //# sourceMappingURL=chunk-TCLBCERH.js.map
1480
+ //# sourceMappingURL=chunk-TCLBCERH.js.map