@mountaya/elements 0.0.0-stage → 0.2.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 (828) hide show
  1. package/CHANGELOG.md +273 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +1510 -2
  5. package/THIRD-PARTY-NOTICES.txt +103 -0
  6. package/dist/agent/index.cjs +1211 -0
  7. package/dist/agent/index.cjs.map +1 -0
  8. package/dist/agent/index.d.cts +1966 -0
  9. package/dist/agent/index.d.ts +1966 -0
  10. package/dist/agent/index.js +1181 -0
  11. package/dist/agent/index.js.map +1 -0
  12. package/dist/camera/index.cjs +2512 -0
  13. package/dist/camera/index.cjs.map +1 -0
  14. package/dist/camera/index.d.cts +1723 -0
  15. package/dist/camera/index.d.ts +1723 -0
  16. package/dist/camera/index.js +2443 -0
  17. package/dist/camera/index.js.map +1 -0
  18. package/dist/chunk-5pTPpv4v.d.cts +897 -0
  19. package/dist/chunk-5pTPpv4v.d.ts +897 -0
  20. package/dist/chunk-6JzFMFHh.d.ts +119 -0
  21. package/dist/chunk-6qyuJVvt.d.ts +513 -0
  22. package/dist/chunk-9fp0lDic.cjs +583 -0
  23. package/dist/chunk-9fp0lDic.cjs.map +1 -0
  24. package/dist/chunk-A48H1rDg.d.cts +73 -0
  25. package/dist/chunk-A48H1rDg.d.ts +73 -0
  26. package/dist/chunk-B-m1AchR.cjs +57 -0
  27. package/dist/chunk-B-m1AchR.cjs.map +1 -0
  28. package/dist/chunk-B-qFTf04.d.ts +216 -0
  29. package/dist/chunk-B0YROiZh.d.cts +1475 -0
  30. package/dist/chunk-B14wgOvH.d.cts +68 -0
  31. package/dist/chunk-B19l3j9r.cjs +150 -0
  32. package/dist/chunk-B19l3j9r.cjs.map +1 -0
  33. package/dist/chunk-B2PtjVKg.cjs +86 -0
  34. package/dist/chunk-B2PtjVKg.cjs.map +1 -0
  35. package/dist/chunk-B56Oyb7W.cjs +70 -0
  36. package/dist/chunk-B56Oyb7W.cjs.map +1 -0
  37. package/dist/chunk-B5WGMQwK.cjs +113 -0
  38. package/dist/chunk-B5WGMQwK.cjs.map +1 -0
  39. package/dist/chunk-B98mKrdu.d.cts +302 -0
  40. package/dist/chunk-BB0PmqIM.d.cts +44 -0
  41. package/dist/chunk-BBikve0Z.cjs +269 -0
  42. package/dist/chunk-BBikve0Z.cjs.map +1 -0
  43. package/dist/chunk-BHeXmM0X.js +37 -0
  44. package/dist/chunk-BHeXmM0X.js.map +1 -0
  45. package/dist/chunk-BI8WZLpU.cjs +281 -0
  46. package/dist/chunk-BI8WZLpU.cjs.map +1 -0
  47. package/dist/chunk-BIEc_SkR.cjs +29 -0
  48. package/dist/chunk-BIEc_SkR.cjs.map +1 -0
  49. package/dist/chunk-BJ6L6_W9.cjs +553 -0
  50. package/dist/chunk-BJ6L6_W9.cjs.map +1 -0
  51. package/dist/chunk-BJ91UCbB.js +11 -0
  52. package/dist/chunk-BJ91UCbB.js.map +1 -0
  53. package/dist/chunk-BJEZWTKj.cjs +166 -0
  54. package/dist/chunk-BJEZWTKj.cjs.map +1 -0
  55. package/dist/chunk-BJz54mfg.cjs +10 -0
  56. package/dist/chunk-BJz54mfg.cjs.map +1 -0
  57. package/dist/chunk-BNX5LAfN.d.cts +912 -0
  58. package/dist/chunk-BP6KgA86.js +35 -0
  59. package/dist/chunk-BP6KgA86.js.map +1 -0
  60. package/dist/chunk-BRnjQq6K.d.cts +157 -0
  61. package/dist/chunk-BSiMEwPS.js +46 -0
  62. package/dist/chunk-BSiMEwPS.js.map +1 -0
  63. package/dist/chunk-BTPjDw_y.cjs +16 -0
  64. package/dist/chunk-BTPjDw_y.cjs.map +1 -0
  65. package/dist/chunk-BTUUABGI.js +17 -0
  66. package/dist/chunk-BTUUABGI.js.map +1 -0
  67. package/dist/chunk-BUeL9y7s.cjs +45 -0
  68. package/dist/chunk-BUeL9y7s.cjs.map +1 -0
  69. package/dist/chunk-BWMuCNc9.cjs +172 -0
  70. package/dist/chunk-BWMuCNc9.cjs.map +1 -0
  71. package/dist/chunk-BWjRfhpF.js +126 -0
  72. package/dist/chunk-BWjRfhpF.js.map +1 -0
  73. package/dist/chunk-BZ5KyZXI.d.ts +302 -0
  74. package/dist/chunk-B_4SVmvh.js +94 -0
  75. package/dist/chunk-B_4SVmvh.js.map +1 -0
  76. package/dist/chunk-BcTUuZQ3.js +95 -0
  77. package/dist/chunk-BcTUuZQ3.js.map +1 -0
  78. package/dist/chunk-BdkqSsJe.cjs +140 -0
  79. package/dist/chunk-BdkqSsJe.cjs.map +1 -0
  80. package/dist/chunk-BfktMVmI.js +70 -0
  81. package/dist/chunk-BfktMVmI.js.map +1 -0
  82. package/dist/chunk-BfzQb0EK.cjs +6 -0
  83. package/dist/chunk-BhWfT-22.d.cts +808 -0
  84. package/dist/chunk-BjJcqX5J.cjs +60 -0
  85. package/dist/chunk-BjJcqX5J.cjs.map +1 -0
  86. package/dist/chunk-Bk0L8g5J.d.cts +77 -0
  87. package/dist/chunk-Bk0L8g5J.d.ts +77 -0
  88. package/dist/chunk-Bl4_uVa6.cjs +11 -0
  89. package/dist/chunk-Bl4_uVa6.cjs.map +1 -0
  90. package/dist/chunk-BlKF4lrp.js +43 -0
  91. package/dist/chunk-BlKF4lrp.js.map +1 -0
  92. package/dist/chunk-Bm1FieGR.js +4 -0
  93. package/dist/chunk-Bm1FieGR.js.map +1 -0
  94. package/dist/chunk-Bn6ZbxkS.cjs +27 -0
  95. package/dist/chunk-BpN3hr6a.cjs +541 -0
  96. package/dist/chunk-BpN3hr6a.cjs.map +1 -0
  97. package/dist/chunk-Bq_WHTfd.d.cts +119 -0
  98. package/dist/chunk-Bqt4LBBz.cjs +648 -0
  99. package/dist/chunk-Bqt4LBBz.cjs.map +1 -0
  100. package/dist/chunk-Bqt97zwf.d.cts +54 -0
  101. package/dist/chunk-Bqt97zwf.d.ts +54 -0
  102. package/dist/chunk-BsBiN4w6.d.cts +245 -0
  103. package/dist/chunk-BvTpOUoC.cjs +207 -0
  104. package/dist/chunk-BvTpOUoC.cjs.map +1 -0
  105. package/dist/chunk-BwK6Hl3q.cjs +446 -0
  106. package/dist/chunk-BwK6Hl3q.cjs.map +1 -0
  107. package/dist/chunk-BxDQZDXR.d.cts +76 -0
  108. package/dist/chunk-BxDQZDXR.d.ts +76 -0
  109. package/dist/chunk-BxUio8kX.js +20 -0
  110. package/dist/chunk-BxUio8kX.js.map +1 -0
  111. package/dist/chunk-BxaocpFi.d.cts +1 -0
  112. package/dist/chunk-Bywi0K1N.js +36 -0
  113. package/dist/chunk-Bywi0K1N.js.map +1 -0
  114. package/dist/chunk-C-IlmkDl.js +59 -0
  115. package/dist/chunk-C-IlmkDl.js.map +1 -0
  116. package/dist/chunk-C5PtVewq.d.ts +389 -0
  117. package/dist/chunk-C5dpC7mQ.js +19 -0
  118. package/dist/chunk-C5dpC7mQ.js.map +1 -0
  119. package/dist/chunk-C5q1sgSa.js +46 -0
  120. package/dist/chunk-C5q1sgSa.js.map +1 -0
  121. package/dist/chunk-C6fU9G5I.cjs +221 -0
  122. package/dist/chunk-C6fU9G5I.cjs.map +1 -0
  123. package/dist/chunk-C71dpWUK.js +5 -0
  124. package/dist/chunk-C71dpWUK.js.map +1 -0
  125. package/dist/chunk-C82N1gQX.d.ts +1831 -0
  126. package/dist/chunk-C8HdaHpu.js +118 -0
  127. package/dist/chunk-C8HdaHpu.js.map +1 -0
  128. package/dist/chunk-C8ZGryck.js +236 -0
  129. package/dist/chunk-C8ZGryck.js.map +1 -0
  130. package/dist/chunk-C95NG0oD.cjs +43 -0
  131. package/dist/chunk-C95NG0oD.cjs.map +1 -0
  132. package/dist/chunk-C9aR8DXb.js +9 -0
  133. package/dist/chunk-C9aR8DXb.js.map +1 -0
  134. package/dist/chunk-CAUZnoCs.d.ts +525 -0
  135. package/dist/chunk-CBXWWuM9.cjs +82 -0
  136. package/dist/chunk-CBXWWuM9.cjs.map +1 -0
  137. package/dist/chunk-CC_Kquu7.d.cts +125 -0
  138. package/dist/chunk-CC_Kquu7.d.ts +125 -0
  139. package/dist/chunk-CCp85vXg.cjs +60 -0
  140. package/dist/chunk-CCp85vXg.cjs.map +1 -0
  141. package/dist/chunk-CEcB1_uK.js +39 -0
  142. package/dist/chunk-CEcB1_uK.js.map +1 -0
  143. package/dist/chunk-CFIo021l.d.cts +216 -0
  144. package/dist/chunk-CH_IZoJE.js +33 -0
  145. package/dist/chunk-CH_IZoJE.js.map +1 -0
  146. package/dist/chunk-CHrasH_g.cjs +25 -0
  147. package/dist/chunk-CHrasH_g.cjs.map +1 -0
  148. package/dist/chunk-CJVoSaAE.cjs +3 -0
  149. package/dist/chunk-CJp8nGcb.js +96 -0
  150. package/dist/chunk-CJp8nGcb.js.map +1 -0
  151. package/dist/chunk-CJwUtkOt.js +112 -0
  152. package/dist/chunk-CJwUtkOt.js.map +1 -0
  153. package/dist/chunk-CKhCOVIf.d.cts +751 -0
  154. package/dist/chunk-CKiVSRYg.js +50 -0
  155. package/dist/chunk-CKiVSRYg.js.map +1 -0
  156. package/dist/chunk-CKtd19eD.cjs +59 -0
  157. package/dist/chunk-CKtd19eD.cjs.map +1 -0
  158. package/dist/chunk-CL92KE3j.d.ts +3188 -0
  159. package/dist/chunk-CLqUlkAe.js +54 -0
  160. package/dist/chunk-CLqUlkAe.js.map +1 -0
  161. package/dist/chunk-CMG5OV0q.cjs +4741 -0
  162. package/dist/chunk-CMG5OV0q.cjs.map +1 -0
  163. package/dist/chunk-CN_TKSgm.js +10 -0
  164. package/dist/chunk-CN_TKSgm.js.map +1 -0
  165. package/dist/chunk-CNe6MtqV.cjs +29 -0
  166. package/dist/chunk-CNe6MtqV.cjs.map +1 -0
  167. package/dist/chunk-COQkDTC5.js +83 -0
  168. package/dist/chunk-COQkDTC5.js.map +1 -0
  169. package/dist/chunk-CPBl6K4M.cjs +168 -0
  170. package/dist/chunk-CPBl6K4M.cjs.map +1 -0
  171. package/dist/chunk-CPx0ZYFB.d.ts +3 -0
  172. package/dist/chunk-CQQhcP_C.d.ts +197 -0
  173. package/dist/chunk-CTNoajFh.d.cts +389 -0
  174. package/dist/chunk-CTd-qgJc.cjs +384 -0
  175. package/dist/chunk-CTd-qgJc.cjs.map +1 -0
  176. package/dist/chunk-CW80YYtU.cjs +1056 -0
  177. package/dist/chunk-CW80YYtU.cjs.map +1 -0
  178. package/dist/chunk-CWpqBgkF.d.cts +24 -0
  179. package/dist/chunk-CWpqBgkF.d.ts +24 -0
  180. package/dist/chunk-CXjRArgy.d.ts +3 -0
  181. package/dist/chunk-CXonfH3-.cjs +14 -0
  182. package/dist/chunk-CXonfH3-.cjs.map +1 -0
  183. package/dist/chunk-CYcouGXN.d.ts +825 -0
  184. package/dist/chunk-CZDAzEBw.cjs +1621 -0
  185. package/dist/chunk-CZDAzEBw.cjs.map +1 -0
  186. package/dist/chunk-C_fQFr70.d.cts +159 -0
  187. package/dist/chunk-C_fQFr70.d.ts +159 -0
  188. package/dist/chunk-CbOtHnnB.cjs +359 -0
  189. package/dist/chunk-CbOtHnnB.cjs.map +1 -0
  190. package/dist/chunk-CdA6ZMGk.d.cts +825 -0
  191. package/dist/chunk-Ce1_thm7.js +146 -0
  192. package/dist/chunk-Ce1_thm7.js.map +1 -0
  193. package/dist/chunk-CeD8Hw0j.d.cts +3188 -0
  194. package/dist/chunk-CeiTuMyt.d.cts +525 -0
  195. package/dist/chunk-Ch1OLzLi.js +1 -0
  196. package/dist/chunk-Cizu_j1N.cjs +87 -0
  197. package/dist/chunk-Cizu_j1N.cjs.map +1 -0
  198. package/dist/chunk-CjDe9z6A.d.cts +427 -0
  199. package/dist/chunk-Cl1etdlu.js +63 -0
  200. package/dist/chunk-Cl1etdlu.js.map +1 -0
  201. package/dist/chunk-CmoVJDoz.js +4 -0
  202. package/dist/chunk-CmoVJDoz.js.map +1 -0
  203. package/dist/chunk-CnLucxjG.cjs +197 -0
  204. package/dist/chunk-CnLucxjG.cjs.map +1 -0
  205. package/dist/chunk-CsWjBmdi.cjs +56 -0
  206. package/dist/chunk-CsWjBmdi.cjs.map +1 -0
  207. package/dist/chunk-CuseO5MZ.d.cts +3 -0
  208. package/dist/chunk-CvMHibbA.d.ts +427 -0
  209. package/dist/chunk-CwDeiN5U.js +870 -0
  210. package/dist/chunk-CwDeiN5U.js.map +1 -0
  211. package/dist/chunk-Cwdmx4tG.js +1 -0
  212. package/dist/chunk-D-4MxHTt.d.cts +105 -0
  213. package/dist/chunk-D-4MxHTt.d.ts +105 -0
  214. package/dist/chunk-D0LF-99V.js +1093 -0
  215. package/dist/chunk-D0LF-99V.js.map +1 -0
  216. package/dist/chunk-D1fe-0c_.js +367 -0
  217. package/dist/chunk-D1fe-0c_.js.map +1 -0
  218. package/dist/chunk-D21fEI6A.d.ts +1926 -0
  219. package/dist/chunk-D39gAxya.cjs +89 -0
  220. package/dist/chunk-D39gAxya.cjs.map +1 -0
  221. package/dist/chunk-D6KdIW5e.cjs +228 -0
  222. package/dist/chunk-D6KdIW5e.cjs.map +1 -0
  223. package/dist/chunk-D6qHYbgW.d.cts +36 -0
  224. package/dist/chunk-D89E-w70.d.ts +44 -0
  225. package/dist/chunk-D8bdTysL.js +552 -0
  226. package/dist/chunk-D8bdTysL.js.map +1 -0
  227. package/dist/chunk-D96QJT24.cjs +109 -0
  228. package/dist/chunk-D96QJT24.cjs.map +1 -0
  229. package/dist/chunk-DAmkQl-i.js +119 -0
  230. package/dist/chunk-DAmkQl-i.js.map +1 -0
  231. package/dist/chunk-DEfsb2lc.cjs +10 -0
  232. package/dist/chunk-DEfsb2lc.cjs.map +1 -0
  233. package/dist/chunk-DIFjT5-V.d.cts +66 -0
  234. package/dist/chunk-DJpUw8TN.d.ts +912 -0
  235. package/dist/chunk-DK6lm2IZ.cjs +11 -0
  236. package/dist/chunk-DK6lm2IZ.cjs.map +1 -0
  237. package/dist/chunk-DKqgr31j.cjs +61 -0
  238. package/dist/chunk-DKqgr31j.cjs.map +1 -0
  239. package/dist/chunk-DLZ0QYm9.js +37 -0
  240. package/dist/chunk-DLZ0QYm9.js.map +1 -0
  241. package/dist/chunk-DLjS0uaC.js +4 -0
  242. package/dist/chunk-DLjS0uaC.js.map +1 -0
  243. package/dist/chunk-DMokwmOV.cjs +49 -0
  244. package/dist/chunk-DMokwmOV.cjs.map +1 -0
  245. package/dist/chunk-DMvWgBZL.d.cts +1831 -0
  246. package/dist/chunk-DNfGfIF3.js +31 -0
  247. package/dist/chunk-DNfGfIF3.js.map +1 -0
  248. package/dist/chunk-DQbSRe8D.d.ts +245 -0
  249. package/dist/chunk-DSGkP8_y.js +45 -0
  250. package/dist/chunk-DSGkP8_y.js.map +1 -0
  251. package/dist/chunk-DTctvfSd.d.cts +197 -0
  252. package/dist/chunk-DWe7igyw.cjs +206 -0
  253. package/dist/chunk-DWe7igyw.cjs.map +1 -0
  254. package/dist/chunk-DWsMP5JR.d.ts +68 -0
  255. package/dist/chunk-DWsm3HIW.d.cts +120 -0
  256. package/dist/chunk-DWsm3HIW.d.ts +120 -0
  257. package/dist/chunk-DXABHjLa.cjs +3 -0
  258. package/dist/chunk-D_BeqSbc.cjs +42 -0
  259. package/dist/chunk-D_BeqSbc.cjs.map +1 -0
  260. package/dist/chunk-D_svQNdW.d.ts +66 -0
  261. package/dist/chunk-Dav4xWrp.js +330 -0
  262. package/dist/chunk-Dav4xWrp.js.map +1 -0
  263. package/dist/chunk-DbCPhepL.js +293 -0
  264. package/dist/chunk-DbCPhepL.js.map +1 -0
  265. package/dist/chunk-DcrTy-y2.cjs +43 -0
  266. package/dist/chunk-DcrTy-y2.cjs.map +1 -0
  267. package/dist/chunk-Ddv484ld.js +487 -0
  268. package/dist/chunk-Ddv484ld.js.map +1 -0
  269. package/dist/chunk-De0bjnhY.cjs +88 -0
  270. package/dist/chunk-De0bjnhY.cjs.map +1 -0
  271. package/dist/chunk-De2FmNPu.cjs +32 -0
  272. package/dist/chunk-De2FmNPu.cjs.map +1 -0
  273. package/dist/chunk-DeSjQXiI.d.ts +157 -0
  274. package/dist/chunk-Den0Ta6C.js +132 -0
  275. package/dist/chunk-Den0Ta6C.js.map +1 -0
  276. package/dist/chunk-DiDKEeEa.js +8 -0
  277. package/dist/chunk-DiDKEeEa.js.map +1 -0
  278. package/dist/chunk-Dj60k5PU.js +197 -0
  279. package/dist/chunk-Dj60k5PU.js.map +1 -0
  280. package/dist/chunk-DjnYQBCN.js +4705 -0
  281. package/dist/chunk-DjnYQBCN.js.map +1 -0
  282. package/dist/chunk-Dk9VKvyq.d.ts +1 -0
  283. package/dist/chunk-Dor1ERI9.cjs +85 -0
  284. package/dist/chunk-Dor1ERI9.cjs.map +1 -0
  285. package/dist/chunk-DpMouOoH.js +451 -0
  286. package/dist/chunk-DpMouOoH.js.map +1 -0
  287. package/dist/chunk-DposgdNL.cjs +52 -0
  288. package/dist/chunk-DposgdNL.cjs.map +1 -0
  289. package/dist/chunk-DqLTG_5Q.d.cts +3 -0
  290. package/dist/chunk-Dr5MCIpS.d.cts +63 -0
  291. package/dist/chunk-Dr5MCIpS.d.ts +63 -0
  292. package/dist/chunk-DrudttCC.cjs +4 -0
  293. package/dist/chunk-DsDYVJQC.js +173 -0
  294. package/dist/chunk-DsDYVJQC.js.map +1 -0
  295. package/dist/chunk-Dw8ur6FJ.js +27 -0
  296. package/dist/chunk-Dw8ur6FJ.js.map +1 -0
  297. package/dist/chunk-DwG6M_0v.js +64 -0
  298. package/dist/chunk-DwG6M_0v.js.map +1 -0
  299. package/dist/chunk-Dy9a5ibO.js +284 -0
  300. package/dist/chunk-Dy9a5ibO.js.map +1 -0
  301. package/dist/chunk-DyayZlQJ.js +157 -0
  302. package/dist/chunk-DyayZlQJ.js.map +1 -0
  303. package/dist/chunk-DyhJZC2i.js +126 -0
  304. package/dist/chunk-DyhJZC2i.js.map +1 -0
  305. package/dist/chunk-F9zBzmmG.cjs +45 -0
  306. package/dist/chunk-F9zBzmmG.cjs.map +1 -0
  307. package/dist/chunk-FyCYofv2.js +116 -0
  308. package/dist/chunk-FyCYofv2.js.map +1 -0
  309. package/dist/chunk-GHJRjAk2.js +1 -0
  310. package/dist/chunk-H14isiSf.d.ts +751 -0
  311. package/dist/chunk-HIJzXoN4.js +7 -0
  312. package/dist/chunk-HIJzXoN4.js.map +1 -0
  313. package/dist/chunk-Id_8kRtu.d.ts +36 -0
  314. package/dist/chunk-KN60yxBQ.js +5 -0
  315. package/dist/chunk-KN60yxBQ.js.map +1 -0
  316. package/dist/chunk-NM5yg6bh.cjs +82 -0
  317. package/dist/chunk-NM5yg6bh.cjs.map +1 -0
  318. package/dist/chunk-OXr3zJfM.cjs +119 -0
  319. package/dist/chunk-OXr3zJfM.cjs.map +1 -0
  320. package/dist/chunk-QGqgNC4z.d.ts +928 -0
  321. package/dist/chunk-QJBtJrZ0.js +36 -0
  322. package/dist/chunk-QJBtJrZ0.js.map +1 -0
  323. package/dist/chunk-QKWhxfPv.d.cts +361 -0
  324. package/dist/chunk-QKWhxfPv.d.ts +361 -0
  325. package/dist/chunk-QXW7b4Ev.d.cts +410 -0
  326. package/dist/chunk-RHZrxUrM.cjs +39 -0
  327. package/dist/chunk-RHZrxUrM.cjs.map +1 -0
  328. package/dist/chunk-RTxe2i66.js +91 -0
  329. package/dist/chunk-RTxe2i66.js.map +1 -0
  330. package/dist/chunk-RrKkJb6P.js +16 -0
  331. package/dist/chunk-RrKkJb6P.js.map +1 -0
  332. package/dist/chunk-VOJqpcnM.cjs +181 -0
  333. package/dist/chunk-VOJqpcnM.cjs.map +1 -0
  334. package/dist/chunk-VljGTrid.js +1 -0
  335. package/dist/chunk-X3UVwUEK.d.cts +513 -0
  336. package/dist/chunk-X9K2WChn.cjs +28 -0
  337. package/dist/chunk-X9K2WChn.cjs.map +1 -0
  338. package/dist/chunk-YrtOx6oy.js +251 -0
  339. package/dist/chunk-YrtOx6oy.js.map +1 -0
  340. package/dist/chunk-bY7ySujI.d.cts +928 -0
  341. package/dist/chunk-bYf1sBz5.d.cts +11 -0
  342. package/dist/chunk-bYf1sBz5.d.ts +11 -0
  343. package/dist/chunk-blfknWoM.d.cts +1926 -0
  344. package/dist/chunk-blqsohAb.js +113 -0
  345. package/dist/chunk-blqsohAb.js.map +1 -0
  346. package/dist/chunk-cDMCjodI.cjs +58 -0
  347. package/dist/chunk-cDMCjodI.cjs.map +1 -0
  348. package/dist/chunk-cWjE3qd6.cjs +10 -0
  349. package/dist/chunk-cWjE3qd6.cjs.map +1 -0
  350. package/dist/chunk-dfOgV3fu.js +26 -0
  351. package/dist/chunk-dfOgV3fu.js.map +1 -0
  352. package/dist/chunk-f9cTwUX1.cjs +125 -0
  353. package/dist/chunk-f9cTwUX1.cjs.map +1 -0
  354. package/dist/chunk-fHVYEZs4.cjs +28 -0
  355. package/dist/chunk-fHVYEZs4.cjs.map +1 -0
  356. package/dist/chunk-fWRUMgRI.js +22 -0
  357. package/dist/chunk-fWRUMgRI.js.map +1 -0
  358. package/dist/chunk-fozLXfHY.d.cts +55 -0
  359. package/dist/chunk-fozLXfHY.d.ts +55 -0
  360. package/dist/chunk-gWmB1l3A.cjs +3122 -0
  361. package/dist/chunk-gWmB1l3A.cjs.map +1 -0
  362. package/dist/chunk-gbj2R-_w.js +58 -0
  363. package/dist/chunk-gbj2R-_w.js.map +1 -0
  364. package/dist/chunk-iIWxsAXd.js +59 -0
  365. package/dist/chunk-iIWxsAXd.js.map +1 -0
  366. package/dist/chunk-lItIuOIS.cjs +137 -0
  367. package/dist/chunk-lItIuOIS.cjs.map +1 -0
  368. package/dist/chunk-m6Rh4PCe.cjs +798 -0
  369. package/dist/chunk-m6Rh4PCe.cjs.map +1 -0
  370. package/dist/chunk-o3IRANDf.cjs +99 -0
  371. package/dist/chunk-o3IRANDf.cjs.map +1 -0
  372. package/dist/chunk-obUcg3Sk.d.ts +808 -0
  373. package/dist/chunk-ohsf-6Rn.js +600 -0
  374. package/dist/chunk-ohsf-6Rn.js.map +1 -0
  375. package/dist/chunk-pBleU6Nv.js +3061 -0
  376. package/dist/chunk-pBleU6Nv.js.map +1 -0
  377. package/dist/chunk-px4e99cy.js +71 -0
  378. package/dist/chunk-px4e99cy.js.map +1 -0
  379. package/dist/chunk-qwYDLeXc.cjs +99 -0
  380. package/dist/chunk-qwYDLeXc.cjs.map +1 -0
  381. package/dist/chunk-rF_859Qk.cjs +101 -0
  382. package/dist/chunk-rF_859Qk.cjs.map +1 -0
  383. package/dist/chunk-rLJkqJ5j.d.ts +1475 -0
  384. package/dist/chunk-twQItIRg.cjs +338 -0
  385. package/dist/chunk-twQItIRg.cjs.map +1 -0
  386. package/dist/chunk-vnPrMVjY.js +10 -0
  387. package/dist/chunk-vnPrMVjY.js.map +1 -0
  388. package/dist/chunk-ws3bVwaS.d.ts +410 -0
  389. package/dist/chunk-xh3UkuVs.cjs +246 -0
  390. package/dist/chunk-xh3UkuVs.cjs.map +1 -0
  391. package/dist/chunk-yMzRr26E.js +153 -0
  392. package/dist/chunk-yMzRr26E.js.map +1 -0
  393. package/dist/collab/index.cjs +831 -0
  394. package/dist/collab/index.cjs.map +1 -0
  395. package/dist/collab/index.d.cts +824 -0
  396. package/dist/collab/index.d.ts +824 -0
  397. package/dist/collab/index.js +819 -0
  398. package/dist/collab/index.js.map +1 -0
  399. package/dist/data/index.cjs +39 -0
  400. package/dist/data/index.d.cts +6 -0
  401. package/dist/data/index.d.ts +6 -0
  402. package/dist/data/index.js +7 -0
  403. package/dist/editor/index.cjs +2713 -0
  404. package/dist/editor/index.cjs.map +1 -0
  405. package/dist/editor/index.d.cts +10 -0
  406. package/dist/editor/index.d.ts +10 -0
  407. package/dist/editor/index.js +2702 -0
  408. package/dist/editor/index.js.map +1 -0
  409. package/dist/errors/index.cjs +11 -0
  410. package/dist/errors/index.d.cts +2 -0
  411. package/dist/errors/index.d.ts +2 -0
  412. package/dist/errors/index.js +1 -0
  413. package/dist/geo/index.cjs +68 -0
  414. package/dist/geo/index.d.cts +6 -0
  415. package/dist/geo/index.d.ts +6 -0
  416. package/dist/geo/index.js +11 -0
  417. package/dist/i18n/fr/index.cjs +333 -0
  418. package/dist/i18n/fr/index.cjs.map +1 -0
  419. package/dist/i18n/fr/index.d.cts +18 -0
  420. package/dist/i18n/fr/index.d.ts +18 -0
  421. package/dist/i18n/fr/index.js +328 -0
  422. package/dist/i18n/fr/index.js.map +1 -0
  423. package/dist/i18n/index.cjs +451 -0
  424. package/dist/i18n/index.cjs.map +1 -0
  425. package/dist/i18n/index.d.cts +268 -0
  426. package/dist/i18n/index.d.ts +268 -0
  427. package/dist/i18n/index.js +430 -0
  428. package/dist/i18n/index.js.map +1 -0
  429. package/dist/icons/index.cjs +37 -0
  430. package/dist/icons/index.d.cts +4 -0
  431. package/dist/icons/index.d.ts +4 -0
  432. package/dist/icons/index.js +8 -0
  433. package/dist/index.cjs +517 -0
  434. package/dist/index.cjs.map +1 -0
  435. package/dist/index.d.cts +174 -0
  436. package/dist/index.d.ts +174 -0
  437. package/dist/index.js +54 -0
  438. package/dist/index.js.map +1 -0
  439. package/dist/layers/index.cjs +83 -0
  440. package/dist/layers/index.d.cts +3 -0
  441. package/dist/layers/index.d.ts +3 -0
  442. package/dist/layers/index.js +5 -0
  443. package/dist/map-client/index.cjs +5 -0
  444. package/dist/map-client/index.d.cts +6 -0
  445. package/dist/map-client/index.d.ts +6 -0
  446. package/dist/map-client/index.js +0 -0
  447. package/dist/maplibre-worker.mjs +12 -0
  448. package/dist/navigation/index.cjs +612 -0
  449. package/dist/navigation/index.cjs.map +1 -0
  450. package/dist/navigation/index.d.cts +551 -0
  451. package/dist/navigation/index.d.ts +551 -0
  452. package/dist/navigation/index.js +599 -0
  453. package/dist/navigation/index.js.map +1 -0
  454. package/dist/profile/index.cjs +177 -0
  455. package/dist/profile/index.d.cts +8 -0
  456. package/dist/profile/index.d.ts +8 -0
  457. package/dist/profile/index.js +10 -0
  458. package/dist/seams/index.cjs +15 -0
  459. package/dist/seams/index.d.cts +4 -0
  460. package/dist/seams/index.d.ts +4 -0
  461. package/dist/seams/index.js +4 -0
  462. package/dist/search/index.cjs +39 -0
  463. package/dist/search/index.d.cts +6 -0
  464. package/dist/search/index.d.ts +6 -0
  465. package/dist/search/index.js +3 -0
  466. package/dist/style/index.cjs +34 -0
  467. package/dist/style/index.d.cts +5 -0
  468. package/dist/style/index.d.ts +5 -0
  469. package/dist/style/index.js +5 -0
  470. package/dist/styles.css +11 -0
  471. package/dist/testing/index.cjs +444 -0
  472. package/dist/testing/index.cjs.map +1 -0
  473. package/dist/testing/index.d.cts +217 -0
  474. package/dist/testing/index.d.ts +217 -0
  475. package/dist/testing/index.js +435 -0
  476. package/dist/testing/index.js.map +1 -0
  477. package/dist/timezone/index.cjs +1953 -0
  478. package/dist/timezone/index.cjs.map +1 -0
  479. package/dist/timezone/index.d.cts +28 -0
  480. package/dist/timezone/index.d.ts +28 -0
  481. package/dist/timezone/index.js +1948 -0
  482. package/dist/timezone/index.js.map +1 -0
  483. package/dist/units/index.cjs +29 -0
  484. package/dist/units/index.d.cts +3 -0
  485. package/dist/units/index.d.ts +3 -0
  486. package/dist/units/index.js +3 -0
  487. package/dist/video/index.cjs +1713 -0
  488. package/dist/video/index.cjs.map +1 -0
  489. package/dist/video/index.d.cts +846 -0
  490. package/dist/video/index.d.ts +846 -0
  491. package/dist/video/index.js +1689 -0
  492. package/dist/video/index.js.map +1 -0
  493. package/dist/view/index.cjs +7 -0
  494. package/dist/view/index.d.cts +3 -0
  495. package/dist/view/index.d.ts +3 -0
  496. package/dist/view/index.js +1 -0
  497. package/package.json +433 -4
  498. package/src/agent/engines/session.ts +2255 -0
  499. package/src/agent/index.ts +109 -0
  500. package/src/agent/rules/agentError.ts +128 -0
  501. package/src/agent/rules/boundedInputJson.ts +53 -0
  502. package/src/agent/rules/conversation.ts +629 -0
  503. package/src/agent/rules/conversationFaults.ts +349 -0
  504. package/src/agent/rules/conversationHost.ts +390 -0
  505. package/src/agent/rules/dispatcher.ts +102 -0
  506. package/src/agent/rules/errorCodes.ts +78 -0
  507. package/src/agent/rules/errorStatus.ts +65 -0
  508. package/src/agent/rules/scriptedTransport.ts +390 -0
  509. package/src/agent/rules/stickToBottom.ts +38 -0
  510. package/src/agent/rules/toolResultPayload.ts +197 -0
  511. package/src/auth/rules/clientHeader.ts +22 -0
  512. package/src/auth/rules/sentCredential.ts +76 -0
  513. package/src/auth/rules/transformRequest.ts +803 -0
  514. package/src/camera/engines/videoFlight.ts +1758 -0
  515. package/src/camera/index.ts +157 -0
  516. package/src/camera/rules/clearance.ts +1099 -0
  517. package/src/camera/rules/fit.ts +132 -0
  518. package/src/camera/rules/modes.ts +1019 -0
  519. package/src/camera/rules/plan.ts +478 -0
  520. package/src/camera/rules/planner.ts +129 -0
  521. package/src/camera/rules/poseRanges.ts +38 -0
  522. package/src/camera/rules/presets.ts +185 -0
  523. package/src/camera/rules/profileSamples.ts +243 -0
  524. package/src/camera/rules/route.ts +596 -0
  525. package/src/camera/rules/routeContent.ts +105 -0
  526. package/src/camera/rules/spline.ts +765 -0
  527. package/src/camera/rules/sweptViewports.ts +39 -0
  528. package/src/camera/rules/track.ts +1412 -0
  529. package/src/camera/rules/vocabulary.ts +130 -0
  530. package/src/camera/rules/zoom.ts +216 -0
  531. package/src/collab/engines/session.ts +1902 -0
  532. package/src/collab/engines/trailingThrottle.ts +151 -0
  533. package/src/collab/index.ts +52 -0
  534. package/src/collab/rules/dispatch.ts +143 -0
  535. package/src/collab/rules/peerNames.ts +51 -0
  536. package/src/collab/rules/scriptedTransport.ts +244 -0
  537. package/src/compose/engines/baseMapSwitch.ts +1136 -0
  538. package/src/compose/engines/events.ts +962 -0
  539. package/src/compose/engines/mountayaMap.ts +5648 -0
  540. package/src/compose/engines/sentCredentials.ts +146 -0
  541. package/src/compose/engines/slotRequests.ts +413 -0
  542. package/src/compose/rules/accessRefusal.ts +109 -0
  543. package/src/compose/rules/accessStanding.ts +75 -0
  544. package/src/compose/rules/analysisKinds.ts +331 -0
  545. package/src/compose/rules/analysisLayers.ts +176 -0
  546. package/src/compose/rules/cameraMoves.ts +38 -0
  547. package/src/compose/rules/carriedLayers.ts +87 -0
  548. package/src/compose/rules/developmentWarnings.ts +167 -0
  549. package/src/compose/rules/fitBox.ts +67 -0
  550. package/src/compose/rules/fitCamera.ts +54 -0
  551. package/src/compose/rules/geoJsonSlot.ts +61 -0
  552. package/src/compose/rules/geometrySlots.ts +155 -0
  553. package/src/compose/rules/glyphNode.ts +62 -0
  554. package/src/compose/rules/layerKeys.ts +92 -0
  555. package/src/compose/rules/layerOrder.ts +85 -0
  556. package/src/compose/rules/layersManifest.ts +26 -0
  557. package/src/compose/rules/mapOptions.ts +300 -0
  558. package/src/compose/rules/maplibreWorkerVersion.gen.ts +8 -0
  559. package/src/compose/rules/markerPin.ts +122 -0
  560. package/src/compose/rules/markerRegistry.ts +85 -0
  561. package/src/compose/rules/markerSprite.ts +382 -0
  562. package/src/compose/rules/maxBounds.ts +120 -0
  563. package/src/compose/rules/overlayLookup.ts +49 -0
  564. package/src/compose/rules/paintDiff.ts +38 -0
  565. package/src/compose/rules/panLock.ts +77 -0
  566. package/src/compose/rules/patch.ts +124 -0
  567. package/src/compose/rules/queriedFeature.ts +55 -0
  568. package/src/compose/rules/queryLayers.ts +46 -0
  569. package/src/compose/rules/searchHighlight.ts +313 -0
  570. package/src/compose/rules/slotNames.ts +19 -0
  571. package/src/compose/rules/stripeImage.ts +253 -0
  572. package/src/compose/rules/swapMarker.ts +66 -0
  573. package/src/compose/rules/terrainVariant.ts +88 -0
  574. package/src/compose/rules/types.ts +559 -0
  575. package/src/compose/rules/urlHash.ts +19 -0
  576. package/src/compose/rules/viewOptions.ts +451 -0
  577. package/src/compose/rules/workerUrl.ts +131 -0
  578. package/src/data/engines/itineraryResource.ts +643 -0
  579. package/src/data/index.ts +78 -0
  580. package/src/data/rules/adapt.ts +473 -0
  581. package/src/data/rules/editModes.ts +51 -0
  582. package/src/data/rules/itinerary.ts +168 -0
  583. package/src/data/rules/nullable.ts +63 -0
  584. package/src/data/rules/roadAccess.ts +169 -0
  585. package/src/data/rules/segmentGroups.ts +309 -0
  586. package/src/data/rules/selectors.ts +95 -0
  587. package/src/data/rules/zones.ts +79 -0
  588. package/src/draw/engines/boundaryEngine.ts +1003 -0
  589. package/src/draw/engines/framedAdapter.ts +198 -0
  590. package/src/draw/engines/pointerCursor.ts +205 -0
  591. package/src/draw/engines/segmentEngine.ts +1405 -0
  592. package/src/draw/engines/snapIndex.ts +254 -0
  593. package/src/draw/engines/waypointEngine.ts +574 -0
  594. package/src/draw/engines/zoneEngine.ts +1137 -0
  595. package/src/draw/rules/drawFrame.ts +123 -0
  596. package/src/draw/rules/insertVertex.ts +226 -0
  597. package/src/draw/rules/screenSpace.ts +62 -0
  598. package/src/draw/rules/seeds.ts +185 -0
  599. package/src/draw/rules/snap.ts +115 -0
  600. package/src/draw/rules/snapCameraKey.ts +50 -0
  601. package/src/draw/rules/terraDrawShared.ts +214 -0
  602. package/src/draw/rules/zoneOutline.ts +213 -0
  603. package/src/editing/engines/cursor.ts +505 -0
  604. package/src/editing/engines/draftMarker.ts +149 -0
  605. package/src/editing/rules/accent.ts +11 -0
  606. package/src/editing/rules/engine.ts +288 -0
  607. package/src/editing/rules/placement.ts +22 -0
  608. package/src/editing/rules/positions.ts +89 -0
  609. package/src/editing/rules/sources.ts +9 -0
  610. package/src/editing/rules/types.ts +457 -0
  611. package/src/editing/rules/vocabulary.ts +10 -0
  612. package/src/editing/rules/waypointCursor.ts +228 -0
  613. package/src/editor/engines/directionArrows.ts +459 -0
  614. package/src/editor/engines/directions.ts +1383 -0
  615. package/src/editor/engines/editorClient.ts +134 -0
  616. package/src/editor/engines/eventScope.ts +59 -0
  617. package/src/editor/engines/frameLoop.ts +159 -0
  618. package/src/editor/engines/itineraryPreview.ts +272 -0
  619. package/src/editor/engines/mapLockGuard.ts +66 -0
  620. package/src/editor/engines/overlayRenderer.ts +2696 -0
  621. package/src/editor/engines/peerDraft.ts +760 -0
  622. package/src/editor/engines/poiPick.ts +305 -0
  623. package/src/editor/engines/pointPick.ts +84 -0
  624. package/src/editor/engines/roadAccessLine.ts +140 -0
  625. package/src/editor/engines/searchHighlight.ts +183 -0
  626. package/src/editor/engines/viewClient.ts +4091 -0
  627. package/src/editor/engines/zoneBadges.ts +503 -0
  628. package/src/editor/index.ts +97 -0
  629. package/src/editor/rules/accentColor.ts +116 -0
  630. package/src/editor/rules/camera.ts +121 -0
  631. package/src/editor/rules/contract.ts +120 -0
  632. package/src/editor/rules/icons.ts +825 -0
  633. package/src/editor/rules/markerElements.ts +244 -0
  634. package/src/editor/rules/style.ts +51 -0
  635. package/src/editor/rules/terrain.ts +98 -0
  636. package/src/editor/rules/tileWarm.ts +191 -0
  637. package/src/editor/rules/tilesReload.ts +158 -0
  638. package/src/editor/rules/zoneBadgePlacement.ts +1832 -0
  639. package/src/editor/rules/zoneTimeStyling.ts +119 -0
  640. package/src/errors/index.ts +25 -0
  641. package/src/errors/rules/errors.ts +158 -0
  642. package/src/errors/rules/print.ts +129 -0
  643. package/src/geo/index.ts +89 -0
  644. package/src/geo/rules/boundaries.ts +105 -0
  645. package/src/geo/rules/camera.ts +496 -0
  646. package/src/geo/rules/corridor.ts +242 -0
  647. package/src/geo/rules/elevationTiles.ts +269 -0
  648. package/src/geo/rules/formatLngLat.ts +63 -0
  649. package/src/geo/rules/geodesy.ts +125 -0
  650. package/src/geo/rules/geometry.ts +362 -0
  651. package/src/geo/rules/lineWalk.ts +77 -0
  652. package/src/geo/rules/longitude.ts +99 -0
  653. package/src/geo/rules/searchLimits.ts +22 -0
  654. package/src/geo/rules/segmentGeometry.ts +80 -0
  655. package/src/geo/rules/terrain.ts +107 -0
  656. package/src/geo/rules/tuples.ts +124 -0
  657. package/src/geo/rules/types.ts +54 -0
  658. package/src/geo/rules/webMercator.ts +57 -0
  659. package/src/i18n/fr/index.ts +17 -0
  660. package/src/i18n/fr/rules/fr.ts +85 -0
  661. package/src/i18n/fr/rules/words.gen.ts +277 -0
  662. package/src/i18n/index.ts +82 -0
  663. package/src/i18n/rules/bundle.ts +378 -0
  664. package/src/i18n/rules/config.ts +71 -0
  665. package/src/i18n/rules/dates.ts +165 -0
  666. package/src/i18n/rules/endonyms.gen.ts +19 -0
  667. package/src/i18n/rules/language.ts +92 -0
  668. package/src/i18n/rules/localizedName.ts +33 -0
  669. package/src/i18n/rules/merge.ts +106 -0
  670. package/src/i18n/rules/scope.ts +127 -0
  671. package/src/i18n/rules/strings.ts +632 -0
  672. package/src/i18n/rules/videoOverlay.ts +121 -0
  673. package/src/i18n/rules/wordForms.ts +95 -0
  674. package/src/i18n/rules/words.gen.ts +277 -0
  675. package/src/icons/index.ts +54 -0
  676. package/src/icons/rules/activities.ts +40 -0
  677. package/src/icons/rules/amenities.ts +250 -0
  678. package/src/icons/rules/artwork.gen.ts +83 -0
  679. package/src/icons/rules/artwork.ts +47 -0
  680. package/src/icons/rules/fallback.ts +21 -0
  681. package/src/icons/rules/lucideMarkers.gen.ts +112 -0
  682. package/src/icons/rules/lucideUi.gen.ts +197 -0
  683. package/src/icons/rules/paint.ts +107 -0
  684. package/src/icons/rules/parse.ts +475 -0
  685. package/src/icons/rules/provider.ts +373 -0
  686. package/src/icons/rules/sprites.ts +54 -0
  687. package/src/icons/rules/ui.ts +348 -0
  688. package/src/icons/rules/waypoints.ts +215 -0
  689. package/src/index.ts +993 -0
  690. package/src/layers/engines/layersSelection.ts +515 -0
  691. package/src/layers/engines/readoutEngine.ts +131 -0
  692. package/src/layers/index.ts +151 -0
  693. package/src/layers/rules/analysis.ts +135 -0
  694. package/src/layers/rules/enrichment.ts +30 -0
  695. package/src/layers/rules/geoJson.ts +270 -0
  696. package/src/layers/rules/hover.ts +67 -0
  697. package/src/layers/rules/itineraries.ts +182 -0
  698. package/src/layers/rules/layersPanel.ts +237 -0
  699. package/src/layers/rules/order.ts +194 -0
  700. package/src/layers/rules/overlayInstant.ts +49 -0
  701. package/src/layers/rules/overlays.ts +52 -0
  702. package/src/layers/rules/poiPanel.ts +119 -0
  703. package/src/layers/rules/pois.ts +114 -0
  704. package/src/layers/rules/readout.ts +340 -0
  705. package/src/layers/rules/streetView.ts +16 -0
  706. package/src/layers/rules/tileTimestamp.ts +146 -0
  707. package/src/layers/rules/timeSlider.ts +192 -0
  708. package/src/layers/rules/timeWindow.ts +123 -0
  709. package/src/layers/rules/zones.ts +43 -0
  710. package/src/layers/rules/zoom.ts +77 -0
  711. package/src/map-client/index.ts +71 -0
  712. package/src/map-client/rules/mapClient.ts +1945 -0
  713. package/src/navigation/engines/navigation.ts +493 -0
  714. package/src/navigation/index.ts +51 -0
  715. package/src/navigation/rules/followedRoute.ts +78 -0
  716. package/src/navigation/rules/instructions.ts +89 -0
  717. package/src/navigation/rules/itineraryRoute.ts +232 -0
  718. package/src/navigation/rules/offRoute.ts +41 -0
  719. package/src/navigation/rules/progress.ts +230 -0
  720. package/src/navigation/rules/prompts.ts +217 -0
  721. package/src/navigation/rules/routeRequest.ts +98 -0
  722. package/src/navigation/rules/status.ts +142 -0
  723. package/src/navigation/rules/steps.ts +234 -0
  724. package/src/navigation/rules/types.ts +83 -0
  725. package/src/profile/index.ts +307 -0
  726. package/src/profile/rules/amenityBadge.ts +35 -0
  727. package/src/profile/rules/amenityFilter.ts +74 -0
  728. package/src/profile/rules/amenityStacks.ts +66 -0
  729. package/src/profile/rules/axis.ts +89 -0
  730. package/src/profile/rules/axisCulling.ts +83 -0
  731. package/src/profile/rules/axisLookup.ts +180 -0
  732. package/src/profile/rules/climbs.ts +292 -0
  733. package/src/profile/rules/cursorMarker.ts +122 -0
  734. package/src/profile/rules/cursorReadout.ts +104 -0
  735. package/src/profile/rules/curvePlacement.ts +216 -0
  736. package/src/profile/rules/dock.ts +293 -0
  737. package/src/profile/rules/elevation.ts +1263 -0
  738. package/src/profile/rules/instant.ts +89 -0
  739. package/src/profile/rules/intl.ts +237 -0
  740. package/src/profile/rules/legEmphasis.ts +53 -0
  741. package/src/profile/rules/profileColors.ts +66 -0
  742. package/src/profile/rules/profileLayout.ts +59 -0
  743. package/src/profile/rules/profileSlices.ts +55 -0
  744. package/src/profile/rules/routeProfile.ts +475 -0
  745. package/src/profile/rules/rowMatch.ts +50 -0
  746. package/src/profile/rules/scale.ts +646 -0
  747. package/src/profile/rules/scaleFrame.ts +171 -0
  748. package/src/profile/rules/sectionChips.ts +83 -0
  749. package/src/profile/rules/sections.ts +923 -0
  750. package/src/profile/rules/slopeRamp.ts +160 -0
  751. package/src/profile/rules/statStrip.ts +103 -0
  752. package/src/profile/rules/steepness.ts +51 -0
  753. package/src/profile/rules/tableCells.ts +269 -0
  754. package/src/profile/rules/tableCursor.ts +87 -0
  755. package/src/profile/rules/unitPatterns.ts +335 -0
  756. package/src/profile/rules/units.ts +1025 -0
  757. package/src/profile/rules/waypointCard.ts +590 -0
  758. package/src/profile/rules/webAddress.ts +130 -0
  759. package/src/profile/rules/windowSpans.ts +65 -0
  760. package/src/rules/asciiFold.ts +17 -0
  761. package/src/rules/inDevelopment.ts +54 -0
  762. package/src/rules/listeners.ts +62 -0
  763. package/src/rules/timers.ts +9 -0
  764. package/src/rules/types.ts +22 -0
  765. package/src/rules/uuid.ts +87 -0
  766. package/src/seams/engines/geolocateControl.ts +286 -0
  767. package/src/seams/index.ts +50 -0
  768. package/src/seams/rules/clock.ts +169 -0
  769. package/src/seams/rules/geolocation.ts +165 -0
  770. package/src/seams/rules/segmentRoute.ts +187 -0
  771. package/src/search/engines/search.ts +1093 -0
  772. package/src/search/index.ts +99 -0
  773. package/src/search/rules/describe.ts +383 -0
  774. package/src/search/rules/filters.ts +195 -0
  775. package/src/search/rules/highlight.ts +270 -0
  776. package/src/search/rules/pick.ts +90 -0
  777. package/src/search/rules/rows.ts +258 -0
  778. package/src/search/rules/searchFocus.ts +27 -0
  779. package/src/search/rules/searchViewport.ts +44 -0
  780. package/src/search/rules/shown.ts +77 -0
  781. package/src/search/rules/types.ts +340 -0
  782. package/src/stream/rules/reconnectSchedule.ts +83 -0
  783. package/src/style/engines/organizationRead.ts +80 -0
  784. package/src/style/index.ts +63 -0
  785. package/src/style/rules/apply.ts +268 -0
  786. package/src/style/rules/attribution.ts +119 -0
  787. package/src/style/rules/itineraryLine.ts +142 -0
  788. package/src/style/rules/language.ts +668 -0
  789. package/src/style/rules/layout.gen.ts +27 -0
  790. package/src/style/rules/organization.ts +96 -0
  791. package/src/style/rules/paint.ts +143 -0
  792. package/src/style/rules/panelLayout.ts +51 -0
  793. package/src/style/rules/roadAccessColors.ts +29 -0
  794. package/src/style/rules/roadAccessLine.ts +267 -0
  795. package/src/style/rules/segmentColors.ts +207 -0
  796. package/src/testing/catalogs.ts +103 -0
  797. package/src/testing/index.ts +30 -0
  798. package/src/testing/mapClient.ts +241 -0
  799. package/src/testing/mountayaMap.ts +741 -0
  800. package/src/timezone/index.ts +14 -0
  801. package/src/timezone/rules/viewport.ts +875 -0
  802. package/src/units/index.ts +55 -0
  803. package/src/units/rules/conversions.ts +620 -0
  804. package/src/units/rules/preferenceChoices.ts +124 -0
  805. package/src/units/rules/preferences.ts +77 -0
  806. package/src/units/rules/rounding.ts +69 -0
  807. package/src/video/engines/videoRun.ts +654 -0
  808. package/src/video/engines/viewClient.ts +6 -0
  809. package/src/video/index.ts +83 -0
  810. package/src/video/profileOverlay/rules/contract.ts +210 -0
  811. package/src/video/profileOverlay/rules/curve.ts +216 -0
  812. package/src/video/profileOverlay/rules/draw.ts +410 -0
  813. package/src/video/profileOverlay/rules/fonts.ts +54 -0
  814. package/src/video/profileOverlay/rules/graphDesign.ts +690 -0
  815. package/src/video/profileOverlay/rules/minimalDesign.ts +144 -0
  816. package/src/video/profileOverlay/rules/registry.ts +23 -0
  817. package/src/video/profileOverlay/rules/staticLayer.ts +582 -0
  818. package/src/video/profileOverlay/rules/stripDesign.ts +327 -0
  819. package/src/video/profileOverlay/rules/types.ts +78 -0
  820. package/src/video/rules/videoConstants.ts +250 -0
  821. package/src/video/rules/videoEncoder.ts +277 -0
  822. package/src/video/rules/videoFrames.ts +99 -0
  823. package/src/video/rules/videoPreview.ts +185 -0
  824. package/src/video/rules/videoRecorder.ts +746 -0
  825. package/src/video/rules/videoWatermark.ts +155 -0
  826. package/src/video/rules/watermarkMark.ts +40 -0
  827. package/src/view/engines/viewClient.ts +6 -0
  828. package/src/view/index.ts +20 -0
@@ -0,0 +1,2255 @@
1
+ /**
2
+ * Driving one co-pilot run from open to settled.
3
+ *
4
+ * The engine owns the stream and nothing else owns any of it: it opens the run's event stream,
5
+ * folds every frame into the conversation, dispatches the client tools that arrive on it,
6
+ * resumes after a drop from the last event id, backs off when an open is unproductive, and
7
+ * tears down exactly what it stood up.
8
+ *
9
+ * **It is not the collaboration session wearing a different name, and the two are deliberately
10
+ * not one engine.** They look alike from a distance (both open a stream, resume it, back off
11
+ * and dispose), and the halves that genuinely ARE shared already are: `@mountaya/client/events`
12
+ * publishes the reader, the frame decoding and the event types, which both sides import rather
13
+ * than restate, and both draw the wait before a reopen through `reconnectDelayMs`
14
+ * (`stream/rules/reconnectSchedule.ts`), full jitter below a ceiling that doubles. What is left is
15
+ * POLICY, and the policies disagree on every number and on the rule behind each one, because one
16
+ * has a person waiting on it and the other does not.
17
+ *
18
+ * Here: a ceiling that doubles to 8 seconds, and six attempts, because someone is sitting in
19
+ * front of the run: it must never spend a minute asleep, and it must stop rather than re-open a
20
+ * stream nothing can revive for as long as the tab is open. A reconnect is judged by whether the
21
+ * open was PRODUCTIVE, since a gateway that says one thing and hangs up delivers a frame every
22
+ * time. A read that fails reopens only when the next open can outlive the failure: a dropped
23
+ * connection, a 429, a 503 or a 504. A run the provider's rate limit already ended is answered
24
+ * 409, which every reopen would meet again, and a 502 is never reopened either. The 503 is the
25
+ * one failure the six attempts do not count: it says the run's events cannot be reached for a
26
+ * moment while the run goes on, so its opens are held to two minutes, which is still a bound.
27
+ *
28
+ * There: a ceiling that doubles from half a second to 15 seconds, and no attempt limit, because a
29
+ * collaboration feed is background and a persistently-unreachable endpoint should keep trying at
30
+ * a steady rate; and a stream that delivered more than the frames every open begins with
31
+ * reconnects with NO delay, so a healthy feed the API cycles between windows resumes promptly.
32
+ *
33
+ * A shared core beyond the draw would have to be parameterised by the ceiling, the growth seed,
34
+ * the attempt limit, the productivity rule and the resume key, which is every line that differs,
35
+ * and would leave behind two configuration objects and one indirection for the few lines of a read
36
+ * loop the two files have in common.
37
+ */
38
+
39
+ import type {
40
+ AgentClientToolManifest,
41
+ AgentRunCreateParams,
42
+ AgentRunProfile,
43
+ AgentRunReason,
44
+ } from "@mountaya/client";
45
+ import type {
46
+ AgentEvent,
47
+ AgentInput,
48
+ AgentStreamHandlers,
49
+ AgentTransport,
50
+ } from "@mountaya/client/events";
51
+
52
+ import { MountayaElementsError } from "../../errors/rules/errors.js";
53
+ import { surfaceFault } from "../../rules/listeners.js";
54
+ import { randomUuid } from "../../rules/uuid.js";
55
+ import {
56
+ type ReconnectSchedule,
57
+ reconnectDelayMs,
58
+ retryAfterDelayMs,
59
+ } from "../../stream/rules/reconnectSchedule.js";
60
+ import type {
61
+ AgentToolContext,
62
+ RecoveryLookup,
63
+ StateDelta,
64
+ ToolDispatcher,
65
+ ToolManifestEntry,
66
+ } from "../rules/dispatcher.js";
67
+ import { toWireErrorCode } from "../rules/errorCodes.js";
68
+ import { retryAfterMsOf, statusOf } from "../rules/errorStatus.js";
69
+ import { buildToolResultPayload } from "../rules/toolResultPayload.js";
70
+
71
+ /**
72
+ * ServerToolConfirmation describes a destructive SERVER tool the gateway asks to
73
+ * run: the run identifies it by name alone (a server tool has no client-side
74
+ * schema, so there is no input to show, and the event carries no prose of its
75
+ * own). The host gate turns the name into its own localized approval prompt, which
76
+ * is why this stays decoupled from the bus's client-tool ConfirmationRequest.
77
+ */
78
+ export interface ServerToolConfirmation {
79
+ name: string;
80
+ }
81
+
82
+ /**
83
+ * ToolActivityOutcome is how a tool call settled, delivered through
84
+ * {@link AgentObserver.onToolResult} so the host can settle the activity row it
85
+ * appended for the call: `ok` with an optional human `summary` of what the tool
86
+ * did, `error` with the failure text, or `abandoned` when the call was given up on
87
+ * (the user declined a client tool's confirmation, or the run moved on without an
88
+ * answer to the call). It mirrors both the bus result of a client tool and the
89
+ * stream's `tool-result` / `tool-abandoned` event, so one settle path covers a call
90
+ * the host recorded and one it never saw a call for.
91
+ */
92
+ export interface ToolActivityOutcome {
93
+ error?: string | undefined;
94
+ /**
95
+ * Why an abandoned call was given up on: `timeout` when nothing came back within
96
+ * the await window, `closed` when the run was asked to finish while the call was
97
+ * still outstanding. Absent on any other status, and on a gateway that does not
98
+ * send one.
99
+ */
100
+ abandonedReason?: "timeout" | "closed" | undefined;
101
+ /**
102
+ * What the run will try about this failure, from the tool's playbook entry.
103
+ * Present only on a failure the playbook has guidance for. The run already sends
104
+ * this to the model; surfacing it to the host too is what stops a silent retry
105
+ * reading as a stall.
106
+ */
107
+ recovery?: string | undefined;
108
+ status: "abandoned" | "error" | "ok";
109
+ summary?: string | undefined;
110
+ }
111
+
112
+ /**
113
+ * AgentObserver is the host's window onto a running session. The engine pushes
114
+ * streamed text and lifecycle signals out through it; the host renders them,
115
+ * deferring the non-urgent text so input stays responsive. The engine itself
116
+ * renders nothing and touches no store: every UI effect goes through the bus.
117
+ *
118
+ * A callback answers nothing the run waits on, so one that throws stops neither the
119
+ * read nor the frame it was handed: its fault reaches the program as an uncaught error
120
+ * on a microtask. A throw from a seam that answers (the tool layer, the confirm gate,
121
+ * the tool surface, the state delta) ends the read instead.
122
+ */
123
+ export interface AgentObserver {
124
+ /**
125
+ * onError surfaces an error or budget-exhausted event so the host can show it.
126
+ * `code` is the machine-readable reason every run error carries (e.g.
127
+ * `rate-limited`), or the literal `budget-exhausted` for a budget ceiling, in
128
+ * which case `message` carries the exhausted dimension (`turns` / `cost`) rather
129
+ * than a human string. It is absent only for a fault the engine raises itself,
130
+ * such as a tool result it could not post, whose message is empty. This lets the
131
+ * host map a known code to specific copy (a budget code to per-dimension
132
+ * usage-limit copy) and fall back to a generic message otherwise.
133
+ *
134
+ * It never ends the run. The gateway publishes an `error` or a `budget-exhausted` only
135
+ * as the run ends and always follows it with the terminal `done`, which is what ends the
136
+ * run and reaches {@link onRunEnd}.
137
+ */
138
+ onError?: ((message: string, code?: string) => void) | undefined;
139
+ /**
140
+ * onRunEnd reports how a run ended, read off its terminal `done` frame: `completed`,
141
+ * `closed`, `failed`, `budget-exhausted`, `rate-limited` or `looping`. It fires at most
142
+ * once per read of a run, which one {@link AgentEngine.start} or {@link AgentEngine.resume}
143
+ * makes, before `onStateChange("ended")`. A resume that reads the `done` of a run already
144
+ * read to its end reports it again: one by an engine that holds no position for the run,
145
+ * which is answered with the run's history, or one given a position before the `done`.
146
+ *
147
+ * Only `done` knows the reason, so a read that ends any other way reports none: a
148
+ * {@link AgentEngine.close} or {@link AgentEngine.dispose}, a start or a resume that
149
+ * replaces the run, and a stream the engine stopped reconnecting to without a `done`.
150
+ * Optional: a host that needs only the `ended`
151
+ * state omits it.
152
+ */
153
+ onRunEnd?: ((reason: AgentRunReason) => void) | undefined;
154
+ /**
155
+ * onChecksUnmet reports the success criteria a run's retrieved skills promised
156
+ * that the workspace does not back, published by the run right before it settles
157
+ * into awaiting_input. Informational, never terminal: the answer stands and the
158
+ * user decides. The sentences are the authored criteria, written for the user.
159
+ * Optional: a host that does not render the warning omits it.
160
+ */
161
+ onChecksUnmet?: ((unmet: readonly string[]) => void) | undefined;
162
+ /**
163
+ * onMessage delivers a complete assistant message (the turn's settled text) with
164
+ * the message's zero-based position among the run's assistant messages.
165
+ *
166
+ * The index is the number a rating on this message has to carry back, and it comes
167
+ * from the run because a host cannot work it out. A host counts the replies it is
168
+ * showing, and a reload mid-run leaves it showing none (the URL carries the thread
169
+ * and run ids, not the conversation), so a locally counted index restarts at zero
170
+ * while the run's is already higher, and every rating from then on names an earlier
171
+ * answer than the one that was rated.
172
+ *
173
+ * It is undefined for a message from a gateway that sends no index, in which case
174
+ * the host falls back to its own count for that message alone.
175
+ */
176
+ onMessage?: ((content: string, messageIndex?: number) => void) | undefined;
177
+ /** onMessageDelta delivers one streamed assistant token as it arrives. */
178
+ onMessageDelta?: ((text: string) => void) | undefined;
179
+ /**
180
+ * onRunId reports the run's id the moment start/resume sets it, so the host can
181
+ * persist it (e.g. into the URL) for a reload to reconnect.
182
+ */
183
+ onRunId?: ((runId: string) => void) | undefined;
184
+ /** onStateChange reports the session's lifecycle transitions to the host. */
185
+ onStateChange?: ((state: AgentEngineState) => void) | undefined;
186
+ /**
187
+ * onToolActivity surfaces what the run is doing right now so the host can show
188
+ * a live activity line. The session emits the dispatched CLIENT tool's name as
189
+ * it begins, then the tool's result summary (when the bus returns one) as it
190
+ * settles, so the line tracks the action from start to finish. Optional: a host
191
+ * that does not render activity omits it.
192
+ */
193
+ onToolActivity?: ((summary: string) => void) | undefined;
194
+ /**
195
+ * onToolCall delivers a client tool call's name, its raw unvalidated input, and
196
+ * the call's id the moment the run emits it: the structured twin of
197
+ * {@link onToolActivity}, which carries only the human display string. A host reads
198
+ * this to react to WHAT the tool will touch (deriving the workspace target an edit is
199
+ * about to lock from the input) and to record the call as a durable activity row
200
+ * keyed by its id, which {@link onToolResult} later settles. The display line
201
+ * cannot carry the structured input or the id. Fires before the bus dispatch,
202
+ * alongside onToolActivity. Optional: a host that renders only the activity line
203
+ * omits it.
204
+ */
205
+ onToolCall?: ((name: string, input: unknown, toolCallId: string) => void) | undefined;
206
+ /**
207
+ * onToolResult reports how a tool call settled, keyed by its call id, so a host
208
+ * that recorded the call through onToolCall can settle that activity row. A CLIENT
209
+ * tool call the engine ran is reported once, from the bus result as the dispatch
210
+ * returns. Every other call is reported from the `tool-result` or `tool-abandoned`
211
+ * event the stream carries for it: a SERVER tool's outcome, a call the run gave up
212
+ * on, and the outcome replayed behind a call the stream marks `settled`. Optional:
213
+ * a host that renders only the activity line omits it.
214
+ *
215
+ * The stream names a call the engine ran a second time: the gateway echoes the
216
+ * answer the engine posted as a `tool-result`, and a `tool-abandoned` can cross an
217
+ * answer that came late. For a call it reported, the engine drops both whole, in the
218
+ * read that ran the call and in every later read of the run, so the bus result is the
219
+ * one report. An echo says less than the bus did: it carries no summary, and it words
220
+ * a confirmation the user declined as an error. A call whose handling threw before the
221
+ * report (the tool layer, or one of the host's seams) has no report of the engine's,
222
+ * so what the stream says about it is delivered. What the stream says of a call while its
223
+ * tool still runs, in a read a {@link AgentEngine.resume} opened beside it, is held until
224
+ * the tool settles: the bus result is then the one report, and the first thing the stream
225
+ * said is delivered only when the handling throws.
226
+ *
227
+ * The id may be one the host never saw a call for, which the host settles by
228
+ * appending an already-settled row: a server tool's, which emits no call event, or
229
+ * a call the stream marks settled, whose `tool-call` frame the engine drops before
230
+ * it reports the outcome replayed behind it. The id may also be one already reported: a failed
231
+ * `tool-result` follows the `tool-abandoned` of a confirmation nobody decided, and
232
+ * a resumed stream replays an outcome. The first report is the one to keep, which
233
+ * is what `settleActivityEntry` does.
234
+ */
235
+ onToolResult?: ((toolCallId: string, outcome: ToolActivityOutcome) => void) | undefined;
236
+ }
237
+
238
+ /**
239
+ * AgentEngineState is the session lifecycle the host renders against: it is
240
+ * `running` from the message that opens a turn (a start or a send, at the call)
241
+ * until the turn settles, `awaiting_input` once the turn settles and the
242
+ * run is ready for the next user message (multi-turn), and `ended` after a
243
+ * terminal event. A message that does not reach its run (a start that fails, a send
244
+ * whose post fails with no other message on its way and no frame since) returns the
245
+ * engine to `awaiting_input`. Held as a string union (Zod is unnecessary: this value never
246
+ * crosses a runtime boundary). It is the engine's own vocabulary rather than the
247
+ * contract's, so `awaiting_input` keeps its spelling where the event that leads to it
248
+ * is `awaiting-input`.
249
+ */
250
+ export type AgentEngineState = "running" | "awaiting_input" | "ended";
251
+
252
+ /**
253
+ * AgentStreamPosition is where an engine stands in the event stream of a run: the run, and the
254
+ * last position its stream named.
255
+ *
256
+ * {@link AgentEngine.streamPosition} answers it and {@link AgentEngine.resume} takes its two
257
+ * members, so a host that replaces an engine hands the run to the next one where the last one
258
+ * left it, and the gateway replays nothing the host already holds.
259
+ */
260
+ export interface AgentStreamPosition {
261
+ /** The position, as the stream spelled it: what a reopen sends back as `Last-Event-ID`. */
262
+ readonly lastEventId: string;
263
+ /** The run the position belongs to. A position names nothing in another run. */
264
+ readonly runId: string;
265
+ }
266
+
267
+ /**
268
+ * AgentEngineConfig wires a session to the tool bus and its execution context, the
269
+ * injectable transport, and the host observer. `confirmServerTool` is the gate the
270
+ * session calls when the gateway asks to run a destructive SERVER tool
271
+ * ({@link ServerToolConfirmation}); the host wires it to the same confirm modal the
272
+ * bus uses for client tools. The engine changes no UI state of its own: it dispatches
273
+ * every UI-affecting client tool through the bus, the sole executor.
274
+ *
275
+ * `toolSurface` is the routing seam: it returns the tool names the model should be
276
+ * offered right now, or undefined for the whole permitted set. The session only
277
+ * reads it (which tools belong to a task is policy the host owns), and it is
278
+ * consulted both when a run opens and on every {@link AgentEngine.routeTools} call,
279
+ * so the run's opening turn is routed exactly like the ones after it. It shapes only
280
+ * what the model can SEE; the capability gate remains the sole authorization boundary.
281
+ */
282
+ export interface AgentEngineConfig<TContext extends AgentToolContext = AgentToolContext> {
283
+ bus: ToolDispatcher<TContext>;
284
+ confirmServerTool: (confirmation: ServerToolConfirmation) => Promise<boolean>;
285
+ ctx: TContext;
286
+ observer: AgentObserver;
287
+ /**
288
+ * How the host reports what its own state did while a tool ran, and what to try after a
289
+ * failure. Both are OPTIONAL and both are the host's policy rather than the loop's:
290
+ * `@mountaya/studio` passes its store fingerprint and its routing tables, a host wiring their
291
+ * own tools passes neither and a run reports the tool result bare.
292
+ */
293
+ recoveryFor?: RecoveryLookup | undefined;
294
+ stateDelta?: StateDelta<TContext> | undefined;
295
+ /**
296
+ * Prompt profile the run opens with. Omitted means the full studio co-pilot.
297
+ * It belongs on the session rather than on start() because it is a property of
298
+ * the SURFACE, not of a message: a Video Director session is a director for its
299
+ * whole life.
300
+ */
301
+ profile?: AgentRunProfile | undefined;
302
+ /**
303
+ * Whether a run names the server tools the model sees, from the selection `toolSurface`
304
+ * answers: the routed set rides a start's `server_tools` and every routing update's.
305
+ *
306
+ * Off by default, and off under a publishable key, the credential a run is started with: a
307
+ * run under a key calls no server tool, and the API refuses a start or an update that names
308
+ * any. The engine then sends no `server_tools` at all, and routes the client tools alone.
309
+ * Turn it on only for a credential the API lets a run's model reach the server tools under:
310
+ * on under a publishable key, the transport `createAgentTransport` builds refuses the start
311
+ * before it is sent, with a `MountayaConfigurationError` naming this option, which the start
312
+ * rejects with.
313
+ *
314
+ * @default false
315
+ */
316
+ routesServerTools?: boolean | undefined;
317
+ toolSurface?: (() => ReadonlySet<string> | undefined) | undefined;
318
+ /**
319
+ * The run's reader and writer: usually `createAgentTransport` from `@mountaya/client/events`,
320
+ * which gives up an open that never answers and a stream gone silent as connection errors. A
321
+ * transport of your own bounds both waits the same way, since the engine waits as long as
322
+ * `subscribe` says nothing, and reports `onClose("terminal")` only after it has handed over a
323
+ * `done`.
324
+ */
325
+ transport: AgentTransport;
326
+ }
327
+
328
+ /**
329
+ * toClientToolManifest maps the bus's capability-scoped manifest onto the wire
330
+ * shape the gateway expects: a tool's JSON-Schema `inputSchema` becomes the
331
+ * manifest entry's `parameters` object. The gateway merges these client tools
332
+ * with its server tools into the schema list handed to the model.
333
+ *
334
+ * `confirms` rides along for the tools that interrupt the user, so the model can
335
+ * sequence them last instead of stalling a multi-step run on a modal it did not
336
+ * know was coming. It is sent only when true: an explicit `false` on every other
337
+ * tool would cost bytes on the run-start upload for no signal.
338
+ */
339
+ const toClientToolManifest = (entries: ToolManifestEntry[]): AgentClientToolManifest[] =>
340
+ entries.map((entry) => ({
341
+ ...(entry.requiresConfirmation ? { confirms: true } : {}),
342
+ ...(entry.readOnly ? { read_only: true } : {}),
343
+ description: entry.description,
344
+ name: entry.name,
345
+ parameters: entry.inputSchema,
346
+ }));
347
+
348
+ /**
349
+ * manifestKey reduces a manifest to the identity routing cares about: which tools
350
+ * are in it. Descriptions and schemas come from the registry, so two manifests
351
+ * over the same names are the same offer, and comparing names alone is what lets
352
+ * an unchanged selection skip the wire.
353
+ */
354
+ const manifestKey = (manifest: AgentClientToolManifest[]): string =>
355
+ manifest
356
+ .map((entry) => entry.name)
357
+ .sort()
358
+ .join("\n");
359
+
360
+ /**
361
+ * routedKey is the change key for a whole routed selection, its client tools and its
362
+ * server tools alike.
363
+ *
364
+ * It spans client AND server tools because a selection that moves only its server ops
365
+ * (same client members, different surface) must still signal, or the model keeps
366
+ * yesterday's server list. Held in one function because the run start and the mid-run
367
+ * re-route both compute it, and a key computed two ways is a key that eventually
368
+ * disagrees with itself: the two sides would then either signal on every turn (busting
369
+ * the cached prompt prefix each time) or never.
370
+ *
371
+ * The separator is NUL because it cannot occur in a tool name, so no combination of
372
+ * names can be read as a different split. It is written as an escape rather than as a
373
+ * literal byte: a raw NUL in the source makes the file binary to grep and diff, and is
374
+ * invisible in an editor, which is a poor property for a character load-bearing enough
375
+ * to be chosen on purpose.
376
+ */
377
+ const routedKey = (
378
+ manifest: AgentClientToolManifest[],
379
+ serverTools: string[] | undefined,
380
+ ): string => `${manifestKey(manifest)}\0${serverTools?.join(",") ?? ""}`;
381
+
382
+ /**
383
+ * AGENT_RECONNECT_BASE_MS is the ceiling of the wait before the first reconnect after an
384
+ * unproductive hangup, doubling from there. Half a second keeps a gateway blipping
385
+ * between turns invisible to the user, and the doubling keeps a stream that fails
386
+ * the instant it opens from being re-opened in a tight loop.
387
+ */
388
+ const AGENT_RECONNECT_BASE_MS = 500;
389
+
390
+ /**
391
+ * RECONNECT_MAX_MS caps the doubling ceiling. Someone is sitting in front of the
392
+ * run, so it must never spend a minute asleep between tries: the ceiling stops
393
+ * growing well before the attempt ceiling is reached.
394
+ */
395
+ const RECONNECT_MAX_MS = 8_000;
396
+
397
+ /**
398
+ * reconnectSchedule is the run's numbers for {@link reconnectDelayMs}: a wait drawn
399
+ * from zero to a ceiling that starts at {@link AGENT_RECONNECT_BASE_MS} and doubles to
400
+ * {@link RECONNECT_MAX_MS}. The draw rather than the ceiling, so runs one gateway
401
+ * restart dropped together do not reopen in step and meet each other again.
402
+ */
403
+ const reconnectSchedule: ReconnectSchedule = {
404
+ baseMs: AGENT_RECONNECT_BASE_MS,
405
+ maxMs: RECONNECT_MAX_MS,
406
+ };
407
+
408
+ /**
409
+ * RECONNECT_MAX_ATTEMPTS is how many consecutive unproductive reconnects a run
410
+ * gets before it settles. Six waits add up to a little over twenty seconds at
411
+ * most, and about half that on average: enough to ride out a proxy recycling a
412
+ * connection, and short enough that a run nothing can revive stops re-opening a
413
+ * stream for as long as the tab is open. An open answered 503 is not one of them:
414
+ * {@link RECONNECT_UNAVAILABLE_MAX_MS} bounds those.
415
+ */
416
+ const RECONNECT_MAX_ATTEMPTS = 6;
417
+
418
+ /**
419
+ * RECONNECT_UNAVAILABLE_MAX_MS is how long a run keeps reopening a stream whose opens are
420
+ * answered 503 before it settles with the last of them: two minutes from the first, with no
421
+ * progress in between.
422
+ *
423
+ * It is sized for a failover of the store behind the stream. A 503 says the run's events cannot
424
+ * be reached for a moment, and the run goes on being published while they cannot: a read that
425
+ * gave up shows nothing of it until the page is loaded again. A failover can outlast the
426
+ * twenty-odd seconds {@link RECONNECT_MAX_ATTEMPTS} allows, and the API names a wait of one
427
+ * second on each answer, which six attempts would spend in about ten. So these opens are held to
428
+ * a time and to no count: two minutes gives a failover room to finish, and is still short of
429
+ * leaving a person in front of a stream nothing will revive.
430
+ */
431
+ const RECONNECT_UNAVAILABLE_MAX_MS = 120_000;
432
+
433
+ /**
434
+ * UNAVAILABLE_STATUS is the answer to a stream open that says the run's events cannot be reached
435
+ * for a moment, the one {@link RECONNECT_UNAVAILABLE_MAX_MS} bounds.
436
+ */
437
+ const UNAVAILABLE_STATUS = 503;
438
+
439
+ /**
440
+ * PRODUCTIVE_FRAME_COUNT is the frame count one open has to BEAT to count as
441
+ * progress. A gateway that opens, says one thing, and hangs up delivers exactly
442
+ * one frame on every try, and a rule of "delivered a frame" would count that as
443
+ * progress forever, so only a stream that carried more than that clears the
444
+ * attempt counter.
445
+ */
446
+ const PRODUCTIVE_FRAME_COUNT = 1;
447
+
448
+ /**
449
+ * REOPEN_STATUSES are the answers to a stream open that the next open can outlive: 429
450
+ * (the gateway is shedding load), 503 and 504 (the gateway or a proxy in front of it failed
451
+ * for a moment). The run behind each is intact, so the engine reopens on its reconnect
452
+ * schedule. 502 is absent: the stream's contract declares none, so one comes from a proxy in
453
+ * front of the gateway, and it is not assumed to be a moment's failure. 500 is absent because
454
+ * a failed request is not assumed safe to repeat, and every 4xx but the 429 is absent because
455
+ * the same request meets the same refusal, the 409 of a run the provider's rate limit already
456
+ * ended included.
457
+ */
458
+ const REOPEN_STATUSES: readonly number[] = [429, 503, 504];
459
+
460
+ /**
461
+ * isConnectionFault reports whether an error is a connection that dropped or never opened:
462
+ * a `TypeError`, which is what fetch and a response body read reject with when the network
463
+ * fails in every runtime, or the client's own `MountayaConnectionError`, which wraps one.
464
+ * Read by `name`, for the reason {@link statusOf} gives.
465
+ */
466
+ const isConnectionFault = (error: unknown): boolean => {
467
+ if (typeof error !== "object" || error === null || !("name" in error)) {
468
+ return false;
469
+ }
470
+
471
+ return error.name === "TypeError" || error.name === "MountayaConnectionError";
472
+ };
473
+
474
+ /**
475
+ * isTransientStreamFault reports whether a failed read of the run's stream is worth another
476
+ * open: a connection fault, or an answer in {@link REOPEN_STATUSES}. Everything else is
477
+ * final, the client's local refusal of a credential included, because nothing about the next
478
+ * open would be different.
479
+ */
480
+ const isTransientStreamFault = (error: unknown): boolean => {
481
+ const status = statusOf(error);
482
+
483
+ return status === undefined ? isConnectionFault(error) : REOPEN_STATUSES.includes(status);
484
+ };
485
+
486
+ /**
487
+ * StreamFailure is a read of the run's stream that failed rather than closed: the `error` it
488
+ * failed with, and whether the next open can outlive it (`transient`). A fault in the
489
+ * engine's own handling of a frame is never transient, whatever it looks like: the engine
490
+ * reopens nothing by itself after one, since the same frame would fail the same way. The
491
+ * position goes back before that frame, so a resume the host asks for reads it again.
492
+ */
493
+ interface StreamFailure {
494
+ error: unknown;
495
+ transient: boolean;
496
+ }
497
+
498
+ /**
499
+ * ConsumeResult reports the outcome of reading one open of the run's stream:
500
+ * whether a terminal event `ended` the run, how many `frames` it delivered, whether the
501
+ * stream ended with the credential it was opened with (`reconnect`), and the
502
+ * `failure` when the read failed rather than closed. The count tells a turn that
503
+ * actually moved from one that delivered just enough to look like it did. It counts every
504
+ * record that carries data, one the transport skips included, since the stream delivered it, and
505
+ * never a `reconnect`, which is the transport's own.
506
+ */
507
+ interface ConsumeResult {
508
+ ended: boolean;
509
+ failure?: StreamFailure | undefined;
510
+ frames: number;
511
+ reconnect?: boolean | undefined;
512
+ }
513
+
514
+ /**
515
+ * UnavailableOpens are the opens answered 503 among a run of consecutive opens without progress:
516
+ * how many, which the attempt ceiling leaves out of its count, and when the first was answered,
517
+ * which {@link RECONNECT_UNAVAILABLE_MAX_MS} is measured from.
518
+ */
519
+ interface UnavailableOpens {
520
+ count: number;
521
+ readonly since: number;
522
+ }
523
+
524
+ /**
525
+ * PendingStart is a start still waiting on its run id. close(), dispose(), and a later
526
+ * start() or resume() withdraw it by aborting `withdrawal`, and the start then finishes the
527
+ * run it opens instead of reading it: the host never learned that run's id, so nothing but
528
+ * the engine can reach it.
529
+ */
530
+ interface PendingStart {
531
+ /**
532
+ * Whether the start opened a run the engine reads: true once the engine adopts the run, false
533
+ * when the start fails or is withdrawn. A message or a routing update made while the start
534
+ * waits reads it to learn whether it has a run to go to.
535
+ */
536
+ readonly opened: Promise<boolean>;
537
+ /** settle answers `opened`. The first call decides it, and a later one changes nothing. */
538
+ readonly settle: (opened: boolean) => void;
539
+ readonly withdrawal: AbortController;
540
+ }
541
+
542
+ /** createPendingStart builds the record of a start that is about to post. */
543
+ const createPendingStart = (): PendingStart => {
544
+ let settle: (opened: boolean) => void = () => {};
545
+ const opened = new Promise<boolean>((resolve) => {
546
+ settle = resolve;
547
+ });
548
+
549
+ return { opened, settle, withdrawal: new AbortController() };
550
+ };
551
+
552
+ /**
553
+ * SendHold is the claim the messages still being posted have on `running`: the state the first
554
+ * of them found, and how many posts are out.
555
+ *
556
+ * A send reports `running` at the call. When its post fails the message reached no run and no
557
+ * turn follows it, so the state goes back to what the hold found, once the last post of the
558
+ * hold has failed. A post that lands empties `found`: its turn follows and the stream settles
559
+ * it. The engine drops the hold at every other report of a state, so a frame that spoke, a
560
+ * close or a new run leaves nothing to go back to.
561
+ */
562
+ interface SendHold {
563
+ found: AgentEngineState | null;
564
+ posting: number;
565
+ }
566
+
567
+ /**
568
+ * AgentEngine is a long-lived, multi-turn agent run over a single persistent
569
+ * event stream. start() opens the run with the bus's contextual client-tool
570
+ * manifest and then consumes the run's one events stream to completion; across
571
+ * the run that consumer streams assistant text to the observer, dispatches each
572
+ * CLIENT tool-call through the bus and posts the result back, drives a
573
+ * destructive SERVER tool's confirmation through the host gate, and rides each
574
+ * turn boundary (an `awaiting-input` event keeps the same stream open for the next
575
+ * message). send() only posts the follow-up message; the already-open consumer
576
+ * carries that turn's events. close() asks the run to finish. The bus is the
577
+ * sole executor of UI-affecting tools: the model only emits tool calls.
578
+ *
579
+ * A resumed stream replays the run's history, and the engine leaves alone every call the
580
+ * replay marks `settled`: it drops a `tool-call` or a `confirm-required` that carries the
581
+ * marker, and any `tool_call_id` it has already handled in the run, so one engine runs a
582
+ * call once and asks a confirmation once. A replayed frame with neither is handled as a
583
+ * live one: a call still waiting on its answer, or a confirmation approved while its tool
584
+ * is still running, which the stream holds no outcome for yet. For that confirmation an
585
+ * engine built after a page reload asks the host again, and the gateway ignores the second
586
+ * decision.
587
+ *
588
+ * One engine reads one run at a time. A start() or a resume() replaces whatever the
589
+ * engine reads when it is called, so two runs never share its cursor, its stream or
590
+ * its memory of handled calls.
591
+ *
592
+ * @example
593
+ * ```ts
594
+ * import type { Mountaya } from "@mountaya/client";
595
+ * import { createAgentTransport } from "@mountaya/client/events";
596
+ * import { AgentEngine, type ToolDispatcher } from "@mountaya/elements/agent";
597
+ *
598
+ * declare const mountaya: Mountaya;
599
+ *
600
+ * const tools: ToolDispatcher<{ capabilities: ReadonlySet<string> }> = {
601
+ * dispatchFromModel: async (_context, name) => ({ ok: true, summary: `Ran ${name}` }),
602
+ * manifest: () => [],
603
+ * };
604
+ *
605
+ * const engine = new AgentEngine({
606
+ * bus: tools,
607
+ * confirmServerTool: async ({ name }) => window.confirm(`Run ${name}?`),
608
+ * ctx: { capabilities: new Set<string>() },
609
+ * observer: {
610
+ * onMessage: (content) => console.log(content),
611
+ * onStateChange: (state) => console.log(state),
612
+ * },
613
+ * transport: createAgentTransport(mountaya.transport),
614
+ * });
615
+ *
616
+ * // A start rejects when the run fails for good, and a send when no run is open: both report.
617
+ * const report = (error: unknown): void => console.error(error);
618
+ *
619
+ * engine.start("Plan a loop around the lake", "org_123").catch(report);
620
+ * // Later, on the user's next message, and on the way out:
621
+ * engine.send("Make it shorter").catch(report);
622
+ * void engine.close().finally(() => engine.dispose());
623
+ * ```
624
+ */
625
+ export class AgentEngine {
626
+ private currentRunId: string | null = null;
627
+ // The run this engine adopted and has neither read to its `done` nor closed: the one run it
628
+ // still owes a close. It outlives the read when the engine stops reading on its own (the
629
+ // reconnect ceiling, two minutes of opens answered 503, an open refused for good), because
630
+ // the gateway holds that run open until its own timeout and nobody else was reading it.
631
+ // leaveRun and close pay it.
632
+ private unfinishedRunId: string | null = null;
633
+ private state: AgentEngineState = "awaiting_input";
634
+
635
+ /**
636
+ * The state the observer was told last. It is {@link state} but from the moment a start
637
+ * readies its run until that start reports: the engine rests for those statements, and the
638
+ * observer is told the state the start leaves it in, never the rest between two turns.
639
+ */
640
+ private reported: AgentEngineState = "awaiting_input";
641
+ // The claim the sends still being posted have on `running`, or null when the state is not
642
+ // theirs alone; see SendHold.
643
+ private sendHold: SendHold | null = null;
644
+ // True while the `running` report of a send is on the stack. A send made from inside it lets
645
+ // the one that reports make its post first; see send.
646
+ private sendReporting = false;
647
+ // The last position the stream named, by a frame that reached the engine or by a record that
648
+ // carries none, sent back as Last-Event-ID so a reconnect resumes after it rather than
649
+ // replaying the whole durable history. A frame whose handling threw gives its position back.
650
+ private lastEventId: string | undefined;
651
+ // Aborts the open events stream when the host tears the run down or it ends, so
652
+ // a parked consumer and its fetch are released rather than leaked. Replaced each
653
+ // time a new stream is opened (a reconnect), and tripped by close(), dispose(), and
654
+ // a start() or resume() that replaces the run.
655
+ private streamAbort: AbortController | null = null;
656
+ // Unsubscribes from the open events stream. The abort tears the live fetch down;
657
+ // this stops the callback delivery (and the scripted drain, which has no fetch).
658
+ // Whatever trips the abort trips both; a settle inside consume clears it while it is
659
+ // still that read's.
660
+ private unsubscribe: (() => void) | null = null;
661
+ // Counts the reads beginRun readied, so a read can tell whether a start or a resume made
662
+ // from one of the observer's callbacks replaced it while it handled a frame.
663
+ private readGeneration = 0;
664
+ // The tool names the run was last offered, so routeTools can skip a no-op
665
+ // update rather than busting the provider's cached prompt prefix for nothing.
666
+ private routedNames = "";
667
+ // Counts the routing updates sent, so each one is numbered in the order the run was sent it.
668
+ private routingUpdates = 0;
669
+ // The number of the update whose selection is recorded, so an answer can tell whether the
670
+ // run accepted a later one.
671
+ private routedUpdate = 0;
672
+ // The shutdown latch. dispose() sets it, and from then on start() and resume() open
673
+ // nothing: a torn-down engine that started a run would start one nobody reads.
674
+ private disposed = false;
675
+ // The start still waiting on its run id, if one is; see PendingStart.
676
+ private pendingStart: PendingStart | null = null;
677
+ // The tool_call_ids of the client tool calls the engine ran, of the confirmations it
678
+ // answered and of the calls the stream marked settled, in the run named by handledRunId, so
679
+ // a frame the stream sends again runs nothing twice and asks nothing twice. A reopen that
680
+ // sends no cursor is answered with the run's whole history, the calls already handled
681
+ // included.
682
+ private readonly handledCalls = new Set<string>();
683
+ private handledRunId: string | null = null;
684
+ // The tool_call_ids of the client tool calls the engine ran and reported itself in the run
685
+ // named by handledRunId. Each is reported from the bus result, so what the stream says about
686
+ // one afterwards (the gateway's echo of the answer, an abandonment that crossed it) is
687
+ // dropped. A call whose handling threw before its report is not among them: what the stream
688
+ // says about it is the one report it gets.
689
+ private readonly dispatchedCalls = new Set<string>();
690
+ // The client tool calls the engine is running in the run named by handledRunId: claimed, and
691
+ // not reported yet. Each maps to the first thing the stream said of the call meanwhile, held
692
+ // as the report it would have made, or to null while the stream has said nothing. A read a
693
+ // resume opened beside the handling is the one that can say something. The entry goes at
694
+ // the engine's own report, which drops the held word, and when the handling throws before
695
+ // it, which releases the word.
696
+ private readonly runningCalls = new Map<string, (() => void) | null>();
697
+
698
+ constructor(private readonly config: AgentEngineConfig) {}
699
+
700
+ /**
701
+ * start opens a fresh run with the user's first message, then consumes the
702
+ * run's single event stream to completion. The returned promise settles only
703
+ * when the engine stops reading the run, so the caller fire-and-forgets it and
704
+ * reacts to turns through the observer instead. It resolves on the terminal
705
+ * `done`, on {@link close} or {@link dispose}, when a later start or
706
+ * {@link resume} replaces the run, and when its reconnects stop being productive.
707
+ *
708
+ * It rejects when the start or the stream fails for good: a start whose post is
709
+ * refused, at once for most answers and, for a 429, a 502, a 503, a 504 or a dropped
710
+ * connection, once the transport has repeated it under the start's idempotency key
711
+ * as far as its retry policy goes, a stream open answered with anything but a 429,
712
+ * 503 or 504, a fault in one of the host's own seams, and a stream that is still
713
+ * failing when the reconnect ceiling is reached, whether its connection stays down
714
+ * or every open is answered 429 or 504; that one rejects with the last
715
+ * failure. A stream that fails leaves the state `ended`, reported through
716
+ * `onStateChange("ended")`, before the promise rejects; a start that fails leaves
717
+ * it `awaiting_input`.
718
+ *
719
+ * A stream open answered 503 is not counted against the reconnect ceiling. It says the
720
+ * run's events cannot be reached for a moment while the run goes on, so the engine opens
721
+ * the stream again, after the wait the answer names, for as long as two minutes of such
722
+ * answers with no turn read in between, and then rejects with the last of them.
723
+ *
724
+ * The state is `running` from the call, reported through `onStateChange("running")` before
725
+ * the run has an id, so a host shows the turn as under way from the message. A start that
726
+ * fails reports `awaiting_input` again before its promise rejects. The report is the last
727
+ * step ahead of the post: a start that fails before it, on a fault in the tool surface,
728
+ * never reports `running`.
729
+ *
730
+ * A start that replaces a run reports that one change and no rest ahead of it: `running`
731
+ * from an engine at rest or whose last run ended, and nothing from an engine whose run is
732
+ * under way, which reads `running` through the replacement. Where such a start fails, the
733
+ * one report is `awaiting_input`.
734
+ *
735
+ * One engine reads one run. A start while the engine still reads a run tears that
736
+ * run's stream down and posts a close for it before it opens its own, so none of
737
+ * that run's frames, its resume cursor or its `done` reach the run that replaces
738
+ * it. A start while another start still waits on its run id withdraws that start,
739
+ * as {@link close} does. A start on an engine whose last run ended opens the next
740
+ * run and reads it from its beginning, and posts a close for that last run first when
741
+ * the engine stopped reading it short of its `done` (see {@link close}). A start after
742
+ * {@link dispose} opens nothing and resolves at once.
743
+ *
744
+ * Every start carries an `Idempotency-Key` of its own, drawn once per call where the runtime
745
+ * has a cryptographic random source, and is posted once: the transport repeats a start whose
746
+ * answer was lost under that same key, and the API answers the repeat with the run the key
747
+ * already started, so a lost answer never opens a second run. A start the transport gives up
748
+ * on rejects with the transport's failure, which carries the key. A custom
749
+ * {@link AgentTransport} receives the key as the `idempotencyKey` of the options its `startRun`
750
+ * is handed, and none where the runtime offers no source to draw it from.
751
+ *
752
+ * A {@link close}, a {@link dispose} or a later start or {@link resume} while the start
753
+ * still waits on its run id withdraws it: no stream is opened, no run id and no frame of
754
+ * the run reaches the observer, and the returned promise resolves even when the start
755
+ * itself fails. The run it opens is closed as soon as its id arrives. A withdrawal made from
756
+ * inside a state report of the start itself, or from inside the tool surface it reads (the
757
+ * bus's `manifest`), comes ahead of the post: nothing is posted, no run is opened and no
758
+ * `running` follows the `ended` the withdrawal reported.
759
+ *
760
+ * @param message The user's first message, which opens the run's first turn.
761
+ * @param organizationId The organization that owns the resource the co-pilot is opened on
762
+ * (the itinerary or zone being edited). The run is scoped and access-gated to it, and the
763
+ * API resolves the AI provider credential through it. It is captured per start because it
764
+ * reflects the resource open at the moment the run opens, and the API requires it.
765
+ * @param context The caller's point-in-time studio snapshot, forwarded verbatim to the
766
+ * gateway's create body so the run starts knowing the current UI state. It is captured per
767
+ * start (not held on the session config) because it is a snapshot of the moment the run
768
+ * opens. It stays an opaque `Record<string, unknown>` here because its typed shape is the
769
+ * host's, which this package does not import: the host builds it and passes it through.
770
+ */
771
+ async start(
772
+ message: string,
773
+ organizationId: string,
774
+ context?: Record<string, unknown>,
775
+ ): Promise<void> {
776
+ if (this.disposed) {
777
+ return;
778
+ }
779
+
780
+ this.leaveRun();
781
+ // The start is on record ahead of every state it reports. A report hands control to the
782
+ // observer, and a close, a dispose, a start or a resume made from inside one withdraws this
783
+ // start as it does one that waits on its run id.
784
+ const pending = createPendingStart();
785
+ this.pendingStart = pending;
786
+ let runId: string;
787
+ try {
788
+ // Unreported: the observer hears `running` next, or the rest once the start fails.
789
+ this.beginRun();
790
+ const manifest = this.routedManifest();
791
+ const serverTools = this.routedServerTools();
792
+ if (pending.withdrawal.signal.aborted) {
793
+ // Withdrawn from inside the tool surface: the call that withdrew it reported its state,
794
+ // and nothing is posted, so no run is owed a close.
795
+ return;
796
+ }
797
+
798
+ const params: AgentRunCreateParams = {
799
+ client_tools: manifest,
800
+ context,
801
+ message,
802
+ organization_id: organizationId,
803
+ profile: this.config.profile,
804
+ // Left out rather than sent empty where the session routes no server tool: a key's run
805
+ // calls none, and the API refuses a start that names any.
806
+ ...(serverTools === undefined ? {} : { server_tools: serverTools }),
807
+ };
808
+ // Drawn once for this start and sent on every attempt of its post, so the transport's
809
+ // repeat after a lost answer resolves to the run the first attempt started. A runtime with
810
+ // no cryptographic source draws none, and the transport then sends none.
811
+ const idempotencyKey = randomUuid();
812
+ // The message opens a turn: the engine is running from here, whatever the stream says
813
+ // first. The report is the last step ahead of the post, so a fault in the host's tool
814
+ // surface is a start that never left rest.
815
+ this.setState("running");
816
+ if (pending.withdrawal.signal.aborted) {
817
+ // Withdrawn from inside the report. Nothing is posted, so no run is owed a close.
818
+ return;
819
+ }
820
+
821
+ this.routedNames = routedKey(manifest, serverTools);
822
+ ({ runId } = await this.config.transport.startRun(params, { idempotencyKey }));
823
+ } catch (error) {
824
+ pending.settle(false);
825
+ if (!pending.withdrawal.signal.aborted) {
826
+ // No run opened, so no turn follows the message. A withdrawn start leaves the state to
827
+ // whatever withdrew it.
828
+ this.setState("awaiting_input");
829
+
830
+ throw error;
831
+ }
832
+
833
+ // A withdrawn start has nobody to report to: the host tore the conversation down, or
834
+ // moved on to another run, while it waited.
835
+ return;
836
+ } finally {
837
+ if (this.pendingStart === pending) {
838
+ this.pendingStart = null;
839
+ }
840
+ }
841
+
842
+ if (pending.withdrawal.signal.aborted) {
843
+ await this.closeQuietly(runId);
844
+
845
+ return;
846
+ }
847
+
848
+ this.adoptRun(runId);
849
+ // What waited on this start resumes after the read below has opened the run's stream, so a
850
+ // held message is posted into a run already being read.
851
+ pending.settle(true);
852
+ this.tell((observer) => observer.onRunId?.(runId));
853
+
854
+ await this.run(runId);
855
+ }
856
+
857
+ /**
858
+ * resume re-attaches to an already-started run (e.g. after a page reload) and consumes the
859
+ * run's single event stream to completion. It lets a reload reconnect to an
860
+ * in-flight conversation rather than starting over. Its promise settles as the
861
+ * read of a {@link start} does: it resolves when the engine stops reading the run,
862
+ * and rejects when the stream fails for good, the state already `ended`.
863
+ *
864
+ * `lastEventId` is the stream position to read on from: the gateway replays what follows
865
+ * it, then the live feed. Without one the read starts where the engine left the run when
866
+ * `runId` is the run it holds (the one it read last, still open or not), so a host that
867
+ * kept its transcript re-attaches and is handed nothing a second time. That place is after
868
+ * the last frame that reached the engine, the one an observer callback is being handed
869
+ * included: a resume made from inside the callback reads on after that frame. A frame whose
870
+ * handling threw (a seam that answers: the tool layer, the confirm gate, the tool surface or
871
+ * the state delta) is the exception. It is read again, and
872
+ * a call the run already claimed is dropped. For any other run the engine holds no position,
873
+ * and the gateway answers with the run's whole history: that is the read an engine built
874
+ * after a reload makes, and its host starts from an empty transcript. To read the held run
875
+ * from its first event again, resume it on a new engine.
876
+ *
877
+ * Like {@link start}, it reads the run on an engine whose last run ended, opens
878
+ * nothing after {@link dispose}, and replaces what the engine reads when it is
879
+ * called: another run is torn down and closed, and a start still waiting on its run
880
+ * id is withdrawn. A resume of the run the engine is reading tears that read down
881
+ * and reads the run again from `lastEventId`, or from where that read was when none is
882
+ * passed, and posts no close for it.
883
+ *
884
+ * The engine is at rest as the read begins, reported through `onStateChange("awaiting_input")`
885
+ * from an engine that was `running` or `ended`, and the stream says the rest. A call made
886
+ * from inside that report is read before the run is adopted, as one made from a report of a
887
+ * {@link start} is: a {@link dispose} ends the resume with no stream opened and no run to
888
+ * close, and a start or another resume is the one read the engine makes, so this resume
889
+ * resolves at once. A {@link close} made there finds no run held and posts nothing, and the
890
+ * resume reads its run.
891
+ */
892
+ async resume(runId: string, lastEventId?: string): Promise<void> {
893
+ if (this.disposed) {
894
+ return;
895
+ }
896
+
897
+ // Read before beginRun clears it: the position belongs to the run read last, so it is
898
+ // kept for a resume of that run and for no other.
899
+ const held = this.currentRunId === runId ? this.lastEventId : undefined;
900
+
901
+ this.leaveRun(runId);
902
+ const generation = this.beginRun();
903
+ // The rest the engine is readied in is reported, and the report hands control to the
904
+ // observer. A dispose made from inside it ends this resume, and a start or a resume made
905
+ // there has the engine from here: each readies a read of its own.
906
+ this.setState("awaiting_input");
907
+ if (this.disposed || generation !== this.readGeneration) {
908
+ return;
909
+ }
910
+
911
+ this.adoptRun(runId);
912
+ this.lastEventId = lastEventId ?? held;
913
+
914
+ await this.run(runId);
915
+ }
916
+
917
+ /**
918
+ * streamPosition reads where the engine stands in the run it read last, for a host that
919
+ * replaces the engine and has the next one read the run on.
920
+ *
921
+ * It is the position a {@link resume} of that run on this engine reads on from: after the last
922
+ * frame that reached the engine, or the position a resume was handed while no frame has
923
+ * followed it. It is kept through {@link dispose}, which is when a host reads it.
924
+ *
925
+ * @returns The run and the position, or `null` while the engine has read no run or the run's
926
+ * stream has named no position, which is the whole of a run whose frames carry no id.
927
+ *
928
+ * @example
929
+ * ```ts
930
+ * import type { AgentEngine } from "@mountaya/elements/agent";
931
+ *
932
+ * declare const parked: AgentEngine;
933
+ * declare const next: AgentEngine;
934
+ *
935
+ * const position = parked.streamPosition();
936
+ * parked.dispose();
937
+ * if (position !== null) {
938
+ * next.resume(position.runId, position.lastEventId).catch((error: unknown) => {
939
+ * console.error(error);
940
+ * });
941
+ * }
942
+ * ```
943
+ */
944
+ streamPosition(): AgentStreamPosition | null {
945
+ return this.currentRunId === null || this.lastEventId === undefined
946
+ ? null
947
+ : { lastEventId: this.lastEventId, runId: this.currentRunId };
948
+ }
949
+
950
+ /**
951
+ * runId reads the id of the run the engine holds: the one a {@link start} opened, from the
952
+ * moment its post answers, or the one a {@link resume} reads, from the moment it begins. It is
953
+ * kept once the engine stops reading that run, whether the run ended, its stream failed, or the
954
+ * engine was disposed.
955
+ *
956
+ * It is what tells the two failures a start rejects with apart. A start whose post the gateway
957
+ * refused opened no run, and this reads null; a start whose run opened and whose stream was
958
+ * then refused reads that run. The same status says different things on each: a 404 on the post
959
+ * is an organization the reader does not reach, and a 404 on the stream is a run the gateway no
960
+ * longer holds.
961
+ *
962
+ * @returns The run's id, or null while the engine holds none: before its first run, and from
963
+ * the moment a start replaces a run until the post of that start answers, which a start that
964
+ * fails never does.
965
+ *
966
+ * @example
967
+ * ```ts
968
+ * import type { AgentEngine } from "@mountaya/elements/agent";
969
+ *
970
+ * declare const engine: AgentEngine;
971
+ * declare const report: (failure: unknown, openedRun: string | null) => void;
972
+ *
973
+ * engine.start("Plan a loop", "organization-id").catch((failure: unknown) => {
974
+ * report(failure, engine.runId());
975
+ * });
976
+ * ```
977
+ */
978
+ runId(): string | null {
979
+ return this.currentRunId;
980
+ }
981
+
982
+ /**
983
+ * send delivers a follow-up user message into the open run. It only posts the
984
+ * input (the persistent consumer opened by start/resume carries this turn's
985
+ * events), so it does NOT open a second stream.
986
+ *
987
+ * A message sent while a {@link start} still waits on its run id is held until the id
988
+ * arrives, then posted into that run, behind the opening of its stream and in the order the
989
+ * messages were sent. A start settles only when its run is over, so a caller has no promise
990
+ * to wait on before the next message. When that start opens no run (it fails, or a
991
+ * {@link close}, a {@link dispose} or a later start or {@link resume} withdraws it), the
992
+ * held message is dropped and the promise resolves: the start's rejection, or the call that
993
+ * withdrew it, already says the conversation did not open, and a second report of one
994
+ * failure is one too many.
995
+ *
996
+ * The state is `running` from the call the engine takes, reported through
997
+ * `onStateChange("running")` when the run was at rest, so the turn's settle is a change the
998
+ * observer hears even when the turn sends no frame of its own. A message the engine refuses
999
+ * changes nothing. When the post fails, the engine reports `awaiting_input` again before the
1000
+ * promise rejects, unless another message is still being posted, one of them landed, or the
1001
+ * stream has reported a state since: the turn is then the stream's to settle.
1002
+ *
1003
+ * The report is made ahead of the post, and the message goes into the run it found at the
1004
+ * call. A {@link close}, a {@link dispose}, a {@link start} or a {@link resume} of another run
1005
+ * made from inside that report takes the run from the message: nothing is posted and the
1006
+ * promise resolves, as it does for a message held behind a start that opens no run. A
1007
+ * {@link resume} of the same run keeps the message, and its turn is the stream's to settle.
1008
+ * A send made from inside that report is posted after the message that reported, so two
1009
+ * messages reach the run in the order they were sent.
1010
+ *
1011
+ * @throws {MountayaElementsError} when no run is being read and none is on its way: on an
1012
+ * engine that never opened one, and once the run has ended, been closed or been disposed.
1013
+ * A run that ended takes no more messages, and one the engine has stopped reading would
1014
+ * answer to nobody, so the refusal is local rather than a request the gateway refuses. It
1015
+ * is the package's own error and no stream fault, because it is a misuse of this package,
1016
+ * which is what a consumer catching {@link MountayaElementsError} is catching. The next
1017
+ * message goes into a run a new {@link start} opens, except on a disposed engine, which
1018
+ * opens no more runs: the conversation continues on a new engine.
1019
+ */
1020
+ async send(message: string): Promise<void> {
1021
+ // Made from inside the `running` report of another send: that send goes on to its post, or
1022
+ // drops its message, in the turn its report returns to. One turn later this message is
1023
+ // behind it, and is checked against the engine as that call left it.
1024
+ if (this.sendReporting) {
1025
+ await Promise.resolve();
1026
+ }
1027
+
1028
+ const pending = this.pendingStart;
1029
+ if (pending !== null && !(await pending.opened)) {
1030
+ return;
1031
+ }
1032
+
1033
+ if (this.disposed) {
1034
+ throw new MountayaElementsError(
1035
+ "send: the engine is disposed and opens no more runs. Build a new engine to continue the conversation.",
1036
+ );
1037
+ }
1038
+
1039
+ if (this.state === "ended") {
1040
+ throw new MountayaElementsError(
1041
+ "send: the run has ended, and a run that ended takes no more messages. Open the next run with start().",
1042
+ );
1043
+ }
1044
+
1045
+ // Read once: the message goes into the run it was checked against, whatever the observer
1046
+ // does from inside the report below.
1047
+ const runId = this.currentRunId;
1048
+ if (runId === null) {
1049
+ throw new MountayaElementsError(
1050
+ "send: no run is open. Open one with start(), or re-attach to one with resume(), before sending into it.",
1051
+ );
1052
+ }
1053
+
1054
+ // The message opens a turn. A send that finds no other post out takes the state as it
1055
+ // stands, and one made beside another joins that one's hold.
1056
+ const hold = this.sendHold ?? { found: this.state, posting: 0 };
1057
+ hold.posting += 1;
1058
+ this.sendHold = hold;
1059
+
1060
+ try {
1061
+ // The one report that keeps the hold. It hands control to the observer, and any state the
1062
+ // engine reports from inside it (a close, a dispose, a start, a resume) drops the hold as
1063
+ // it does at any other time.
1064
+ this.sendReporting = true;
1065
+ try {
1066
+ this.reportState("running");
1067
+ } finally {
1068
+ this.sendReporting = false;
1069
+ }
1070
+
1071
+ if (!this.reads(runId)) {
1072
+ // The call made from inside the report took the run from the message, as a withdrawal
1073
+ // takes it from a message held behind a start. That call has said so already.
1074
+ return;
1075
+ }
1076
+
1077
+ await this.config.transport.sendInput(runId, { content: message, type: "user-message" });
1078
+ // The message is in the run: its turn follows, and the stream settles it.
1079
+ hold.found = null;
1080
+ } catch (error) {
1081
+ // The message reached no run. The last post of a hold nothing else has spoken over gives
1082
+ // the state back. A hold stands only while the state is `running`, so what is given back
1083
+ // is the message's own report.
1084
+ if (this.sendHold === hold && hold.posting === 1 && hold.found === "awaiting_input") {
1085
+ this.setState("awaiting_input");
1086
+ }
1087
+
1088
+ throw error;
1089
+ } finally {
1090
+ hold.posting -= 1;
1091
+ if (this.sendHold === hold && hold.posting === 0) {
1092
+ this.sendHold = null;
1093
+ }
1094
+ }
1095
+ }
1096
+
1097
+ /**
1098
+ * reads reports whether `runId` is still the run this engine reads: the engine is neither
1099
+ * disposed nor ended, and no start or resume has put another run in its place.
1100
+ */
1101
+ private reads(runId: string): boolean {
1102
+ return !this.disposed && this.state !== "ended" && this.currentRunId === runId;
1103
+ }
1104
+
1105
+ /**
1106
+ * routedManifest renders the wire manifest for whatever the toolSurface seam
1107
+ * currently selects, or the whole permitted set when no router is wired.
1108
+ */
1109
+ private routedManifest(): AgentClientToolManifest[] {
1110
+ const { bus, ctx, toolSurface } = this.config;
1111
+
1112
+ return toClientToolManifest(bus.manifest(ctx.capabilities, toolSurface?.()));
1113
+ }
1114
+
1115
+ /**
1116
+ * routedServerTools renders the server-tool allowlist for whatever the
1117
+ * toolSurface seam currently selects: the routed name set verbatim, sorted so
1118
+ * the wire body and the change key are stable across identical selections.
1119
+ * The gateway ignores the client-tool names in it, so no registry knowledge
1120
+ * is needed here. Undefined when no router is wired: the run then keeps
1121
+ * every server tool. Undefined as well unless the session routes server tools
1122
+ * ({@link AgentEngineConfig.routesServerTools}): under a publishable key a run
1123
+ * calls none, and a list naming any is refused, so none is sent.
1124
+ */
1125
+ private routedServerTools(): string[] | undefined {
1126
+ if (this.config.routesServerTools !== true) {
1127
+ return undefined;
1128
+ }
1129
+
1130
+ const surface = this.config.toolSurface?.();
1131
+
1132
+ return surface ? [...surface].sort() : undefined;
1133
+ }
1134
+
1135
+ /**
1136
+ * routeTools re-reads the toolSurface seam and, when it has moved, replaces the
1137
+ * tool set the run offers the model from its next turn on. The model then
1138
+ * chooses among a coherent handful for the task at hand instead of the whole
1139
+ * registry.
1140
+ *
1141
+ * It narrows only what the model can SEE. Every tool stays registered on the
1142
+ * bus and dispatchable by a human click or an internal tool chain, and the
1143
+ * capability gate remains the sole authorization boundary, exactly as
1144
+ * `agentHidden` behaves.
1145
+ *
1146
+ * An unchanged selection sends nothing. That is not just a saved request: the
1147
+ * tool array is the outermost part of the provider's cached prompt prefix, so a
1148
+ * manifest re-sent on every turn would invalidate the cache every turn and cost
1149
+ * far more than routing saves. "Unchanged" means changed since the run last
1150
+ * ACCEPTED a set, so a selection whose POST failed is retried on the next call
1151
+ * rather than treated as delivered.
1152
+ *
1153
+ * It is a no-op before a run exists, rather than a throw: routing is advisory,
1154
+ * and a surface change while the panel is idle should cost nothing, since the
1155
+ * next start() sends the current selection as the run's seed anyway.
1156
+ *
1157
+ * While a {@link start} still waits on its run id, the seed is already on its way, so the
1158
+ * call waits for the run as {@link send} does and then routes it with the selection the
1159
+ * surface holds by then. A routing update and a message held behind one start are released
1160
+ * in the order they were called, neither waiting on the other's answer, so a caller that
1161
+ * needs the selection in the run ahead of its message awaits routeTools() before it calls
1162
+ * {@link send}. When that start opens no run, nothing is sent.
1163
+ */
1164
+ async routeTools(): Promise<void> {
1165
+ const pending = this.pendingStart;
1166
+ if (pending !== null && !(await pending.opened)) {
1167
+ return;
1168
+ }
1169
+
1170
+ if (!this.currentRunId || this.state === "ended") {
1171
+ return;
1172
+ }
1173
+
1174
+ const manifest = this.routedManifest();
1175
+ const serverTools = this.routedServerTools();
1176
+ // The change key spans BOTH halves of the routed set: a selection that
1177
+ // moves only its server tools (same client members, different surface
1178
+ // ops) must still signal, or the model keeps yesterday's server list.
1179
+ const key = routedKey(manifest, serverTools);
1180
+ if (key === this.routedNames) {
1181
+ return;
1182
+ }
1183
+
1184
+ const runId = this.currentRunId;
1185
+ this.routingUpdates += 1;
1186
+ const update = this.routingUpdates;
1187
+
1188
+ await this.config.transport.sendInput(runId, {
1189
+ client_tools: manifest,
1190
+ ...(serverTools === undefined ? {} : { server_tools: serverTools }),
1191
+ type: "manifest-update",
1192
+ });
1193
+ // Recorded only once the run actually HOLDS this set. Recording it before the
1194
+ // POST would pin the run to the PREVIOUS tool set whenever the update fails: the
1195
+ // caller treats routing as advisory and swallows the rejection, so every later
1196
+ // identical selection would short-circuit above and the model would keep reaching
1197
+ // tools this selection withdrew until the surface happened to move again.
1198
+ //
1199
+ // And only while it is still the answer to believe: a start or a resume that replaced
1200
+ // the run has recorded the new run's own seed, and of the updates the run accepted the one
1201
+ // sent last is the set it holds, whichever answers first. An update sent later that the
1202
+ // run refused changes nothing it holds.
1203
+ if (this.currentRunId === runId && update > this.routedUpdate) {
1204
+ this.routedNames = key;
1205
+ this.routedUpdate = update;
1206
+ }
1207
+ }
1208
+
1209
+ /**
1210
+ * close asks the run to finish. It POSTs a close so the gateway finishes the
1211
+ * run successfully (a terminal `done` event), AND aborts the open stream so a
1212
+ * consumer parked between turns unwinds promptly rather than waiting on the
1213
+ * gateway to close the connection. The terminal `done`, when it arrives first,
1214
+ * ends the session.
1215
+ *
1216
+ * It closes a run the engine stopped reading on its own just the same: one it gave
1217
+ * up on at the reconnect ceiling, after two minutes of opens answered 503 or on an
1218
+ * open refused for good, which the gateway would otherwise hold open until its own
1219
+ * timeout. A run is closed at most once, and a run that read its `done` is closed
1220
+ * never: a second call, and a call after `done`, post nothing. So does a call after
1221
+ * {@link dispose}, which leaves the run it was reading to the host.
1222
+ *
1223
+ * During a start that still waits on its run id, close withdraws the start and
1224
+ * resolves at once, and the start finishes the run it opens (see {@link start}).
1225
+ */
1226
+ async close(): Promise<void> {
1227
+ if (this.pendingStart !== null) {
1228
+ this.withdrawStart();
1229
+ this.setState("ended");
1230
+
1231
+ return;
1232
+ }
1233
+
1234
+ const runId = this.unfinishedRunId;
1235
+ if (runId === null) {
1236
+ return;
1237
+ }
1238
+
1239
+ this.unfinishedRunId = null;
1240
+ this.setState("ended");
1241
+ this.teardownStream();
1242
+ await this.config.transport.sendInput(runId, { type: "close" });
1243
+ }
1244
+
1245
+ /**
1246
+ * dispose tears the session down without signalling the gateway: it aborts the
1247
+ * open stream and marks the run ended, releasing the parked consumer. The host
1248
+ * calls it on unmount AFTER close() has POSTed (a closed tab finishes the run),
1249
+ * with the abort as the backstop when the consumer would otherwise leak.
1250
+ *
1251
+ * It is the engine's shutdown latch: {@link start} and {@link resume} open nothing
1252
+ * afterwards. What it can still cause is what a start sends to finish the run whose id the
1253
+ * host never received, when it was withdrawn or gave up at its ceiling: that run's close,
1254
+ * and, when the start's answer was lost, the one last post of the start that names the run
1255
+ * (see {@link start}).
1256
+ *
1257
+ * The run the engine was reading, or stopped reading on its own, is the host's from here:
1258
+ * the host holds its id, so it can resume it or close it, and a later {@link close} on
1259
+ * this engine posts nothing for it.
1260
+ */
1261
+ dispose(): void {
1262
+ this.disposed = true;
1263
+ this.unfinishedRunId = null;
1264
+ this.withdrawStart();
1265
+ this.setState("ended");
1266
+ this.teardownStream();
1267
+ }
1268
+
1269
+ /**
1270
+ * leaveRun stops the engine reading what it reads, before a {@link start} or a
1271
+ * {@link resume} reads a run: one engine reads one run. A start still waiting on its run
1272
+ * id is withdrawn. A run still being read has its stream torn down, so none of its frames,
1273
+ * its resume cursor or its `done` reach the run read next. A close is posted for the run the
1274
+ * engine still owes one (see `unfinishedRunId`): the run it was reading, and the run it
1275
+ * stopped reading on its own, because in both cases the engine was the one party reading
1276
+ * it. `next` names the run about to be read, and that run is spared the close when it is
1277
+ * the one owed it: a resume of it reads it again.
1278
+ */
1279
+ private leaveRun(next?: string): void {
1280
+ this.withdrawStart();
1281
+
1282
+ if (this.currentRunId !== null && this.state !== "ended") {
1283
+ this.teardownStream();
1284
+ }
1285
+
1286
+ const owed = this.unfinishedRunId;
1287
+ this.unfinishedRunId = null;
1288
+ if (owed !== null && owed !== next) {
1289
+ void this.closeQuietly(owed);
1290
+ }
1291
+ }
1292
+
1293
+ /**
1294
+ * withdrawStart withdraws the start still waiting on its run id, if one is: that start then
1295
+ * finishes the run it opens instead of reading it (see {@link start}), and every message
1296
+ * and routing update held behind it is dropped (see {@link send}).
1297
+ */
1298
+ private withdrawStart(): void {
1299
+ const pending = this.pendingStart;
1300
+ this.pendingStart = null;
1301
+ // Settled here and not when the start's post answers: what waited on the start learns at
1302
+ // once that it has no run to go to, however long the answer takes.
1303
+ pending?.settle(false);
1304
+ pending?.withdrawal.abort();
1305
+ }
1306
+
1307
+ /**
1308
+ * beginRun readies the engine to read a new run once {@link leaveRun} has stopped it
1309
+ * reading the last one. The run id, the resume cursor and the stream handle belong to that
1310
+ * run, so all three go, and the state returns to `awaiting_input`: `ended` would stop the
1311
+ * read loop before it opened anything.
1312
+ *
1313
+ * The rest is the engine's own and is reported to nobody here. A {@link resume} reports it,
1314
+ * since its run may rest for good. A {@link start} reports `running` next, or the rest once
1315
+ * it fails, so a start that replaces a run under way is one turn after another to the
1316
+ * observer and no rest between them ({@link reportState}).
1317
+ *
1318
+ * @returns The generation of the read being readied, which a later start or resume replaces.
1319
+ */
1320
+ private beginRun(): number {
1321
+ this.readGeneration += 1;
1322
+ this.currentRunId = null;
1323
+ this.lastEventId = undefined;
1324
+ this.streamAbort = null;
1325
+ this.sendHold = null;
1326
+ this.state = "awaiting_input";
1327
+
1328
+ return this.readGeneration;
1329
+ }
1330
+
1331
+ /**
1332
+ * adoptRun makes `runId` the run this engine reads, and the run it owes a close until the
1333
+ * run's `done` arrives or a close is posted. The memory of handled calls, and of the calls
1334
+ * the engine reported among them, belongs to one run, because call ids are the run's own: it
1335
+ * is kept when the run is the one already read (a resume of it) and emptied for any other.
1336
+ */
1337
+ private adoptRun(runId: string): void {
1338
+ this.currentRunId = runId;
1339
+ this.unfinishedRunId = runId;
1340
+ if (this.handledRunId !== runId) {
1341
+ this.handledRunId = runId;
1342
+ this.handledCalls.clear();
1343
+ this.dispatchedCalls.clear();
1344
+ this.runningCalls.clear();
1345
+ }
1346
+ }
1347
+
1348
+ /**
1349
+ * claimCall records a call id as handled and reports whether the frame that names it is
1350
+ * the engine's to act on. Two frames are not, and each is dropped whole:
1351
+ *
1352
+ * - one whose id the run already sighted, a replay of a call the engine ran or answered
1353
+ * itself, whose result is already posted;
1354
+ * - one the stream marks `settled`, a replay of a call whose outcome the stream already
1355
+ * holds. An engine built after a page reload has no memory of the run, so the marker is
1356
+ * all that tells it the call was answered.
1357
+ *
1358
+ * A settled id is recorded like any other, so a later frame that names it without the
1359
+ * marker runs nothing either. A replayed frame with no marker and an id never sighted is
1360
+ * one the stream holds no outcome for, and is the engine's.
1361
+ */
1362
+ private claimCall(toolCallId: string, settled: boolean | undefined): boolean {
1363
+ const sighted = this.handledCalls.has(toolCallId);
1364
+ this.handledCalls.add(toolCallId);
1365
+
1366
+ return !sighted && settled !== true;
1367
+ }
1368
+
1369
+ /**
1370
+ * closeQuietly posts a close for a live run the engine leaves behind: one a withdrawn start
1371
+ * opened and never read, whose id the host never received, and one a later start or resume
1372
+ * replaced. A failed post is dropped: nobody is
1373
+ * left to tell, and the gateway completes a run that goes quiet on its own.
1374
+ */
1375
+ private async closeQuietly(runId: string): Promise<void> {
1376
+ try {
1377
+ await this.config.transport.sendInput(runId, { type: "close" });
1378
+ } catch {
1379
+ // Dropped on purpose; see above.
1380
+ }
1381
+ }
1382
+
1383
+ /**
1384
+ * releaseSubscription stops callback delivery from the open stream, exactly
1385
+ * once. It reads the handle out and clears it BEFORE invoking it, so a
1386
+ * re-entrant settle (the abort listener firing synchronously inside
1387
+ * teardownStream, or a transport calling back into onClose) finds nothing
1388
+ * left to release rather than calling the same handle twice.
1389
+ */
1390
+ private releaseSubscription(): void {
1391
+ const unsubscribe = this.unsubscribe;
1392
+ this.unsubscribe = null;
1393
+ unsubscribe?.();
1394
+ }
1395
+
1396
+ /**
1397
+ * teardownStream releases the open events stream from both sides: the
1398
+ * unsubscribe stops callback delivery (covering the scripted drain, which has
1399
+ * no fetch to abort), and the abort closes the live fetch (and trips the resume
1400
+ * detection in run()). Idempotent, so close() followed by dispose() is harmless.
1401
+ *
1402
+ * The unsubscribe runs FIRST because abort() dispatches its listener
1403
+ * synchronously: that listener settles the read and clears the handle, so
1404
+ * aborting first would leave nothing to unsubscribe and the scripted drain
1405
+ * would stay parked for the life of the process.
1406
+ */
1407
+ private teardownStream(): void {
1408
+ this.releaseSubscription();
1409
+ this.streamAbort?.abort();
1410
+ }
1411
+
1412
+ /**
1413
+ * run consumes the run's event stream to completion, reconnecting when the
1414
+ * stream closes before a terminal event. The gateway may close an SSE
1415
+ * connection between turns (e.g. after `awaiting-input`); rather than leave the
1416
+ * run silently stuck, run re-opens the stream from the tracked Last-Event-ID so
1417
+ * the conversation continues. It returns once a terminal event ends the run, an
1418
+ * abort tears the stream down, or the reconnects stop being productive: an open that
1419
+ * closes having said nothing or one frame waits on the reconnect schedule, and the
1420
+ * attempt ceiling below bounds how many of them in a row the run is given.
1421
+ *
1422
+ * A read that FAILS is judged by {@link isTransientStreamFault}. A transient one (a
1423
+ * dropped connection, a 429, 503 or 504 at open) reopens from the last id on the same
1424
+ * schedule and under the same ceiling as a hangup, and when the ceiling is reached on a
1425
+ * read that failed, that failure (the drop, or the 429 or 504) is what the caller
1426
+ * receives. The client's own reader reports an open that never answers and a stream gone
1427
+ * silent as dropped connections, so both reopen. Any other failure ends the read at once and
1428
+ * rejects with it. Either way the state is `ended` before the rejection, because the engine
1429
+ * has stopped reading the run, and the run is owed a close (see {@link close}).
1430
+ *
1431
+ * An open answered 503 reopens on that schedule and outside that ceiling: it is left out of
1432
+ * the count, neither adding to it nor clearing it, and such opens are bounded by
1433
+ * {@link RECONNECT_UNAVAILABLE_MAX_MS} from the first of them, past which the caller receives
1434
+ * the 503. A turn that moves starts the count and that time again.
1435
+ *
1436
+ * A stream that ends with the credential it was opened with, or that the API could not keep
1437
+ * delivering (`interrupted`), reopens at once from the last id, and clears the count of
1438
+ * fruitless opens: the transport closes either as `reconnect`, and the reopen carries the
1439
+ * session token the client holds by then. A 401 on that reopen is a failure like any other
1440
+ * refusal, and ends the read.
1441
+ *
1442
+ * A teardown ends the read wherever it finds it, the backoff between two opens included:
1443
+ * a close or a dispose, and a start or a resume that replaced this run (see
1444
+ * {@link leaveRun}).
1445
+ */
1446
+ private async run(runId: string): Promise<void> {
1447
+ // Consecutive unproductive reconnects, counting the one about to be made. A
1448
+ // turn that actually moved clears it, so this only ever grows while the same
1449
+ // fruitless open is being repeated.
1450
+ let attempts = 0;
1451
+ // The opens answered 503 among them, or null while none was. It is cleared where the count
1452
+ // is and nowhere else: a drop between two 503s belongs to the same outage.
1453
+ let unavailable: UnavailableOpens | null = null;
1454
+
1455
+ while (this.state !== "ended") {
1456
+ const abort = new AbortController();
1457
+ this.streamAbort = abort;
1458
+
1459
+ const result = await this.consume(runId, abort.signal);
1460
+
1461
+ // An abort (a close, a dispose, a start or resume that replaced this run, or a
1462
+ // terminal the session decided) tears the stream down deliberately, so the read's
1463
+ // outcome, a failure included, is moot.
1464
+ if (result.ended || abort.signal.aborted) {
1465
+ return;
1466
+ }
1467
+
1468
+ const { failure } = result;
1469
+ if (failure !== undefined && !failure.transient) {
1470
+ this.setState("ended");
1471
+
1472
+ throw failure.error;
1473
+ }
1474
+
1475
+ // The stream ended with the credential it was opened with (the session token it carried
1476
+ // expired, or the key was revoked), or the API could not keep delivering it
1477
+ // (`interrupted`). That is no failure and no end of the run, so the read reopens at once,
1478
+ // with the token the client holds now and the last event id, and the count of fruitless
1479
+ // opens starts again, as a turn that moved starts it. A 401 on that reopen fails the read
1480
+ // for good above, as every refusal but a 429, 503 or 504 does.
1481
+ if (result.reconnect === true) {
1482
+ attempts = 0;
1483
+ unavailable = null;
1484
+
1485
+ continue;
1486
+ }
1487
+
1488
+ // The stream closed or dropped mid-run: the gateway hung up, or the connection
1489
+ // went. Reconnect from the last seen id to resume the live feed, but count the
1490
+ // fruitless ones, because "delivered a frame" is not the same as "made
1491
+ // progress". A stream that closes having delivered nothing is an open without
1492
+ // progress like any other: a proxy that cycles an idle conversation's stream
1493
+ // says nothing before it hangs up, and the run behind it is intact. A gateway
1494
+ // that opens, emits one frame and hangs up counts too, so a run nothing can
1495
+ // revive stops re-opening the stream at the ceiling. A failed open delivered
1496
+ // nothing at all, so it always counts.
1497
+ //
1498
+ // A turn that carried more than that one frame is a conversation that is
1499
+ // working: it clears the counter and reconnects with no wait at all, which
1500
+ // is the ordinary between-turns hangup. That is what makes this incapable
1501
+ // of throttling a healthy run: the delay only ever accrues across
1502
+ // CONSECUTIVE unproductive opens.
1503
+ if (result.frames > PRODUCTIVE_FRAME_COUNT) {
1504
+ attempts = 0;
1505
+ unavailable = null;
1506
+
1507
+ continue;
1508
+ }
1509
+
1510
+ attempts += 1;
1511
+ if (failure !== undefined && statusOf(failure.error) === UNAVAILABLE_STATUS) {
1512
+ // The run's events cannot be reached for a moment, and the run behind them is intact
1513
+ // and still being published. Such an open is left out of the ceiling's count and held
1514
+ // to a time, measured from the first of them: the outage a 503 reports can outlast the
1515
+ // ceiling's six attempts, and a read that stopped there would show nothing of the run
1516
+ // until the page is loaded again. Past that time the read settles as it does at the
1517
+ // ceiling, and reports the 503.
1518
+ unavailable ??= { count: 0, since: Date.now() };
1519
+ unavailable.count += 1;
1520
+ if (Date.now() - unavailable.since >= RECONNECT_UNAVAILABLE_MAX_MS) {
1521
+ this.setState("ended");
1522
+
1523
+ throw failure.error;
1524
+ }
1525
+ } else if (attempts - (unavailable?.count ?? 0) > RECONNECT_MAX_ATTEMPTS) {
1526
+ // A stream that keeps closing with a token of progress or none is not
1527
+ // recoverable by trying again: whatever ends it (a proxy idle timeout, a
1528
+ // run the gateway has already given up on) ends the next open exactly the
1529
+ // same way. Settle so the host re-enables input rather than leaving the
1530
+ // tab reconnecting behind a conversation nobody can continue. A connection
1531
+ // that never came back is reported, so the host can say so; a stream that
1532
+ // kept closing has no reason to report.
1533
+ this.setState("ended");
1534
+
1535
+ if (failure !== undefined) {
1536
+ throw failure.error;
1537
+ }
1538
+
1539
+ return;
1540
+ }
1541
+
1542
+ // The wait is abort-aware, so a teardown during it unwinds now rather than eight
1543
+ // seconds from now: it trips this same signal. The state is no guard here, because a
1544
+ // start or a resume that replaced this run leaves it anything but `ended`, so the
1545
+ // signal is what ends the read.
1546
+ // A 429 or a 503 that names its wait in `Retry-After` has the reopen wait it out in place
1547
+ // of the draw: one sooner meets the same answer, and a 429's is counted against the same
1548
+ // bound. The draw is on every open without progress, the 503s among them, so a 503 that
1549
+ // names no wait is still reopened at a cadence that slows.
1550
+ await this.backoff(attempts, abort.signal, retryAfterMsOf(failure?.error));
1551
+ if (abort.signal.aborted) {
1552
+ return;
1553
+ }
1554
+ }
1555
+ }
1556
+
1557
+ /**
1558
+ * backoff waits out one reconnect delay, drawn by {@link reconnectDelayMs} on the run's
1559
+ * {@link reconnectSchedule}: below a ceiling that doubles from AGENT_RECONNECT_BASE_MS to
1560
+ * RECONNECT_MAX_MS, so the wait stays inside a person's patience and runs dropped together
1561
+ * do not reopen together. Where the failure was a 429 or a 503 that named its wait (`namedMs`),
1562
+ * that wait replaces the draw, with up to a second drawn above it and the timer's ceiling over
1563
+ * it ({@link retryAfterDelayMs}), as SPEC §2 has `Retry-After` replace the schedule. It settles
1564
+ * on whichever comes first, the timer or the stream teardown's abort, and drops both hooks
1565
+ * either way: a run that reconnects many times must not accumulate listeners on the signal, nor
1566
+ * leave a timer holding the loop after the session is gone.
1567
+ */
1568
+ private backoff(attempts: number, signal: AbortSignal, namedMs?: number): Promise<void> {
1569
+ const delay =
1570
+ namedMs === undefined
1571
+ ? reconnectDelayMs(attempts, reconnectSchedule)
1572
+ : retryAfterDelayMs(namedMs);
1573
+
1574
+ return new Promise<void>((resolve) => {
1575
+ const settle = (): void => {
1576
+ clearTimeout(timer);
1577
+ signal.removeEventListener("abort", settle);
1578
+ resolve();
1579
+ };
1580
+
1581
+ const timer = setTimeout(settle, delay);
1582
+ signal.addEventListener("abort", settle, { once: true });
1583
+ });
1584
+ }
1585
+
1586
+ /**
1587
+ * consume opens one read of the run's events stream and settles when it
1588
+ * finishes, bridging the transport's AgentStreamHandlers callbacks to a single
1589
+ * promise run() can await. It reacts to each decoded frame and records its id as
1590
+ * the resume position when the frame arrives, taking it back when the frame's handling
1591
+ * throws; the transport has already validated every frame, so it trusts the typed
1592
+ * event. Unlike a per-turn drive it does NOT stop on
1593
+ * `awaiting-input` (the stream stays open for the next message). It resolves
1594
+ * with whether a terminal event ended the run and how many frames the stream
1595
+ * delivered, so the caller can decide between reconnecting and settling and
1596
+ * tell a productive open from a fruitless one, and with the failure when the
1597
+ * read failed. It never rejects, a transport that throws from the open included:
1598
+ * whether a failure ends the run is run()'s call.
1599
+ * A terminal the SESSION decides (handle returning true on `done`) tears the
1600
+ * subscription down here so no further frame is processed after the run is
1601
+ * over. A teardown's abort (a close, a dispose, or a start or resume that replaced
1602
+ * the run) settles the promise on its own (the transport fires no callback on a
1603
+ * deliberate abort), so run() unwinds without waiting on a dead stream.
1604
+ *
1605
+ * It is one closure on purpose. Every handler reads and writes this read's own settle
1606
+ * latch and frame count, and held as fields they would be the next read's to reach.
1607
+ */
1608
+ private consume(runId: string, signal: AbortSignal): Promise<ConsumeResult> {
1609
+ return new Promise<ConsumeResult>((resolve) => {
1610
+ let frames = 0;
1611
+ // The handlers (and the abort) can fire after a settle (a body close racing a
1612
+ // session terminal, a queued onFrame): this guard makes the first outcome win
1613
+ // and drops the rest, so the promise settles exactly once.
1614
+ let settled = false;
1615
+
1616
+ // This read's own hold on its subscription, released at most once whoever releases it:
1617
+ // its settle, or a teardown of the engine's stream while it is the read open. It is the
1618
+ // handle the engine holds as `unsubscribe` while the read is open.
1619
+ let unsubscribe: (() => void) | undefined;
1620
+ let released = false;
1621
+ const release = (): void => {
1622
+ if (released) {
1623
+ return;
1624
+ }
1625
+
1626
+ released = true;
1627
+ unsubscribe?.();
1628
+ };
1629
+
1630
+ // settle claims the one outcome this read gets, and reports whether it won. It drops
1631
+ // the abort hook on every path, not only the abort's own: an open that ends on its
1632
+ // own never fires it, and the signal outlives the open (the engine holds the last one
1633
+ // until the next open replaces it), so a hook left behind keeps this read's closure
1634
+ // alive for as long as the engine is. It releases this read's subscription and no
1635
+ // other: a start or a resume made from an observer callback may already have opened
1636
+ // the next read, whose handle the engine holds by then.
1637
+ const settle = (): boolean => {
1638
+ if (settled) {
1639
+ return false;
1640
+ }
1641
+
1642
+ settled = true;
1643
+ signal.removeEventListener("abort", onAbort);
1644
+ if (this.unsubscribe === release) {
1645
+ this.unsubscribe = null;
1646
+ }
1647
+ release();
1648
+
1649
+ return true;
1650
+ };
1651
+
1652
+ const finish = (ended: boolean, reconnect = false): void => {
1653
+ if (!settle()) {
1654
+ return;
1655
+ }
1656
+
1657
+ resolve({ ended, frames, reconnect });
1658
+ };
1659
+
1660
+ const fail = (error: unknown, transient: boolean): void => {
1661
+ if (!settle()) {
1662
+ return;
1663
+ }
1664
+
1665
+ resolve({ ended: false, failure: { error, transient }, frames });
1666
+ };
1667
+
1668
+ // A deliberate abort (a teardown; see above) fires no transport callback, so settle
1669
+ // here. run() reads abort.signal.aborted and returns, so the outcome is moot.
1670
+ const onAbort = (): void => finish(false);
1671
+
1672
+ if (signal.aborted) {
1673
+ finish(false);
1674
+
1675
+ return;
1676
+ }
1677
+
1678
+ signal.addEventListener("abort", onAbort, { once: true });
1679
+
1680
+ const handlers: AgentStreamHandlers = {
1681
+ onClose: (reason) => finish(reason === "terminal", reason === "reconnect"),
1682
+ onError: (error) => fail(error, isTransientStreamFault(error)),
1683
+ onFrame: async (frame) => {
1684
+ if (settled) {
1685
+ return;
1686
+ }
1687
+
1688
+ frames += 1;
1689
+ // The position moves when the frame arrives, ahead of its handling: a resume of the
1690
+ // run made from inside an observer callback reopens after the frame the host is being
1691
+ // handed, and is handed it once.
1692
+ const before = this.lastEventId;
1693
+ if (frame.id !== undefined) {
1694
+ this.lastEventId = frame.id;
1695
+ }
1696
+
1697
+ let ended: boolean;
1698
+ try {
1699
+ ended = await this.handle(runId, frame.event);
1700
+ } catch (error) {
1701
+ // A frame whose handling threw was not delivered, and a reopen past it would lose
1702
+ // it: the position goes back to where it was when the frame arrived. A read that
1703
+ // settled while the frame was handled is stale and the position is the newer read's,
1704
+ // and a position something else moved since (a later frame, a record that carries
1705
+ // none) is past this frame already.
1706
+ if (frame.id !== undefined && !settled && this.lastEventId === frame.id) {
1707
+ this.lastEventId = before;
1708
+ }
1709
+
1710
+ // The engine's own fault (a host seam that threw), never the connection's,
1711
+ // so it is final whatever it looks like. Settled here rather than rethrown:
1712
+ // settling releases the subscription, which stops the read, and a transport
1713
+ // that surfaces a throwing onFrame would only report the same fault twice.
1714
+ fail(error, false);
1715
+
1716
+ return;
1717
+ }
1718
+
1719
+ if (ended) {
1720
+ // A session-decided terminal: settle FIRST so the intended outcome wins
1721
+ // the settle race, THEN tear the read down. teardownStream() aborts
1722
+ // synchronously, which trips the abort listener's finish({ ended: false });
1723
+ // settling first makes that a no-op and keeps run()'s ended branch honest
1724
+ // rather than resting on the abort.signal.aborted backstop. Tearing the
1725
+ // subscription down here (not waiting for the transport's own close)
1726
+ // guarantees no further frame reaches handle after the run ends. The stream
1727
+ // torn down is this read's alone: a start or a resume made while the frame was
1728
+ // handled owns the one the engine holds now.
1729
+ finish(true);
1730
+ if (this.streamAbort?.signal === signal) {
1731
+ this.teardownStream();
1732
+ }
1733
+ }
1734
+ },
1735
+ // A record that names a position and carries no frame moves the cursor too, so a
1736
+ // reopen resumes from the last position the stream named. A settled read's report is
1737
+ // stale, like its frames.
1738
+ onLastEventId: (lastEventId) => {
1739
+ if (!settled) {
1740
+ this.lastEventId = lastEventId;
1741
+ }
1742
+ },
1743
+ // A frame the transport skips, an event this build does not know or data it cannot read,
1744
+ // hands the run nothing and moves no position, and it is still a frame the stream
1745
+ // delivered: a stream saying one thing and then one this build skips has said two.
1746
+ onSkippedFrame: () => {
1747
+ if (!settled) {
1748
+ frames += 1;
1749
+ }
1750
+ },
1751
+ };
1752
+
1753
+ try {
1754
+ unsubscribe = this.config.transport.subscribe(runId, handlers, {
1755
+ lastEventId: this.lastEventId,
1756
+ signal,
1757
+ });
1758
+ } catch (error) {
1759
+ // A transport that throws from the open, where it should report through onError,
1760
+ // opened nothing. The same open throws the same way, so the failure is final, and
1761
+ // settling it here is what ends the read by run()'s rules: the state `ended` before
1762
+ // the rejection, and the abort hook dropped.
1763
+ fail(error, false);
1764
+
1765
+ return;
1766
+ }
1767
+ // A transport may settle the read from inside subscribe (a failure it reports at once),
1768
+ // before it has handed back the handle to release: the release it asked for runs here.
1769
+ if (released) {
1770
+ unsubscribe();
1771
+ } else {
1772
+ this.unsubscribe = release;
1773
+ }
1774
+ });
1775
+ }
1776
+
1777
+ /**
1778
+ * handle reacts to one event of the run `runId` names and reports whether the run
1779
+ * ended (so consume can stop). An active-turn event (streamed text, a tool call, a
1780
+ * confirm request) flips the lifecycle to `running`; a client tool-call is dispatched
1781
+ * through the bus and its result posted back; a confirm-required is routed through
1782
+ * the host gate and the decision posted back. Both answers go to `runId`, the run that
1783
+ * asked, even when a later start or resume replaced it while the tool ran or the host
1784
+ * decided. A tool-call or a confirm-required that {@link claimCall} refuses, one the
1785
+ * stream marks `settled` or one the run already handled, is dropped whole: it reaches
1786
+ * neither the bus, the gate nor the observer, and leaves the lifecycle as it is. An
1787
+ * `awaiting-input` event settles the turn to the `awaiting_input` state but
1788
+ * keeps the stream open (returns false); only a terminal `done` ends the run (returns
1789
+ * true).
1790
+ */
1791
+ private async handle(runId: string, event: AgentEvent): Promise<boolean> {
1792
+ switch (event.type) {
1793
+ case "message-delta":
1794
+ this.setState("running");
1795
+ this.tell((observer) => observer.onMessageDelta?.(event.text));
1796
+
1797
+ return false;
1798
+
1799
+ case "message":
1800
+ this.setState("running");
1801
+ this.tell((observer) => observer.onMessage?.(event.content, event.message_index));
1802
+
1803
+ return false;
1804
+
1805
+ case "tool-call":
1806
+ return this.handleToolCall(runId, event);
1807
+
1808
+ case "confirm-required":
1809
+ return this.handleConfirmRequired(runId, event);
1810
+
1811
+ case "budget-exhausted":
1812
+ // A budget ceiling is the run ending: surface the exhausted dimension tagged
1813
+ // with the `budget-exhausted` code so the host maps it to per-dimension
1814
+ // usage-limit copy rather than showing the raw reason. The run itself ends on
1815
+ // the `done` the gateway always sends next, which carries how it ended, so the
1816
+ // read goes on until that frame.
1817
+ this.tell((observer) => observer.onError?.(event.reason, "budget-exhausted"));
1818
+
1819
+ return false;
1820
+
1821
+ case "error":
1822
+ // A run error likewise: surface it and read on to the `done` behind it. The
1823
+ // host renders a localized message, not this raw string from the API: the `code`
1824
+ // (e.g. `rate-limited`) lets it pick specific copy, and a code it does not
1825
+ // know falls back to a generic message.
1826
+ this.tell((observer) => observer.onError?.(event.message, event.code));
1827
+
1828
+ return false;
1829
+
1830
+ case "checks-unmet":
1831
+ // The run answered while success criteria its retrieved skills promised
1832
+ // are not backed by the workspace. Published right before `awaiting-input`,
1833
+ // and the stream's awaited frame handling means the host's warning row
1834
+ // lands before the state flips. Informational, never terminal.
1835
+ this.tell((observer) => observer.onChecksUnmet?.(event.unmet));
1836
+
1837
+ return false;
1838
+
1839
+ case "awaiting-input":
1840
+ // The turn settled, but the run's stream stays open for the next
1841
+ // message: keep consuming rather than ending the run.
1842
+ this.setState("awaiting_input");
1843
+
1844
+ return false;
1845
+
1846
+ case "done":
1847
+ return this.handleDone(runId, event);
1848
+
1849
+ case "tool-result":
1850
+ return this.handleToolResult(event);
1851
+
1852
+ case "tool-abandoned":
1853
+ return this.handleToolAbandoned(event);
1854
+
1855
+ case "reconnect":
1856
+ // The end of the stream's credential is the read's to act on: the client's transport
1857
+ // closes the read on it as `reconnect` and hands it on to no one, and the run reads on
1858
+ // past the reopen. A transport of the host's own that hands it on has it dropped here.
1859
+ return false;
1860
+ }
1861
+ }
1862
+
1863
+ /**
1864
+ * handleToolCall runs one client tool call through the bus, reports it to the observer and
1865
+ * posts its result back into the run that asked. It answers false: a tool call never ends
1866
+ * the run.
1867
+ *
1868
+ * The call is running from its claim to its report. What the stream says of it meanwhile is
1869
+ * held ({@link holdWhileRunning}), and released when the handling throws before the report:
1870
+ * the engine has no report of its own then, and the stream's word settles the host's row.
1871
+ */
1872
+ private async handleToolCall(
1873
+ runId: string,
1874
+ event: Extract<AgentEvent, { type: "tool-call" }>,
1875
+ ): Promise<boolean> {
1876
+ // A call the stream marks settled, or one this run already dispatched, sent again:
1877
+ // see claimCall.
1878
+ if (!this.claimCall(event.tool_call_id, event.settled)) {
1879
+ return false;
1880
+ }
1881
+
1882
+ this.runningCalls.set(event.tool_call_id, null);
1883
+ try {
1884
+ return await this.runToolCall(runId, event);
1885
+ } catch (error) {
1886
+ this.releaseHeldWord(runId, event.tool_call_id);
1887
+
1888
+ throw error;
1889
+ }
1890
+ }
1891
+
1892
+ /**
1893
+ * releaseHeldWord takes a call out of the running set and delivers what the stream said of it
1894
+ * while it ran, when it said anything. A call the engine reported is out of the set already,
1895
+ * and so is every call of a run the engine no longer holds the memory of: both release
1896
+ * nothing.
1897
+ */
1898
+ private releaseHeldWord(runId: string, toolCallId: string): void {
1899
+ if (this.handledRunId !== runId) {
1900
+ return;
1901
+ }
1902
+
1903
+ const held = this.runningCalls.get(toolCallId);
1904
+ this.runningCalls.delete(toolCallId);
1905
+ held?.();
1906
+ }
1907
+
1908
+ /**
1909
+ * holdWhileRunning keeps what the stream says of a call the engine is still running, as the
1910
+ * report it would have made, and answers whether it did. The first word is the one kept: a
1911
+ * failed `tool-result` follows the `tool-abandoned` of a call the run gave up on.
1912
+ */
1913
+ private holdWhileRunning(toolCallId: string, report: () => void): boolean {
1914
+ if (!this.runningCalls.has(toolCallId)) {
1915
+ return false;
1916
+ }
1917
+
1918
+ if (this.runningCalls.get(toolCallId) === null) {
1919
+ this.runningCalls.set(toolCallId, report);
1920
+ }
1921
+
1922
+ return true;
1923
+ }
1924
+
1925
+ /** runToolCall is the handling of a claimed client tool call: see {@link handleToolCall}. */
1926
+ private async runToolCall(
1927
+ runId: string,
1928
+ event: Extract<AgentEvent, { type: "tool-call" }>,
1929
+ ): Promise<boolean> {
1930
+ const { bus, ctx, recoveryFor, stateDelta } = this.config;
1931
+
1932
+ this.setState("running");
1933
+ // Surface the tool by name as the dispatch begins so the host's activity
1934
+ // line reflects the action while it runs, not only once it settles.
1935
+ this.tell((observer) => observer.onToolActivity?.(event.name));
1936
+ // The structured twin: the host reads the call's name, raw input and id to
1937
+ // derive the workspace target it is about to touch (e.g. the segment an
1938
+ // edit will lock) and to record the call as a durable activity row keyed by
1939
+ // its id, which the display summary cannot carry. Fired before the bus
1940
+ // dispatch so the host can arm ahead of the mutation.
1941
+ this.tell((observer) => observer.onToolCall?.(event.name, event.input, event.tool_call_id));
1942
+ // The model only emits tool calls; the bus is the sole executor and
1943
+ // re-validates the unknown input against the tool's own schema before
1944
+ // running it. The name and input arrive as a runtime string/unknown off the
1945
+ // wire, so this goes through dispatchFromModel, the type-unchecked entry
1946
+ // whose runtime gate (unknown-tool, capability, Zod) matches the typed
1947
+ // dispatch, plus the one gate only a model-issued call needs: a tool
1948
+ // withheld from the manifest is refused rather than run. The outcome is
1949
+ // posted straight back so the run can react.
1950
+ // Read the workspace immediately either side of the dispatch, so the
1951
+ // result can carry what the call MOVED rather than leaving the model to
1952
+ // infer it from a prose summary. Both reads are synchronous: an await
1953
+ // between them would let an unrelated update land in the gap and be
1954
+ // reported as this tool's doing.
1955
+ const before = stateDelta?.capture(ctx);
1956
+ const result = await bus.dispatchFromModel(ctx, event.name, event.input);
1957
+ const moved =
1958
+ stateDelta && before !== undefined
1959
+ ? stateDelta.diff(before, stateDelta.capture(ctx))
1960
+ : undefined;
1961
+ // A successful dispatch with a human summary refines the activity line to
1962
+ // what the tool actually did; a failure or summary-less success leaves the
1963
+ // tool name in place rather than blanking the line mid-run.
1964
+ if (result.ok && result.summary) {
1965
+ this.tell((observer) => observer.onToolActivity?.(result.summary));
1966
+ }
1967
+
1968
+ // Settle the activity row the host recorded for this call from the bus
1969
+ // result: the summary on success, an `abandoned` marker when the USER declined
1970
+ // the in-chat confirmation, and the failure text for every other rejection. A
1971
+ // decline is a choice, not a failure: it settles dimmed like a dropped server
1972
+ // tool rather than the red error a genuine rejection shows. The bus tags a
1973
+ // denied confirmation with the stable `confirmation-denied` code (ctx.confirm
1974
+ // returned false), which is what distinguishes it from a handler error. The
1975
+ // gateway post below makes no such distinction: a decline is posted as a
1976
+ // failing tool-result.
1977
+ // Resolved once and used twice: the host renders it beside the failure, and
1978
+ // the gateway post below carries it to the model. Two lookups could not
1979
+ // disagree today, but they would be free to later.
1980
+ const recovery = result.ok ? undefined : recoveryFor?.(event.name, result.code);
1981
+
1982
+ // The engine makes this call's report here, so from this line on whatever the stream says
1983
+ // about the call is dropped. The id is recorded at the report and no earlier: a call whose
1984
+ // handling threw before it (the bus or the state delta) was reported by nobody,
1985
+ // and the stream's `tool-abandoned` or `tool-result` is then what settles the host's row.
1986
+ // A read hands over its next frame only once this one is handled, so the read that carried
1987
+ // the call states nothing about it ahead of the report.
1988
+ //
1989
+ // And only while the memory is still this run's: a start, or a resume of another run, made
1990
+ // while the tool ran has emptied it for the run the engine reads now, in which the same id
1991
+ // is another call's.
1992
+ if (this.handledRunId === runId) {
1993
+ this.dispatchedCalls.add(event.tool_call_id);
1994
+ // The call stops running here, and what the stream said of it while it ran goes with it.
1995
+ this.runningCalls.delete(event.tool_call_id);
1996
+ }
1997
+
1998
+ this.tell((observer) =>
1999
+ observer.onToolResult?.(
2000
+ event.tool_call_id,
2001
+ result.ok
2002
+ ? { status: "ok", summary: result.summary }
2003
+ : result.code === "confirmation-denied"
2004
+ ? { status: "abandoned" }
2005
+ : { error: result.error, recovery, status: "error" },
2006
+ ),
2007
+ );
2008
+
2009
+ // On success forward the tool's STRUCTURED data alongside the summary,
2010
+ // trimmed to a cap by collection rather than by bytes. A read tool's
2011
+ // whole purpose is the payload (a terrain grid, the studio snapshot,
2012
+ // the overlay catalog), and a model that receives only "sampled 144
2013
+ // cells" cannot reason about the ground it just measured, nor choose the
2014
+ // next tool from what it found. The summary stays as the display line.
2015
+ //
2016
+ // On failure forward the bus's machine-readable `code` alongside the
2017
+ // error so the run branches on the KIND of failure (a never-retry
2018
+ // invalid-input vs a retryable conflict) rather than parsing the human
2019
+ // string; an unclassified failure omits it, and success omits it entirely.
2020
+ // The code is narrowed to the wire's vocabulary first: the bus classifies a
2021
+ // few human-only pointer failures the stream has no member for.
2022
+ await this.postInput(runId, {
2023
+ ok: result.ok,
2024
+ tool_call_id: event.tool_call_id,
2025
+ type: "tool-result",
2026
+ ...(result.ok
2027
+ ? { result: buildToolResultPayload(result.summary, result.data, moved) }
2028
+ : {
2029
+ code: toWireErrorCode(result.code),
2030
+ error: result.error,
2031
+ // What to do about THIS failure of THIS tool, when the playbook
2032
+ // says. It rides the failing result rather than the prompt so it
2033
+ // costs nothing for the codes that never fire.
2034
+ ...(recovery ? { recovery } : {}),
2035
+ }),
2036
+ });
2037
+
2038
+ return false;
2039
+ }
2040
+
2041
+ /**
2042
+ * handleConfirmRequired puts a server tool's confirmation to the host gate and posts the
2043
+ * decision back into the run that asked. It answers false: a confirmation never ends the
2044
+ * run.
2045
+ */
2046
+ private async handleConfirmRequired(
2047
+ runId: string,
2048
+ event: Extract<AgentEvent, { type: "confirm-required" }>,
2049
+ ): Promise<boolean> {
2050
+ // A confirmation the stream marks settled, or one this run already answered, sent
2051
+ // again: see claimCall.
2052
+ if (!this.claimCall(event.tool_call_id, event.settled)) {
2053
+ return false;
2054
+ }
2055
+
2056
+ this.setState("running");
2057
+ // A destructive SERVER tool runs on the gateway, so the bus cannot gate
2058
+ // it; the host confirm modal does, and the decision is signalled back. The
2059
+ // host composes the prompt from the tool's name, which is all that crosses
2060
+ // this seam.
2061
+ const approved = await this.config.confirmServerTool({ name: event.name });
2062
+ await this.postInput(runId, {
2063
+ approved,
2064
+ tool_call_id: event.tool_call_id,
2065
+ type: "confirm",
2066
+ });
2067
+
2068
+ return false;
2069
+ }
2070
+
2071
+ /**
2072
+ * handleDone reports how the run ended and ends the read, unless a start or a resume made
2073
+ * from the callback has already replaced it. It answers true: `done` is the one terminal.
2074
+ */
2075
+ private handleDone(runId: string, event: Extract<AgentEvent, { type: "done" }>): boolean {
2076
+ // The one terminal: it is the last frame on the stream, and the only one that
2077
+ // knows how the run ended. The run is finished, so it is owed no close, and that is
2078
+ // settled before onRunEnd: a start the host makes from the callback leaves this run
2079
+ // behind without posting one. That start or resume has replaced this read by the time
2080
+ // the callback returns: the state is then the new run's, and ending it here would stop
2081
+ // that read before it opened.
2082
+ if (this.unfinishedRunId === runId) {
2083
+ this.unfinishedRunId = null;
2084
+ }
2085
+
2086
+ const generation = this.readGeneration;
2087
+ this.tell((observer) => observer.onRunEnd?.(event.reason));
2088
+ if (generation === this.readGeneration) {
2089
+ this.setState("ended");
2090
+ }
2091
+
2092
+ return true;
2093
+ }
2094
+
2095
+ /**
2096
+ * handleToolResult reports a call's outcome as the stream states it, unless the call is one
2097
+ * the engine ran and reported itself. It answers false.
2098
+ */
2099
+ private handleToolResult(event: Extract<AgentEvent, { type: "tool-result" }>): boolean {
2100
+ // The gateway's echo of the answer the engine posted for a call it ran: the bus
2101
+ // result already reported that call, so the echo is dropped whole.
2102
+ if (this.dispatchedCalls.has(event.tool_call_id)) {
2103
+ return false;
2104
+ }
2105
+
2106
+ // A call's outcome as the run recorded it, with nothing to dispatch and nothing
2107
+ // to post back. It is a server tool's (the gateway runs it), or the outcome
2108
+ // replayed behind a call the stream marks settled (the engine drops that call's
2109
+ // frame). A summary is live activity, so it goes to the host's activity line when
2110
+ // present, and the host settles the activity row keyed by the call id. A server
2111
+ // tool and a settled call report no call, so the host may hold no running row for
2112
+ // the id and appends an already-settled one instead.
2113
+ const report = (): void => {
2114
+ const { summary } = event;
2115
+ if (summary) {
2116
+ this.tell((observer) => observer.onToolActivity?.(summary));
2117
+ }
2118
+
2119
+ this.tell((observer) =>
2120
+ observer.onToolResult?.(
2121
+ event.tool_call_id,
2122
+ event.ok
2123
+ ? { status: "ok", summary: event.summary }
2124
+ : { error: event.error, status: "error" },
2125
+ ),
2126
+ );
2127
+ };
2128
+
2129
+ // A call the engine is still running is reported from the bus result when the tool
2130
+ // settles, so the stream's word waits for that: see holdWhileRunning.
2131
+ if (!this.holdWhileRunning(event.tool_call_id, report)) {
2132
+ report();
2133
+ }
2134
+
2135
+ return false;
2136
+ }
2137
+
2138
+ /**
2139
+ * handleToolAbandoned reports a call the run gave up on, unless the call is one the engine
2140
+ * ran and reported itself. It answers false.
2141
+ */
2142
+ private handleToolAbandoned(event: Extract<AgentEvent, { type: "tool-abandoned" }>): boolean {
2143
+ // The run gave up on a call the engine ran and reported: the abandonment crossed
2144
+ // the engine's answer, and the bus result stays the one report.
2145
+ if (this.dispatchedCalls.has(event.tool_call_id)) {
2146
+ return false;
2147
+ }
2148
+
2149
+ // A call the run gave up on: a client call nobody answered or a server tool's
2150
+ // confirmation nobody decided, in this read or in the replay behind a call the
2151
+ // stream marks settled. There is nothing to dispatch and nothing to post back,
2152
+ // and the host settles the activity row for the call id so a recorded call never
2153
+ // hangs as still running.
2154
+ //
2155
+ // The reason rides along because a timeout and a closed run are
2156
+ // indistinguishable to someone watching and completely different in meaning: a
2157
+ // timeout means nothing came back, while a closed run is the user's own doing
2158
+ // and is not a fault. A gateway that sends no reason leaves it absent, and the
2159
+ // row settles with none.
2160
+ const report = (): void => {
2161
+ this.tell((observer) =>
2162
+ observer.onToolResult?.(event.tool_call_id, {
2163
+ abandonedReason: event.reason,
2164
+ status: "abandoned",
2165
+ }),
2166
+ );
2167
+ };
2168
+
2169
+ // A call the engine is still running is reported from the bus result when the tool
2170
+ // settles, so the stream's word waits for that: see holdWhileRunning.
2171
+ if (!this.holdWhileRunning(event.tool_call_id, report)) {
2172
+ report();
2173
+ }
2174
+
2175
+ return false;
2176
+ }
2177
+
2178
+ /**
2179
+ * setState records the lifecycle transition and notifies the observer only on
2180
+ * an actual change, so the host does not re-render on a no-op.
2181
+ *
2182
+ * Every report, a no-op included, drops the hold the sends being posted have on `running`:
2183
+ * whatever speaks here (a frame, a close, a new run) owns the state from then on. A send
2184
+ * reports its own `running` through {@link reportState}, which keeps the hold.
2185
+ */
2186
+ private setState(next: AgentEngineState): void {
2187
+ this.sendHold = null;
2188
+ this.reportState(next);
2189
+ }
2190
+
2191
+ /**
2192
+ * reportState is {@link setState} without the drop of the hold, for the one report that is
2193
+ * the hold's own: the `running` of a send.
2194
+ *
2195
+ * The observer is told a state that differs from the one it was told last, which is the
2196
+ * engine's own state but while a start readies its run ({@link beginRun}).
2197
+ */
2198
+ private reportState(next: AgentEngineState): void {
2199
+ this.state = next;
2200
+ if (this.reported === next) {
2201
+ return;
2202
+ }
2203
+
2204
+ this.reported = next;
2205
+ this.tell((observer) => observer.onStateChange?.(next));
2206
+ }
2207
+
2208
+ /**
2209
+ * tell hands the observer one report. The observer answers nothing the run waits on, so a
2210
+ * callback that throws is a defect of the host's own rendering and never the run's: its fault
2211
+ * reaches the program through {@link surfaceFault}, and the read goes on.
2212
+ */
2213
+ private tell(report: (observer: AgentObserver) => void): void {
2214
+ try {
2215
+ report(this.config.observer);
2216
+ } catch (fault) {
2217
+ surfaceFault(fault);
2218
+ }
2219
+ }
2220
+
2221
+ /**
2222
+ * postInput sends one input frame back into the run `runId` names, the run that asked
2223
+ * for it, and reports a failure as a fault in the conversation instead of throwing.
2224
+ *
2225
+ * The catch is the point. `start()` ends with `await this.run(runId)`, so the whole
2226
+ * consume loop lives inside the start promise, and an unguarded rejection here would
2227
+ * leave `handle()` as a fault of the engine's own: the read would end for good, and
2228
+ * `start()` would reject into the host's START error path. A network blip on turn
2229
+ * twelve would then render "could not start", clear the started guard and drop the run
2230
+ * id, so the still-alive gateway run could never be resumed and the model's call would
2231
+ * expire as `tool-abandoned` with the user told nothing true about why.
2232
+ *
2233
+ * Reporting and continuing is the right shape: the run is still open, the stream is
2234
+ * still readable, and the gateway abandons the unanswered call on its own timeout so
2235
+ * the model can replan. What is lost is one tool result, which is a turn-level fault,
2236
+ * not a session-level one. A run a later start or resume replaced has nobody reading
2237
+ * it, so a failure to answer it is dropped rather than reported into the run that
2238
+ * replaced it. So is a failure to answer a run the engine has stopped reading, after a
2239
+ * {@link close} or a {@link dispose}: the host ended that conversation, and an error line
2240
+ * under it would report a fault in a run nobody is in.
2241
+ *
2242
+ * The message is deliberately empty. A fetch rejection carries an English,
2243
+ * internal string, and the host resolves an empty message to its own localized
2244
+ * generic line, the same rule the run's other self-raised terminals follow.
2245
+ */
2246
+ private async postInput(runId: string, input: AgentInput): Promise<void> {
2247
+ try {
2248
+ await this.config.transport.sendInput(runId, input);
2249
+ } catch {
2250
+ if (this.currentRunId === runId && this.state !== "ended") {
2251
+ this.tell((observer) => observer.onError?.(""));
2252
+ }
2253
+ }
2254
+ }
2255
+ }