gemi 0.202.0 → 0.204.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 (306) hide show
  1. package/dist/ai/Agent.d.ts +30 -2
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentProvider.d.ts +5 -0
  4. package/dist/ai/AgentProvider.d.ts.map +1 -1
  5. package/dist/ai/Prompt.d.ts +11 -2
  6. package/dist/ai/Prompt.d.ts.map +1 -1
  7. package/dist/ai/index.d.ts +3 -3
  8. package/dist/ai/index.d.ts.map +1 -1
  9. package/dist/ai/index.js +90 -55
  10. package/dist/ai/index.js.map +7 -17
  11. package/dist/ai/jobs/AgentJob.d.ts +180 -1
  12. package/dist/ai/jobs/AgentJob.d.ts.map +1 -1
  13. package/dist/ai/jobs/AgentJobStore.d.ts +69 -5
  14. package/dist/ai/jobs/AgentJobStore.d.ts.map +1 -1
  15. package/dist/ai/jobs/DatabaseAgentJobStore.d.ts +21 -1
  16. package/dist/ai/jobs/DatabaseAgentJobStore.d.ts.map +1 -1
  17. package/dist/ai/jobs/contextBlock.d.ts +1 -1
  18. package/dist/ai/jobs/contextBlock.d.ts.map +1 -1
  19. package/dist/ai/jobs/index.d.ts +2 -2
  20. package/dist/ai/jobs/index.d.ts.map +1 -1
  21. package/dist/ai/jobs/overlay.d.ts +1 -1
  22. package/dist/ai/jobs/overlay.d.ts.map +1 -1
  23. package/dist/ai/providers/request.d.ts +1 -0
  24. package/dist/ai/providers/request.d.ts.map +1 -1
  25. package/dist/ai/testing/Fingerprints.d.ts +106 -0
  26. package/dist/ai/testing/Fingerprints.d.ts.map +1 -0
  27. package/dist/ai/testing/RecordingProvider.d.ts +258 -0
  28. package/dist/ai/testing/RecordingProvider.d.ts.map +1 -0
  29. package/dist/ai/testing/index.d.ts +4 -0
  30. package/dist/ai/testing/index.d.ts.map +1 -0
  31. package/dist/ai/testing/index.js +6 -0
  32. package/dist/ai/testing/index.js.map +12 -0
  33. package/dist/ai/testing/pinClock.d.ts +19 -0
  34. package/dist/ai/testing/pinClock.d.ts.map +1 -0
  35. package/dist/ai/types.d.ts +6 -1
  36. package/dist/ai/types.d.ts.map +1 -1
  37. package/dist/app/index.js +2 -2
  38. package/dist/app/index.js.map +1 -1
  39. package/dist/bin/gemi.js.map +2 -2
  40. package/dist/bun/plugin.js +2 -2
  41. package/dist/bun/plugin.js.map +1 -1
  42. package/dist/bun/preload.js +2 -2
  43. package/dist/bun/preload.js.map +1 -1
  44. package/dist/{chunk-81m95se9.js → chunk-0hfzzb3k.js} +3 -3
  45. package/dist/{chunk-81m95se9.js.map → chunk-0hfzzb3k.js.map} +1 -1
  46. package/dist/chunk-0pgk811s.js +4 -0
  47. package/dist/{chunk-9kmh038f.js.map → chunk-0pgk811s.js.map} +2 -2
  48. package/dist/{chunk-fdcay8np.js → chunk-0shq2d31.js} +2 -2
  49. package/dist/{chunk-fdcay8np.js.map → chunk-0shq2d31.js.map} +1 -1
  50. package/dist/{chunk-mzqhn72h.js → chunk-0t1d9s34.js} +3 -3
  51. package/dist/{chunk-mzqhn72h.js.map → chunk-0t1d9s34.js.map} +1 -1
  52. package/dist/{chunk-zmj4fj4n.js → chunk-1e82gfk9.js} +3 -3
  53. package/dist/{chunk-zmj4fj4n.js.map → chunk-1e82gfk9.js.map} +1 -1
  54. package/dist/{chunk-781k79x8.js → chunk-1kehwa3s.js} +1 -1
  55. package/dist/chunk-1x60thpm.js +8 -0
  56. package/dist/chunk-1x60thpm.js.map +19 -0
  57. package/dist/{chunk-by0afyps.js → chunk-2ngdhbz7.js} +2 -2
  58. package/dist/{chunk-by0afyps.js.map → chunk-2ngdhbz7.js.map} +1 -1
  59. package/dist/{chunk-mddazdpt.js → chunk-2t1eyzvq.js} +2 -2
  60. package/dist/{chunk-mddazdpt.js.map → chunk-2t1eyzvq.js.map} +1 -1
  61. package/dist/{chunk-ewknbs3b.js → chunk-39hed4yr.js} +3 -3
  62. package/dist/{chunk-ewknbs3b.js.map → chunk-39hed4yr.js.map} +1 -1
  63. package/dist/{chunk-87f4gan9.js → chunk-3gkxnfef.js} +3 -3
  64. package/dist/{chunk-87f4gan9.js.map → chunk-3gkxnfef.js.map} +1 -1
  65. package/dist/{chunk-9k3axdsb.js → chunk-3xzhbkya.js} +3 -3
  66. package/dist/{chunk-9k3axdsb.js.map → chunk-3xzhbkya.js.map} +1 -1
  67. package/dist/{chunk-bz3527wx.js → chunk-4c0rb2ng.js} +2 -2
  68. package/dist/{chunk-bz3527wx.js.map → chunk-4c0rb2ng.js.map} +1 -1
  69. package/dist/chunk-4ex4s616.js +4 -0
  70. package/dist/{chunk-qz7v6271.js.map → chunk-4ex4s616.js.map} +2 -2
  71. package/dist/{chunk-t4z6rkvw.js → chunk-4m8t67px.js} +2 -2
  72. package/dist/{chunk-t4z6rkvw.js.map → chunk-4m8t67px.js.map} +1 -1
  73. package/dist/{chunk-65r1ne8r.js → chunk-4v5c4mes.js} +2 -2
  74. package/dist/{chunk-65r1ne8r.js.map → chunk-4v5c4mes.js.map} +1 -1
  75. package/dist/{chunk-3cd30c7k.js → chunk-5gvc03cv.js} +3 -3
  76. package/dist/{chunk-3cd30c7k.js.map → chunk-5gvc03cv.js.map} +1 -1
  77. package/dist/{chunk-6eywgbfz.js → chunk-5km0np8s.js} +2 -2
  78. package/dist/{chunk-6eywgbfz.js.map → chunk-5km0np8s.js.map} +1 -1
  79. package/dist/{chunk-bs6nxaqa.js → chunk-6bfj0mbp.js} +3 -3
  80. package/dist/{chunk-bs6nxaqa.js.map → chunk-6bfj0mbp.js.map} +1 -1
  81. package/dist/chunk-6g1xac70.js +7 -0
  82. package/dist/chunk-6g1xac70.js.map +10 -0
  83. package/dist/{chunk-evaeb75q.js → chunk-6w6q9mxe.js} +3 -3
  84. package/dist/{chunk-evaeb75q.js.map → chunk-6w6q9mxe.js.map} +2 -2
  85. package/dist/chunk-733e6v7b.js +6 -0
  86. package/dist/{chunk-hd8gymeg.js.map → chunk-733e6v7b.js.map} +2 -2
  87. package/dist/{chunk-7xwr52d8.js → chunk-77x9vxht.js} +3 -3
  88. package/dist/{chunk-7xwr52d8.js.map → chunk-77x9vxht.js.map} +1 -1
  89. package/dist/{chunk-7gmkcgq0.js → chunk-7gxmf9rg.js} +2 -2
  90. package/dist/{chunk-7gmkcgq0.js.map → chunk-7gxmf9rg.js.map} +1 -1
  91. package/dist/{chunk-ha4er085.js → chunk-8jfnn7v6.js} +2 -2
  92. package/dist/{chunk-ha4er085.js.map → chunk-8jfnn7v6.js.map} +1 -1
  93. package/dist/{chunk-zhmc2jm4.js → chunk-8pw4zjnx.js} +1 -1
  94. package/dist/{chunk-sg78cmd1.js → chunk-9bjggtdt.js} +2 -2
  95. package/dist/{chunk-sg78cmd1.js.map → chunk-9bjggtdt.js.map} +1 -1
  96. package/dist/{chunk-xhky6kyf.js → chunk-9hqnecjt.js} +2 -2
  97. package/dist/{chunk-xhky6kyf.js.map → chunk-9hqnecjt.js.map} +1 -1
  98. package/dist/{chunk-s0z61m9j.js → chunk-9m7c4mws.js} +2 -2
  99. package/dist/{chunk-s0z61m9j.js.map → chunk-9m7c4mws.js.map} +1 -1
  100. package/dist/{chunk-agc5bqdt.js → chunk-b1mdan5a.js} +2 -2
  101. package/dist/{chunk-agc5bqdt.js.map → chunk-b1mdan5a.js.map} +1 -1
  102. package/dist/chunk-b9czfrxm.js +24 -0
  103. package/dist/{chunk-dh8jqx0k.js.map → chunk-b9czfrxm.js.map} +2 -2
  104. package/dist/{chunk-7txst143.js → chunk-bq4pgzcd.js} +2 -2
  105. package/dist/{chunk-7txst143.js.map → chunk-bq4pgzcd.js.map} +1 -1
  106. package/dist/chunk-c7nbzryd.js +9 -0
  107. package/dist/chunk-c7nbzryd.js.map +10 -0
  108. package/dist/{chunk-y0gaw9ez.js → chunk-cdgnwzwf.js} +2 -2
  109. package/dist/{chunk-y0gaw9ez.js.map → chunk-cdgnwzwf.js.map} +1 -1
  110. package/dist/chunk-cf7xc02m.js +5 -0
  111. package/dist/{chunk-ccpp45dm.js.map → chunk-cf7xc02m.js.map} +1 -1
  112. package/dist/{chunk-cwxjqfkx.js → chunk-cq7hk8v9.js} +2 -2
  113. package/dist/{chunk-cwxjqfkx.js.map → chunk-cq7hk8v9.js.map} +1 -1
  114. package/dist/{chunk-8m9kgynj.js → chunk-crqbzfd5.js} +2 -2
  115. package/dist/{chunk-8m9kgynj.js.map → chunk-crqbzfd5.js.map} +1 -1
  116. package/dist/{chunk-4jbrazr4.js → chunk-d3k38gk1.js} +3 -3
  117. package/dist/{chunk-4jbrazr4.js.map → chunk-d3k38gk1.js.map} +1 -1
  118. package/dist/{chunk-wn9e8bjn.js → chunk-d5d3a8bm.js} +3 -3
  119. package/dist/{chunk-wn9e8bjn.js.map → chunk-d5d3a8bm.js.map} +1 -1
  120. package/dist/chunk-d7kknkmq.js +13 -0
  121. package/dist/{chunk-j43hftgw.js.map → chunk-d7kknkmq.js.map} +3 -4
  122. package/dist/{chunk-bcfcwbp4.js → chunk-dk1xxtgk.js} +2 -2
  123. package/dist/{chunk-bcfcwbp4.js.map → chunk-dk1xxtgk.js.map} +1 -1
  124. package/dist/{chunk-n7bz2283.js → chunk-e3ehv27z.js} +3 -3
  125. package/dist/{chunk-n7bz2283.js.map → chunk-e3ehv27z.js.map} +1 -1
  126. package/dist/{chunk-phszs9ea.js → chunk-e5mqjren.js} +4 -4
  127. package/dist/{chunk-phszs9ea.js.map → chunk-e5mqjren.js.map} +2 -2
  128. package/dist/{chunk-yxge0cem.js → chunk-efnerp0c.js} +2 -2
  129. package/dist/{chunk-yxge0cem.js.map → chunk-efnerp0c.js.map} +1 -1
  130. package/dist/{chunk-5zjw41cv.js → chunk-ek0dvbck.js} +3 -3
  131. package/dist/{chunk-5zjw41cv.js.map → chunk-ek0dvbck.js.map} +1 -1
  132. package/dist/{chunk-b2n74m40.js → chunk-ezvtkbp9.js} +2 -2
  133. package/dist/{chunk-b2n74m40.js.map → chunk-ezvtkbp9.js.map} +1 -1
  134. package/dist/{chunk-vqq0z746.js → chunk-f52maa9b.js} +2 -2
  135. package/dist/{chunk-vqq0z746.js.map → chunk-f52maa9b.js.map} +1 -1
  136. package/dist/{chunk-a9cztxee.js → chunk-f9c8bnzx.js} +3 -3
  137. package/dist/{chunk-a9cztxee.js.map → chunk-f9c8bnzx.js.map} +2 -2
  138. package/dist/{chunk-bwg7genv.js → chunk-fq5b1k4n.js} +2 -2
  139. package/dist/{chunk-bwg7genv.js.map → chunk-fq5b1k4n.js.map} +1 -1
  140. package/dist/{chunk-tbt2j0rf.js → chunk-gc9g7c4p.js} +3 -3
  141. package/dist/{chunk-tbt2j0rf.js.map → chunk-gc9g7c4p.js.map} +1 -1
  142. package/dist/{chunk-x41vw44z.js → chunk-jeq8wvj6.js} +2 -2
  143. package/dist/{chunk-x41vw44z.js.map → chunk-jeq8wvj6.js.map} +1 -1
  144. package/dist/{chunk-bxxd1awv.js → chunk-jma5d7zd.js} +3 -3
  145. package/dist/{chunk-bxxd1awv.js.map → chunk-jma5d7zd.js.map} +1 -1
  146. package/dist/{chunk-zgg2xsxp.js → chunk-jmsfkzav.js} +2 -2
  147. package/dist/{chunk-zgg2xsxp.js.map → chunk-jmsfkzav.js.map} +1 -1
  148. package/dist/chunk-js9rm7g0.js +4 -0
  149. package/dist/{chunk-2n98hczh.js.map → chunk-js9rm7g0.js.map} +2 -2
  150. package/dist/{chunk-y9ktwyrx.js → chunk-k1gt7fgy.js} +3 -3
  151. package/dist/{chunk-y9ktwyrx.js.map → chunk-k1gt7fgy.js.map} +1 -1
  152. package/dist/{chunk-t0qs2q9j.js → chunk-k62338g2.js} +2 -2
  153. package/dist/{chunk-t0qs2q9j.js.map → chunk-k62338g2.js.map} +1 -1
  154. package/dist/{chunk-0a5png2z.js → chunk-k9882kqg.js} +2 -2
  155. package/dist/{chunk-0a5png2z.js.map → chunk-k9882kqg.js.map} +1 -1
  156. package/dist/{chunk-drqv10sv.js → chunk-n26atakz.js} +3 -3
  157. package/dist/{chunk-drqv10sv.js.map → chunk-n26atakz.js.map} +1 -1
  158. package/dist/{chunk-wxcbfqkd.js → chunk-n3kg99yw.js} +3 -3
  159. package/dist/{chunk-wxcbfqkd.js.map → chunk-n3kg99yw.js.map} +1 -1
  160. package/dist/{chunk-a2ybf4jf.js → chunk-n5k42dh7.js} +3 -3
  161. package/dist/{chunk-a2ybf4jf.js.map → chunk-n5k42dh7.js.map} +1 -1
  162. package/dist/chunk-p2nqksdq.js +10 -0
  163. package/dist/{chunk-e9w2yzd2.js.map → chunk-p2nqksdq.js.map} +2 -2
  164. package/dist/{chunk-mvd4mc8p.js → chunk-p9pwskv6.js} +2 -2
  165. package/dist/{chunk-mvd4mc8p.js.map → chunk-p9pwskv6.js.map} +1 -1
  166. package/dist/{chunk-h1fqgz82.js → chunk-phvvxv1a.js} +3 -3
  167. package/dist/{chunk-h1fqgz82.js.map → chunk-phvvxv1a.js.map} +1 -1
  168. package/dist/chunk-pq15dt8j.js +46 -0
  169. package/dist/chunk-pq15dt8j.js.map +27 -0
  170. package/dist/{chunk-a5fvqc4k.js → chunk-ptpzh61m.js} +3 -3
  171. package/dist/{chunk-a5fvqc4k.js.map → chunk-ptpzh61m.js.map} +1 -1
  172. package/dist/{chunk-mq82r0qp.js → chunk-qcrj4t72.js} +3 -3
  173. package/dist/{chunk-mq82r0qp.js.map → chunk-qcrj4t72.js.map} +1 -1
  174. package/dist/{chunk-e3bwytc2.js → chunk-re9ac4tc.js} +27 -27
  175. package/dist/{chunk-e3bwytc2.js.map → chunk-re9ac4tc.js.map} +7 -6
  176. package/dist/{chunk-7881fdej.js → chunk-rr8bzm6k.js} +2 -2
  177. package/dist/{chunk-7881fdej.js.map → chunk-rr8bzm6k.js.map} +1 -1
  178. package/dist/{chunk-h7h8ra65.js → chunk-s5hdrpam.js} +3 -3
  179. package/dist/{chunk-h7h8ra65.js.map → chunk-s5hdrpam.js.map} +1 -1
  180. package/dist/{chunk-ptbrbp80.js → chunk-s6bq91cm.js} +2 -2
  181. package/dist/{chunk-ptbrbp80.js.map → chunk-s6bq91cm.js.map} +1 -1
  182. package/dist/{chunk-5msb5ev6.js → chunk-s6wj8e56.js} +2 -2
  183. package/dist/{chunk-5msb5ev6.js.map → chunk-s6wj8e56.js.map} +2 -2
  184. package/dist/{chunk-sw7c95nh.js → chunk-vsd5h2d9.js} +3 -3
  185. package/dist/{chunk-sw7c95nh.js.map → chunk-vsd5h2d9.js.map} +1 -1
  186. package/dist/{chunk-c8041bgj.js → chunk-w3mc696j.js} +2 -2
  187. package/dist/{chunk-c8041bgj.js.map → chunk-w3mc696j.js.map} +1 -1
  188. package/dist/{chunk-2816nz5e.js → chunk-wn4j741t.js} +2 -2
  189. package/dist/{chunk-2816nz5e.js.map → chunk-wn4j741t.js.map} +1 -1
  190. package/dist/{chunk-hra8evrw.js → chunk-wxyxnbh6.js} +4 -4
  191. package/dist/{chunk-hra8evrw.js.map → chunk-wxyxnbh6.js.map} +1 -1
  192. package/dist/{chunk-m3nhdg9v.js → chunk-x244kqcc.js} +2 -2
  193. package/dist/{chunk-m3nhdg9v.js.map → chunk-x244kqcc.js.map} +1 -1
  194. package/dist/chunk-x26jb60f.js +4 -0
  195. package/dist/{chunk-p96z3yb6.js.map → chunk-x26jb60f.js.map} +2 -2
  196. package/dist/{chunk-xzt117g6.js → chunk-xvk6aqd7.js} +3 -3
  197. package/dist/{chunk-xzt117g6.js.map → chunk-xvk6aqd7.js.map} +1 -1
  198. package/dist/chunk-xwqdh388.js +5 -0
  199. package/dist/chunk-xwqdh388.js.map +13 -0
  200. package/dist/{chunk-mndcq5z1.js → chunk-y45whafz.js} +2 -2
  201. package/dist/{chunk-mndcq5z1.js.map → chunk-y45whafz.js.map} +1 -1
  202. package/dist/{chunk-vpqzzrkn.js → chunk-y5kfqq4f.js} +2 -2
  203. package/dist/{chunk-vpqzzrkn.js.map → chunk-y5kfqq4f.js.map} +1 -1
  204. package/dist/chunk-ybcdxrqx.js +4 -0
  205. package/dist/{chunk-07qjfj2c.js.map → chunk-ybcdxrqx.js.map} +2 -2
  206. package/dist/{chunk-a6hac7pd.js → chunk-yrbvfda9.js} +1 -1
  207. package/dist/{chunk-h2ysbsax.js → chunk-yykrvrpt.js} +1 -1
  208. package/dist/{chunk-6a7kp98d.js → chunk-zk1vwwv6.js} +2 -2
  209. package/dist/{chunk-6a7kp98d.js.map → chunk-zk1vwwv6.js.map} +1 -1
  210. package/dist/chunks/{RealtimeClient-BnNSz8AK.js → RealtimeClient-CLXePUcE.js} +2 -2
  211. package/dist/chunks/{RealtimeClient-BnNSz8AK.js.map → RealtimeClient-CLXePUcE.js.map} +1 -1
  212. package/dist/chunks/{ThemeProvider-CoQ-vnvy.js → ThemeProvider-COjYIalw.js} +74 -1273
  213. package/dist/chunks/ThemeProvider-COjYIalw.js.map +1 -0
  214. package/dist/chunks/{fetchFileRequest-Bhp0oJ0T.js → fetchFileRequest-BaufNZpI.js} +2 -2
  215. package/dist/chunks/{fetchFileRequest-Bhp0oJ0T.js.map → fetchFileRequest-BaufNZpI.js.map} +1 -1
  216. package/dist/chunks/{live-Dt8sq9W4.js → live-Dz_rk7fm.js} +4 -15
  217. package/dist/chunks/{live-Dt8sq9W4.js.map → live-Dz_rk7fm.js.map} +1 -1
  218. package/dist/chunks/{mutationExtras-ChOGPZlY.js → mutationExtras-DtSw6BcX.js} +2 -2
  219. package/dist/chunks/{mutationExtras-ChOGPZlY.js.map → mutationExtras-DtSw6BcX.js.map} +1 -1
  220. package/dist/chunks/rolldown-runtime-D7D4PA-g.js +13 -0
  221. package/dist/chunks/{subscriptionStream-DDl_H-QM.js → subscriptionStream-CqhJOfPn.js} +2 -2
  222. package/dist/chunks/{subscriptionStream-DDl_H-QM.js.map → subscriptionStream-CqhJOfPn.js.map} +1 -1
  223. package/dist/chunks/urlpattern-polyfill-Cc7YrzJf.js +913 -0
  224. package/dist/chunks/urlpattern-polyfill-Cc7YrzJf.js.map +1 -0
  225. package/dist/client/ClientRouter.d.ts +1 -1
  226. package/dist/client/ClientRouter.d.ts.map +1 -1
  227. package/dist/client/ClientRouterContext.d.ts +1 -1
  228. package/dist/client/ClientRouterContext.d.ts.map +1 -1
  229. package/dist/client/browserHistory.d.ts +13 -0
  230. package/dist/client/browserHistory.d.ts.map +1 -0
  231. package/dist/client/index.js +9 -6
  232. package/dist/client/index.js.map +1 -1
  233. package/dist/client/init.d.ts.map +1 -1
  234. package/dist/client/scrollRestoration.d.ts +1 -1
  235. package/dist/client/scrollRestoration.d.ts.map +1 -1
  236. package/dist/client/urlPattern.d.ts +30 -0
  237. package/dist/client/urlPattern.d.ts.map +1 -0
  238. package/dist/config/index.js +1 -1
  239. package/dist/console/run.js +2 -2
  240. package/dist/console/run.js.map +1 -1
  241. package/dist/container/index.js +2 -2
  242. package/dist/container/index.js.map +1 -1
  243. package/dist/database/index.js +2 -2
  244. package/dist/database/index.js.map +1 -1
  245. package/dist/email/index.js +2 -2
  246. package/dist/email/index.js.map +1 -1
  247. package/dist/facades/DB.d.ts +10 -0
  248. package/dist/facades/DB.d.ts.map +1 -1
  249. package/dist/facades/index.js +2 -2
  250. package/dist/facades/index.js.map +1 -1
  251. package/dist/foundation/index.js +2 -2
  252. package/dist/foundation/index.js.map +1 -1
  253. package/dist/http/index.js +2 -2
  254. package/dist/http/index.js.map +1 -1
  255. package/dist/i18n/dictionaryRuntime.js +2 -2
  256. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  257. package/dist/i18n/index.js +2 -2
  258. package/dist/i18n/index.js.map +2 -2
  259. package/dist/kernel/index.js +2 -2
  260. package/dist/kernel/index.js.map +2 -2
  261. package/dist/orm/Model.d.ts.map +1 -1
  262. package/dist/orm/context.d.ts +54 -0
  263. package/dist/orm/context.d.ts.map +1 -1
  264. package/dist/orm/index.d.ts +1 -1
  265. package/dist/orm/index.d.ts.map +1 -1
  266. package/dist/orm/index.js +4 -4
  267. package/dist/orm/index.js.map +3 -3
  268. package/dist/probe/index.js +2 -2
  269. package/dist/probe/index.js.map +1 -1
  270. package/dist/server/index.js +2 -2
  271. package/dist/server/index.js.map +1 -1
  272. package/dist/services/index.js +2 -2
  273. package/dist/services/index.js.map +2 -2
  274. package/dist/services/queue/work.js +2 -2
  275. package/dist/services/queue/work.js.map +1 -1
  276. package/dist/services/router/ViewRouteDispatcher.d.ts +1 -0
  277. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  278. package/dist/stats/route-table.js +1 -1
  279. package/dist/support/index.js +2 -2
  280. package/dist/support/index.js.map +1 -1
  281. package/dist/testing/index.d.ts +1 -0
  282. package/dist/testing/index.d.ts.map +1 -1
  283. package/dist/testing/index.js +234 -2
  284. package/dist/testing/index.js.map +1 -1
  285. package/dist/vitest/index.js +2 -2
  286. package/dist/vitest/index.js.map +1 -1
  287. package/package.json +2 -1
  288. package/dist/chunk-07qjfj2c.js +0 -4
  289. package/dist/chunk-2n98hczh.js +0 -4
  290. package/dist/chunk-64hxqsqx.js +0 -9
  291. package/dist/chunk-64hxqsqx.js.map +0 -10
  292. package/dist/chunk-9kmh038f.js +0 -4
  293. package/dist/chunk-ccpp45dm.js +0 -5
  294. package/dist/chunk-dh8jqx0k.js +0 -24
  295. package/dist/chunk-e9w2yzd2.js +0 -10
  296. package/dist/chunk-hd8gymeg.js +0 -6
  297. package/dist/chunk-j43hftgw.js +0 -15
  298. package/dist/chunk-p96z3yb6.js +0 -4
  299. package/dist/chunk-qz7v6271.js +0 -4
  300. package/dist/chunk-x2zw82xg.js +0 -46
  301. package/dist/chunk-x2zw82xg.js.map +0 -31
  302. package/dist/chunks/ThemeProvider-CoQ-vnvy.js.map +0 -1
  303. /package/dist/{chunk-781k79x8.js.map → chunk-1kehwa3s.js.map} +0 -0
  304. /package/dist/{chunk-zhmc2jm4.js.map → chunk-8pw4zjnx.js.map} +0 -0
  305. /package/dist/{chunk-a6hac7pd.js.map → chunk-yrbvfda9.js.map} +0 -0
  306. /package/dist/{chunk-h2ysbsax.js.map → chunk-yykrvrpt.js.map} +0 -0
package/dist/ai/index.js CHANGED
@@ -1,14 +1,24 @@
1
1
  // @bun
2
- import{$c as _0,Ac as T8,Cc as x8,Dc as y8,Ec as q8,Fc as b8,Gc as f8,Hc as v8,Ic as h8,Jc as g8,Kc as u8,Lc as c8,Mc as m8,Nc as p8,Pc as y,Qc as bJ,Rc as E9,Sc as j9,Tc as k9,Uc as v,Vc as T,Wb as V8,Wc as D8,Xb as fQ,Xc as B0,Yb as yQ,Yc as L0,Zb as H8,Zc as C0,_c as O0,ac as vJ,ad as M0,bc as j,bd as S0,cc as k,cd as A0,dd as R0,ec as X9,ed as E0,fc as J9,fd as j0,gc as HJ,gd as BJ,hc as N0,hd as k0,ic as l,id as pQ,jc as z8,jd as T0,kc as vQ,kd as lQ,lc as hQ,ld as x0,mc as gQ,md as I0,nc as n,nd as w0,oc as uQ,od as wJ,pc as tJ,pd as L$,qc as cQ,qd as q0,rc as mQ,rd as b0,sc as rJ,sd as dQ,tc as E8,td as f0,uc as j8,ud as y0,vd as v0,wc as k8,wd as h0,xc as c,xd as N$,yc as YQ,zc as VQ}from"../chunk-x2zw82xg.js";import{Pd as _8}from"../chunk-mndcq5z1.js";import"../chunk-a2ybf4jf.js";import{$i as xQ,Oh as jQ,Rh as TQ,ej as s$,fj as IQ,hj as wQ,ij as qQ,jj as bQ,oi as q9,pi as F0,qi as P0,ri as U0,si as b}from"../chunk-j43hftgw.js";import{kj as kQ,mj as sJ,nj as aJ}from"../chunk-vpqzzrkn.js";import{wj as p}from"../chunk-b2n74m40.js";import"../chunk-sg78cmd1.js";import"../chunk-mddazdpt.js";import"../chunk-bcfcwbp4.js";import{Ak as r,Ok as TJ,zk as t}from"../chunk-64hxqsqx.js";import"../chunk-t0qs2q9j.js";import"../chunk-t4z6rkvw.js";import{Bl as r9}from"../chunk-wxcbfqkd.js";import"../chunk-ha4er085.js";import"../chunk-xhky6kyf.js";import{Yl as W$}from"../chunk-65r1ne8r.js";import"../chunk-0a5png2z.js";import{existsSync as tQ,readdirSync as u0,readFileSync as L8}from"fs";import{isAbsolute as rQ,join as SJ,relative as eQ,sep as JZ}from"path";var C8="prompts.json",$Z=/\{\{>\s*([\w./-]+)\s*\}\}/g,U8=/\{\{(\w+)\}\}/g,QZ=/^[\w-]+(\/[\w-]+)*$/,N8={dir:"app/agents",shared:"prompts"},RJ={},Q$=new Map,AJ;function ZZ(){if(AJ===void 0){let J=SJ(W$(),"dist","server",C8);AJ=tQ(J)?JSON.parse(L8(J,"utf8")):null}return AJ??null}function WZ(J){return J.replace(/\r?\n$/,"")}function B8(){return RJ.cache??Bun.env.NODE_ENV==="production"}function KZ(J){if(!QZ.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let $=RJ.dir??N8.dir,Q=rQ($)?$:SJ(process.cwd(),$),Z=J.includes("/")?`${J}.md`:SJ(RJ.shared??N8.shared,`${J}.md`);return SJ(Q,Z)}function XZ(J){let $=KZ(J),Q=B8()?Q$.get($):void 0;if(Q!==void 0)return Q;let Z=Bun.env.NODE_ENV==="production";if(Z){let K=ZZ()?.[eQ(W$(),$).split(JZ).join("/")];if(K!==void 0)return K}let W;try{W=WZ(L8($,"utf8"))}catch(K){if(K.code==="ENOENT"){let X=Z?` or in dist/server/${C8}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${$}${X}).`)}throw K}if(B8())Q$.set($,W);return W}function Z$(J,$){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return XZ(J).replace($Z,(Q,Z)=>Z$(Z,[...$,J]))}class O8{static configure(J){RJ={...J},Q$.clear(),AJ=void 0}static render(J,$={}){return Z$(J,[]).replace(U8,(Q,Z)=>{if(!Object.hasOwn($,Z))throw Error(`The prompt "${J}" has no value for {{${Z}}}.`);return String($[Z])})}static placeholders(J){let $=[...Z$(J,[]).matchAll(U8)].map((Q)=>Q[1]);return[...new Set($)]}}class K$ extends _8{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await c.sweep({limit:100})===100);}}var EJ=20;function S8(J,$){if($<=0||J.length===0)return null;let Q=(K,X)=>X.createdAt-K.createdAt||(K.id<X.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>K.state==="running").sort(Q),...J.filter((K)=>K.state!=="running").sort(Q)].slice(0,$).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="running")X.push(`running since ${X$(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${X$(K.settledAt??K.updatedAt)}`);else{let Y=K.error?`${K.error.code}: ${M8(K.error.message,200)}`:"failed";X.push(`failed at ${X$(K.settledAt??K.updatedAt)} (${Y})`)}if(K.summary!==void 0)X.push(`summary: ${M8(JSON.stringify(K.summary),300)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
3
- `)}function X$(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function M8(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}class Y${table;sql;dialect;connection;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of GZ(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return TJ(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=this.q(),Q=this.clock($);await $`
4
- INSERT INTO ${this.name($)}
5
- (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
6
- orphaned, attachment_scope, created_at, updated_at, deadline_at)
7
- VALUES
8
- (${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
9
- ${J.owner}, ${J.job}, ${jJ(J.summary)}, 'running', 0, ${J.attachmentScope},
10
- ${Q}, ${Q}, ${Q} + ${this.ms($,J.deadlineMs)})
11
- `;let Z=await this.get(J.id);if(!Z)throw Error(`The background job ${J.id} was not found after it was written.`);return Z}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?G$(Q[0]):null}async listForThread(J,$={}){let Q=this.q(),Z=$.states===void 0?Q`1 = 1`:$.states.length===0?Q`1 = 0`:Q`state IN (${A8(Q,$.states)})`;return($.limit===void 0?await Q`
2
+ import{ca as bQ,da as yQ,ea as IQ,fa as Y6,ga as V6,ha as z6,ia as b$,ja as D6,ka as H6,la as Y$,ma as P6,na as F6}from"../chunk-1x60thpm.js";import{$c as a9,Bc as JQ,Cc as XQ,Dc as ZQ,Ec as WQ,Fc as KQ,Gc as GQ,Hc as YQ,Ic as VQ,Jc as zQ,Kc as DQ,Lc as HQ,Mc as PQ,Oc as q$,Pc as g9,Qc as u9,Rc as c9,Sc as m9,Tc as p9,Uc as l9,Vc as i9,Wc as d9,Xc as n9,Yc as o9,Zc as s9,_c as GJ,ad as lZ,bd as t9,cd as iZ,dd as r9,ed as e9,fd as J6,gc as I$,gd as SJ,hc as bZ,hd as eJ,ic as yZ,id as $6,jc as w$,jd as Q6,kd as dZ,ld as Z6,md as W6,nc as xQ,nd as K6,oc as AQ,od as X6,pc as ZJ,pd as G6,qc as h9,qd as tJ,rc as f,sc as a$,tc as t$,vc as r$,wc as y,xc as YZ,yc as VZ,zc as e$}from"../chunk-pq15dt8j.js";import{Dd as g,Ed as f$,Hd as vZ,Id as hZ,Jd as gZ,Kd as wJ,Ld as uZ,Md as yJ,Nd as cZ,Od as mZ,Pd as vJ,Qd as pZ,Vd as G$,Wd as o,ud as hQ,vd as A,wd as k}from"../chunk-xwqdh388.js";import{le as l$}from"../chunk-y45whafz.js";import"../chunk-n5k42dh7.js";import{Bj as wZ,Cj as fZ,Dj as qZ,Mi as j,ki as kZ,ni as jZ,tj as xZ,yj as C$,zj as IZ}from"../chunk-d7kknkmq.js";import{Ej as TZ,Gj as qJ,Hj as bJ}from"../chunk-y5kfqq4f.js";import{Qj as h}from"../chunk-ezvtkbp9.js";import{Sj as b9,Tj as y9,Uj as v9}from"../chunk-6g1xac70.js";import"../chunk-9bjggtdt.js";import"../chunk-2t1eyzvq.js";import"../chunk-dk1xxtgk.js";import{Xk as d,Yk as n,kl as _J}from"../chunk-c7nbzryd.js";import"../chunk-k62338g2.js";import"../chunk-4m8t67px.js";import{bm as rQ}from"../chunk-n3kg99yw.js";import"../chunk-8jfnn7v6.js";import"../chunk-9hqnecjt.js";import{ym as cJ}from"../chunk-4v5c4mes.js";import"../chunk-k9882kqg.js";import{existsSync as J8,readdirSync as O6,readFileSync as c$}from"fs";import{isAbsolute as $8,join as FJ,relative as Q8,sep as Z8}from"path";var m$="prompts.json",W8=/\{\{>\s*([\w./-]+)\s*\}\}/g,h$=/\{\{(\w+)\}\}/g,K8=/^[\w-]+(\/[\w-]+)*$/,g$={dir:"app/agents",shared:"prompts"},OJ={},gJ=new Map,NJ;function X8(){if(NJ===void 0){let J=FJ(cJ(),"dist","server",m$);NJ=J8(J)?JSON.parse(c$(J,"utf8")):null}return NJ??null}function G8(J){return J.replace(/\r?\n$/,"")}function u$(){return OJ.cache??Bun.env.NODE_ENV==="production"}function Y8(J,$){if(!K8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??OJ.dir??g$.dir,Z=$8(Q)?Q:FJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:FJ($.shared??OJ.shared??g$.shared,`${J}.md`);return FJ(Z,W)}function V8(J,$){let Q=Y8(J,$),Z=u$()?gJ.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let X=X8()?.[Q8(cJ(),Q).split(Z8).join("/")];if(X!==void 0)return X}let K;try{K=G8(c$(Q,"utf8"))}catch(X){if(X.code==="ENOENT"){let G=W?` or in dist/server/${m$}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw X}if(u$())gJ.set(Q,K);return K}function uJ(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return V8(J,Q).replace(W8,(Z,W)=>uJ(W,[...$,J],Q))}class p${static configure(J){OJ={...J},gJ.clear(),NJ=void 0}static render(J,$={},Q={}){return uJ(J,[],Q).replace(h$,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...uJ(J,[],$).matchAll(h$)].map((Z)=>Z[1]);return[...new Set(Q)]}}class mJ extends l${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await y.sweep({limit:100})===100);}}var UJ=20,z8=300,D8=200;function d$(J,$){if($<=0||J.length===0)return null;let Q=(K,X)=>X.createdAt-K.createdAt||(K.id<X.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>!f(K.state)).sort(Q),...J.filter((K)=>f(K.state)).sort(Q)].slice(0,$).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="waiting")X.push(`waiting for ${(K.after??[]).join(", ")} since ${CJ(K.createdAt)}`);else if(K.state==="running")X.push(`running since ${CJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${CJ(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${i$(K.error.message,D8)}`:"failed";X.push(`failed at ${CJ(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${i$(JSON.stringify(K.summary),z8)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
3
+ `)}function CJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function i$(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}var n$=["after_jobs","batch_key","queued","inbox","job_checkpoint"],o$=20;class pJ{table;sql;dialect;connection;later;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of H8(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return _J(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=J.after!==void 0||J.batch!==void 0||J.queued!==void 0;if($)await this.requireLaterColumns("A job with `after` or `batch`");let Q=this.q(),Z=this.clock(Q),W=J.state??"running";if($)await Q`
4
+ INSERT INTO ${this.name(Q)}
5
+ (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
6
+ orphaned, attachment_scope, created_at, updated_at, deadline_at,
7
+ after_jobs, batch_key, queued)
8
+ VALUES
9
+ (${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
10
+ ${J.owner}, ${J.job}, ${q(J.summary)}, ${W}, 0, ${J.attachmentScope},
11
+ ${Z}, ${Z}, ${Z} + ${this.ms(Q,J.deadlineMs)},
12
+ ${q(J.after)}, ${J.batch??null}, ${q(J.queued)})
13
+ `;else await Q`
14
+ INSERT INTO ${this.name(Q)}
15
+ (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
16
+ orphaned, attachment_scope, created_at, updated_at, deadline_at)
17
+ VALUES
18
+ (${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
19
+ ${J.owner}, ${J.job}, ${q(J.summary)}, ${W}, 0, ${J.attachmentScope},
20
+ ${Z}, ${Z}, ${Z} + ${this.ms(Q,J.deadlineMs)})
21
+ `;let K=await this.get(J.id);if(!K)throw Error(`The background job ${J.id} was not found after it was written.`);return K}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?i(Q[0]):null}async listForThread(J,$={}){let Q=this.q(),Z=$.states===void 0?Q`1 = 1`:$.states.length===0?Q`1 = 0`:Q`state IN (${s$(Q,$.states)})`;return($.limit===void 0?await Q`
12
22
  SELECT * FROM ${this.name(Q)}
13
23
  WHERE thread_id = ${J} AND ${Z}
14
24
  ORDER BY created_at DESC, id DESC
@@ -17,18 +27,36 @@ import{$c as _0,Ac as T8,Cc as x8,Dc as y8,Ec as q8,Fc as b8,Gc as f8,Hc as v8,I
17
27
  WHERE thread_id = ${J} AND ${Z}
18
28
  ORDER BY created_at DESC, id DESC
19
29
  LIMIT ${Math.max(0,Math.floor($.limit))}
20
- `).map(G$)}async transition(J,$,Q){if($.length===0)return!1;let Z=this.q(),W=this.clock(Z),K=[Z`updated_at = ${W}`];if(Q.state!==void 0)K.push(Z`state = ${Q.state}`);if("output"in Q)K.push(Z`output = ${jJ(Q.output)}`);if("error"in Q)K.push(Z`error = ${jJ(Q.error)}`);if("usage"in Q)K.push(Z`${this.column(Z,"usage")} = ${jJ(Q.usage)}`);if("orphaned"in Q)K.push(Z`orphaned = ${Q.orphaned?1:0}`);if(Q.state!==void 0&&Q.state!=="running")K.push(Q.settledAt!==void 0?Z`settled_at = COALESCE(settled_at, ${this.ms(Z,Q.settledAt)})`:Z`settled_at = COALESCE(settled_at, ${W})`);let X=K.reduce((V,G)=>Z`${V}, ${G}`),Y=await Z`
30
+ `).map(i)}async transition(J,$,Q){if($.length===0)return!1;if("checkpoint"in Q)await this.requireLaterColumns("`job.checkpoint`");let Z=this.q(),W=this.clock(Z),K=[Z`updated_at = ${W}`];if(Q.deadlineMs!==void 0)K.push(Z`deadline_at = ${W} + ${this.ms(Z,Q.deadlineMs)}`);if("checkpoint"in Q)K.push(Z`job_checkpoint = ${q(Q.checkpoint)}`);if(Q.state!==void 0)K.push(Z`state = ${Q.state}`);if("output"in Q)K.push(Z`output = ${q(Q.output)}`);if("error"in Q)K.push(Z`error = ${q(Q.error)}`);if("usage"in Q)K.push(Z`${this.column(Z,"usage")} = ${q(Q.usage)}`);if("orphaned"in Q)K.push(Z`orphaned = ${Q.orphaned?1:0}`);if(Q.state!==void 0&&f(Q.state))K.push(Q.settledAt!==void 0?Z`settled_at = COALESCE(settled_at, ${this.ms(Z,Q.settledAt)})`:Z`settled_at = COALESCE(settled_at, ${W})`);let X=K.reduce((V,Y)=>Z`${V}, ${Y}`),G=await Z`
21
31
  UPDATE ${this.name(Z)} SET ${X}
22
- WHERE id = ${J} AND state IN (${A8(Z,$)})
23
- `;return R8(Y)>0}async overdue(J,$){let Q=this.q();return(await Q`
32
+ WHERE id = ${J} AND state IN (${s$(Z,$)})
33
+ `;return LJ(G)>0}async overdue(J,$){let Q=this.q();return(await Q`
24
34
  SELECT * FROM ${this.name(Q)}
25
35
  WHERE state = 'running' AND deadline_at <= ${this.ms(Q,J)}
26
36
  ORDER BY deadline_at, id
27
37
  LIMIT ${Math.max(0,Math.floor($))}
28
- `).map(G$)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async prune(J){let $=this.q(),Q=await $`
38
+ `).map(i)}async waitingOn(J){if(!await this.columns())return[];let $=this.q();return(await $`
39
+ SELECT * FROM ${this.name($)}
40
+ WHERE state = 'waiting' AND after_jobs LIKE ${`%${JSON.stringify(J)}%`}
41
+ ORDER BY created_at, id
42
+ `).map(i).filter((Z)=>Z.after?.includes(J))}async waiting(J){let $=this.q();return(await $`
43
+ SELECT * FROM ${this.name($)}
44
+ WHERE state = 'waiting'
45
+ ORDER BY created_at, id
46
+ LIMIT ${Math.max(0,Math.floor(J))}
47
+ `).map(i)}async listBatch(J){if(!await this.columns())return[];let $=this.q();return(await $`
48
+ SELECT * FROM ${this.name($)} WHERE batch_key = ${J} ORDER BY created_at, id
49
+ `).map(i)}async appendInbox(J,$){await this.requireLaterColumns("`AgentJobs.message`");for(let Q=0;Q<o$;Q++){let Z=this.q(),[W]=await Z`
50
+ SELECT state, inbox FROM ${this.name(Z)} WHERE id = ${J}
51
+ `;if(!W||f(String(W.state)))return!1;let K=W.inbox===null||W.inbox===void 0?null:String(W.inbox),X=JSON.stringify([...I(K)??[],$]),G=await Z`
52
+ UPDATE ${this.name(Z)} SET inbox = ${X}, updated_at = ${this.clock(Z)}
53
+ WHERE id = ${J} AND state IN ('waiting', 'running') AND ${this.sameInbox(Z,K)}
54
+ `;if(LJ(G)>0)return!0}throw Error(`Could not add a message to background job ${J}: too many writers at once.`)}async takeInbox(J){if(!await this.columns())return[];for(let $=0;$<o$;$++){let Q=this.q(),[Z]=await Q`SELECT inbox FROM ${this.name(Q)} WHERE id = ${J}`;if(!Z||Z.inbox===null||Z.inbox===void 0)return[];let W=String(Z.inbox),K=await Q`
55
+ UPDATE ${this.name(Q)} SET inbox = NULL WHERE id = ${J} AND ${this.sameInbox(Q,W)}
56
+ `;if(LJ(K)>0)return I(W)??[]}throw Error(`Could not take the messages of background job ${J}: too many writers.`)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async prune(J){let $=this.q(),Q=await $`
29
57
  DELETE FROM ${this.name($)}
30
- WHERE state <> 'running' AND settled_at <= ${this.clock($)} - ${this.ms($,J)}
31
- `;return R8(Q)}joinable(){if(this.connection===void 0)return;let J=t();if(J===void 0||r()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function A8(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function jJ(J){return J===void 0?null:JSON.stringify(J)}function kJ(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function G$(J){let $=kJ(J.summary),Q=kJ(J.output),Z=kJ(J.error),W=kJ(J.usage);return{id:String(J.id),threadId:String(J.thread_id),runId:String(J.run_id),toolCallId:String(J.tool_call_id),toolName:String(J.tool_name),owner:J.owner===null||J.owner===void 0?null:String(J.owner),job:J.job===null||J.job===void 0?null:String(J.job),...$!==void 0?{summary:$}:{},state:String(J.state),...Q!==void 0?{output:Q}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number(J.orphaned)===1?{orphaned:!0}:{},attachmentScope:J.attachment_scope===null||J.attachment_scope===void 0?null:String(J.attachment_scope),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),deadlineAt:Number(J.deadline_at),...J.settled_at===null||J.settled_at===void 0?{}:{settledAt:Number(J.settled_at)}}}function R8(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function GZ(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
58
+ WHERE state IN ('ok', 'error') AND settled_at <= ${this.clock($)} - ${this.ms($,J)}
59
+ `;return LJ(Q)}columns(){return this.later??=(async()=>{try{return await this.sql.unsafe(`SELECT ${n$.join(", ")} FROM ${this.quoted(this.table)} WHERE 1 = 0`),!0}catch{return!1}})(),this.later}async requireLaterColumns(J){if(await this.columns())return;throw this.later=void 0,Error(`${J} needs the columns ${n$.join(", ")} on the ${this.table} table, which it does not have. Add them (see docs/ai-background-jobs.md and UPGRADE.md), or call createTable() on a new table.`)}sameInbox(J,$){return $===null?J`inbox IS NULL`:J`inbox = ${$}`}quoted(J){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${J}\``:`"${J}"`}joinable(){if(this.connection===void 0)return;let J=d();if(J===void 0||n()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function s$(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function q(J){return J===void 0?null:JSON.stringify(J)}function I(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function i(J){let $=I(J.summary),Q=I(J.output),Z=I(J.error),W=I(J.usage),K=I(J.after_jobs),X=I(J.queued),G=I(J.inbox),V=I(J.job_checkpoint);return{id:String(J.id),threadId:String(J.thread_id),runId:String(J.run_id),toolCallId:String(J.tool_call_id),toolName:String(J.tool_name),owner:J.owner===null||J.owner===void 0?null:String(J.owner),job:J.job===null||J.job===void 0?null:String(J.job),...$!==void 0?{summary:$}:{},state:String(J.state),...Q!==void 0?{output:Q}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number(J.orphaned)===1?{orphaned:!0}:{},attachmentScope:J.attachment_scope===null||J.attachment_scope===void 0?null:String(J.attachment_scope),...K!==void 0?{after:K}:{},...J.batch_key===null||J.batch_key===void 0?{}:{batch:String(J.batch_key)},...X!==void 0?{queued:X}:{},...G!==void 0&&G.length>0?{inbox:G}:{},...V!==void 0?{checkpoint:V}:{},createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),deadlineAt:Number(J.deadline_at),...J.settled_at===null||J.settled_at===void 0?{}:{settledAt:Number(J.settled_at)}}}function LJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function H8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
32
60
  \`id\` VARCHAR(191) NOT NULL,
33
61
  \`thread_id\` VARCHAR(191) NOT NULL,
34
62
  \`run_id\` VARCHAR(191) NOT NULL,
@@ -47,6 +75,11 @@ import{$c as _0,Ac as T8,Cc as x8,Dc as y8,Ec as q8,Fc as b8,Gc as f8,Hc as v8,I
47
75
  \`updated_at\` BIGINT NOT NULL,
48
76
  \`deadline_at\` BIGINT NOT NULL,
49
77
  \`settled_at\` BIGINT NULL,
78
+ \`after_jobs\` LONGTEXT NULL,
79
+ \`batch_key\` VARCHAR(191) NULL,
80
+ \`queued\` LONGTEXT NULL,
81
+ \`inbox\` LONGTEXT NULL,
82
+ \`job_checkpoint\` LONGTEXT NULL,
50
83
 
51
84
  INDEX \`${$}_thread_id_created_at_idx\`(\`thread_id\`, \`created_at\`),
52
85
  INDEX \`${$}_state_deadline_at_idx\`(\`state\`, \`deadline_at\`),
@@ -71,27 +104,32 @@ import{$c as _0,Ac as T8,Cc as x8,Dc as y8,Ec as q8,Fc as b8,Gc as f8,Hc as v8,I
71
104
  "created_at" BIGINT NOT NULL,
72
105
  "updated_at" BIGINT NOT NULL,
73
106
  "deadline_at" BIGINT NOT NULL,
74
- "settled_at" BIGINT${Z}
75
- )`,`CREATE INDEX IF NOT EXISTS "${$}_thread_id_created_at_idx" ON "${$}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_state_deadline_at_idx" ON "${$}"("state", "deadline_at")`]}var I8=4;class H${table;sql;dialect;connection;constructor(J,$={}){let Q=$.table??"gemi_agent_memories";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent memories table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of YZ(this.dialect,this.table))await this.sql.unsafe(J)}async list(J,$={}){if(J.length===0)return[];if($.kinds!==void 0&&$.kinds.length===0)return[];let Q=this.q(),Z=[Q`scope IN (${GJ(Q,J)})`];if($.kinds!==void 0)Z.push(Q`kind IN (${GJ(Q,$.kinds)})`);if(!$.includeExpired)Z.push(Q`(expires_at IS NULL OR expires_at > ${this.clock(Q)})`);if($.after!==void 0){let[V]=await Q`
107
+ "settled_at" BIGINT,
108
+ "after_jobs" TEXT,
109
+ "batch_key" TEXT,
110
+ "queued" TEXT,
111
+ "inbox" TEXT,
112
+ "job_checkpoint" TEXT${Z}
113
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_thread_id_created_at_idx" ON "${$}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_state_deadline_at_idx" ON "${$}"("state", "deadline_at")`]}var $Q=4;class iJ{table;sql;dialect;connection;constructor(J,$={}){let Q=$.table??"gemi_agent_memories";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent memories table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of P8(this.dialect,this.table))await this.sql.unsafe(J)}async list(J,$={}){if(J.length===0)return[];if($.kinds!==void 0&&$.kinds.length===0)return[];let Q=this.q(),Z=[Q`scope IN (${JJ(Q,J)})`];if($.kinds!==void 0)Z.push(Q`kind IN (${JJ(Q,$.kinds)})`);if(!$.includeExpired)Z.push(Q`(expires_at IS NULL OR expires_at > ${this.clock(Q)})`);if($.after!==void 0){let[V]=await Q`
76
114
  SELECT created_at, id FROM ${this.name(Q)}
77
- WHERE id = ${$.after} AND scope IN (${GJ(Q,J)})
78
- `;if(V){let G=this.ms(Q,Number(V.created_at));Z.push(Q`(created_at > ${G} OR (created_at = ${G} AND id > ${String(V.id)}))`)}}let W=Z.reduce((V,G)=>Q`${V} AND ${G}`),K=$.limit===void 0||$.tags!==void 0?void 0:Math.max(0,Math.floor($.limit)),Y=(K===void 0?await Q`
115
+ WHERE id = ${$.after} AND scope IN (${JJ(Q,J)})
116
+ `;if(V){let Y=this.ms(Q,Number(V.created_at));Z.push(Q`(created_at > ${Y} OR (created_at = ${Y} AND id > ${String(V.id)}))`)}}let W=Z.reduce((V,Y)=>Q`${V} AND ${Y}`),K=$.limit===void 0||$.tags!==void 0?void 0:Math.max(0,Math.floor($.limit)),G=(K===void 0?await Q`
79
117
  SELECT * FROM ${this.name(Q)} WHERE ${W}
80
118
  ORDER BY created_at, id
81
119
  `:await Q`
82
120
  SELECT * FROM ${this.name(Q)} WHERE ${W}
83
121
  ORDER BY created_at, id
84
122
  LIMIT ${K}
85
- `).map(V$);if($.tags!==void 0){if(Y=Y.filter((V)=>b8(V,$.tags)),$.limit!==void 0)Y=Y.slice(0,Math.max(0,Math.floor($.limit)))}return Y}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?V$(Q[0]):null}async upsert(J){let $=J.key??null;if($===null)return await this.insert(J,null),{record:await this.mustGet(J.id),action:"added"};for(let Q=1;;Q++){let Z=await this.atKey(J.scope,$);if(Z){if(f8(Z,J))return{record:Z,action:"unchanged"};let W=await this.update(Z.id,{kind:J.kind,content:J.content,tags:J.tags??[],pinned:J.pinned??!1,expiresAt:J.expiresAt??null},Z.version);if(W)return{record:W,action:"updated"}}else try{return await this.insert(J,$),{record:await this.mustGet(J.id),action:"added"}}catch(W){if(Q>=I8||!await this.atKey(J.scope,$))throw W}if(Q>=I8)throw Error(`The memory at "${$}" in ${J.scope} kept changing while it was being written.`)}}async update(J,$,Q){let Z=this.q(),W=[Z`version = version + 1`,Z`updated_at = ${this.clock(Z)}`];if($.kind!==void 0)W.push(Z`kind = ${$.kind}`);if($.content!==void 0)W.push(Z`content = ${$.content}`);if($.key!==void 0)W.push(Z`${this.column(Z,"key")} = ${$.key}`);if($.tags!==void 0)W.push(Z`tags = ${JSON.stringify($.tags)}`);if($.pinned!==void 0)W.push(Z`pinned = ${$.pinned?1:0}`);if($.expiresAt!==void 0)W.push($.expiresAt===null?Z`expires_at = NULL`:Z`expires_at = ${this.ms(Z,$.expiresAt)}`);let K=W.reduce((Y,V)=>Z`${Y}, ${V}`),X=Q===void 0?await Z`UPDATE ${this.name(Z)} SET ${K} WHERE id = ${J}`:await Z`
123
+ `).map(lJ);if($.tags!==void 0){if(G=G.filter((V)=>WQ(V,$.tags)),$.limit!==void 0)G=G.slice(0,Math.max(0,Math.floor($.limit)))}return G}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?lJ(Q[0]):null}async upsert(J){let $=J.key??null;if($===null)return await this.insert(J,null),{record:await this.mustGet(J.id),action:"added"};for(let Q=1;;Q++){let Z=await this.atKey(J.scope,$);if(Z){if(KQ(Z,J))return{record:Z,action:"unchanged"};let W=await this.update(Z.id,{kind:J.kind,content:J.content,tags:J.tags??[],pinned:J.pinned??!1,expiresAt:J.expiresAt??null},Z.version);if(W)return{record:W,action:"updated"}}else try{return await this.insert(J,$),{record:await this.mustGet(J.id),action:"added"}}catch(W){if(Q>=$Q||!await this.atKey(J.scope,$))throw W}if(Q>=$Q)throw Error(`The memory at "${$}" in ${J.scope} kept changing while it was being written.`)}}async update(J,$,Q){let Z=this.q(),W=[Z`version = version + 1`,Z`updated_at = ${this.clock(Z)}`];if($.kind!==void 0)W.push(Z`kind = ${$.kind}`);if($.content!==void 0)W.push(Z`content = ${$.content}`);if($.key!==void 0)W.push(Z`${this.column(Z,"key")} = ${$.key}`);if($.tags!==void 0)W.push(Z`tags = ${JSON.stringify($.tags)}`);if($.pinned!==void 0)W.push(Z`pinned = ${$.pinned?1:0}`);if($.expiresAt!==void 0)W.push($.expiresAt===null?Z`expires_at = NULL`:Z`expires_at = ${this.ms(Z,$.expiresAt)}`);let K=W.reduce((G,V)=>Z`${G}, ${V}`),X=Q===void 0?await Z`UPDATE ${this.name(Z)} SET ${K} WHERE id = ${J}`:await Z`
86
124
  UPDATE ${this.name(Z)} SET ${K}
87
125
  WHERE id = ${J} AND version = ${Math.floor(Q)}
88
- `;if(xJ(X)===0)return null;return this.get(J)}async delete(J){if(J.length===0)return 0;let $=this.q(),Q=await $`DELETE FROM ${this.name($)} WHERE id IN (${GJ($,[...new Set(J)])})`;return xJ(Q)}async deleteScope(J){let $=this.q();return xJ(await $`DELETE FROM ${this.name($)} WHERE scope = ${J}`)}async search(J,$,Q={}){let Z=await this.list(J,{kinds:Q.kinds,tags:Q.tags});return q8(Z,$,Q.limit)}async count(J){let $=this.q(),[Q]=await $`
126
+ `;if(BJ(X)===0)return null;return this.get(J)}async delete(J){if(J.length===0)return 0;let $=this.q(),Q=await $`DELETE FROM ${this.name($)} WHERE id IN (${JJ($,[...new Set(J)])})`;return BJ(Q)}async deleteScope(J){let $=this.q();return BJ(await $`DELETE FROM ${this.name($)} WHERE scope = ${J}`)}async search(J,$,Q={}){let Z=await this.list(J,{kinds:Q.kinds,tags:Q.tags});return ZQ(Z,$,Q.limit)}async count(J){let $=this.q(),[Q]=await $`
89
127
  SELECT COUNT(*) AS total FROM ${this.name($)}
90
128
  WHERE scope = ${J} AND (expires_at IS NULL OR expires_at > ${this.clock($)})
91
129
  `;return Number(Q?.total??0)}async touch(J,$){if(J.length===0)return;let Q=this.q();await Q`
92
130
  UPDATE ${this.name(Q)} SET last_used_at = ${this.ms(Q,$)}
93
- WHERE id IN (${GJ(Q,[...new Set(J)])})
94
- `}async prune(J){let $=this.q();return xJ(await $`DELETE FROM ${this.name($)} WHERE expires_at IS NOT NULL AND expires_at <= ${this.ms($,J)}`)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async insert(J,$){let Q=this.q(),Z=this.clock(Q),W=J.expiresAt===void 0||J.expiresAt===null?null:Math.max(0,Math.round(J.expiresAt));await Q`
131
+ WHERE id IN (${JJ(Q,[...new Set(J)])})
132
+ `}async prune(J){let $=this.q();return BJ(await $`DELETE FROM ${this.name($)} WHERE expires_at IS NOT NULL AND expires_at <= ${this.ms($,J)}`)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async insert(J,$){let Q=this.q(),Z=this.clock(Q),W=J.expiresAt===void 0||J.expiresAt===null?null:Math.max(0,Math.round(J.expiresAt));await Q`
95
133
  INSERT INTO ${this.name(Q)}
96
134
  (id, scope, kind, ${this.column(Q,"key")}, content, tags, pinned, source, version,
97
135
  created_at, updated_at, expires_at)
@@ -102,7 +140,7 @@ import{$c as _0,Ac as T8,Cc as x8,Dc as y8,Ec as q8,Fc as b8,Gc as f8,Hc as v8,I
102
140
  ${W===null?null:this.ms(Q,W)})
103
141
  `}async atKey(J,$){let Q=this.q(),Z=await Q`
104
142
  SELECT * FROM ${this.name(Q)} WHERE scope = ${J} AND ${this.column(Q,"key")} = ${$}
105
- `;return Z[0]?V$(Z[0]):null}async mustGet(J){let $=await this.get(J);if(!$)throw Error(`The memory ${J} was not found after it was written.`);return $}joinable(){if(this.connection===void 0)return;let J=t();if(J===void 0||r()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function GJ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function w8(J,$){if(J===null||J===void 0||J==="")return $;try{return JSON.parse(String(J))}catch{return $}}function V$(J){let $=w8(J.tags,[]);return{id:String(J.id),scope:String(J.scope),kind:String(J.kind),content:String(J.content),key:J.key===null||J.key===void 0?null:String(J.key),tags:Array.isArray($)?$.map(String):[],pinned:Number(J.pinned)===1,source:w8(J.source,{by:"app"}),version:Number(J.version),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),lastUsedAt:J.last_used_at===null||J.last_used_at===void 0?null:Number(J.last_used_at),expiresAt:J.expires_at===null||J.expires_at===void 0?null:Number(J.expires_at)}}function xJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function YZ(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
143
+ `;return Z[0]?lJ(Z[0]):null}async mustGet(J){let $=await this.get(J);if(!$)throw Error(`The memory ${J} was not found after it was written.`);return $}joinable(){if(this.connection===void 0)return;let J=d();if(J===void 0||n()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function JJ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function QQ(J,$){if(J===null||J===void 0||J==="")return $;try{return JSON.parse(String(J))}catch{return $}}function lJ(J){let $=QQ(J.tags,[]);return{id:String(J.id),scope:String(J.scope),kind:String(J.kind),content:String(J.content),key:J.key===null||J.key===void 0?null:String(J.key),tags:Array.isArray($)?$.map(String):[],pinned:Number(J.pinned)===1,source:QQ(J.source,{by:"app"}),version:Number(J.version),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),lastUsedAt:J.last_used_at===null||J.last_used_at===void 0?null:Number(J.last_used_at),expiresAt:J.expires_at===null||J.expires_at===void 0?null:Number(J.expires_at)}}function BJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function P8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
106
144
  \`id\` VARCHAR(191) NOT NULL,
107
145
  \`scope\` VARCHAR(191) NOT NULL,
108
146
  \`kind\` VARCHAR(191) NOT NULL,
@@ -139,11 +177,8 @@ import{$c as _0,Ac as T8,Cc as x8,Dc as y8,Ec as q8,Fc as b8,Gc as f8,Hc as v8,I
139
177
  "updated_at" BIGINT NOT NULL,
140
178
  "last_used_at" BIGINT,
141
179
  "expires_at" BIGINT${Z}
142
- )`,`CREATE INDEX IF NOT EXISTS "${$}_scope_kind_created_at_idx" ON "${$}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${$}_scope_key_key" ON "${$}"("scope", "key")`]}var d8={n:0,mean:0,stddev:0,low:null,high:null};function m(J){let $=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if(J<0.5)return Math.log(Math.PI/Math.sin(Math.PI*J))-m(1-J);J-=1;let Q=$[0],Z=J+7.5;for(let W=1;W<9;W++)Q+=$[W]/(J+W);return 0.5*Math.log(2*Math.PI)+(J+0.5)*Math.log(Z)-Z+Math.log(Q)}function l8(J,$,Q){let W=1,K=1-(J+$)*Q/(J+1);if(Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let X=K;for(let Y=1;Y<=300;Y++){let V=2*Y,G=Y*($-Y)*Q/((J+V-1)*(J+V));if(K=1+G*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+G/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(K=1/K,X*=K*W,G=-(J+Y)*(J+$+Y)*Q/((J+V)*(J+V+1)),K=1+G*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+G/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let H=K*W;if(X*=H,Math.abs(H-1)<0.00000000000001)break}return X}function VZ(J,$,Q){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(m($+Q)-m($)-m(Q)+$*Math.log(J)+Q*Math.log(1-J));return J<($+1)/($+Q+2)?Z*l8($,Q,J)/$:1-Z*l8(Q,$,1-J)/Q}function z$(J,$){return VZ($/($+J*J),$/2,0.5)}function HZ(J){if(!(J>0))return Number.POSITIVE_INFINITY;let $=1.959964,Q=2;while(z$(Q,J)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=($+Q)/2;if(z$(W,J)>0.05)$=W;else Q=W}return($+Q)/2}function zZ(J,$,Q,Z){let W=J+Q,K=$+Z,X=(H,D)=>m(H+1)-m(D+1)-m(H-D+1),Y=(H)=>Math.exp(X($,H)+X(Z,W-H)-X(K,W)),V=Y(J),G=0;for(let H=Math.max(0,W-Z);H<=Math.min($,W);H++){let D=Y(H);if(D<=V*1.0000001)G+=D}return Math.min(1,G)}function i8(J,$){if(J.length<2)return 0;let Q=J.reduce((W,K)=>W+(K-$)**2,0),Z=Math.sqrt(Q/(J.length-1));return Z<0.000000000001*Math.max(1,Math.abs($))?0:Z}function D$(J){let $=J.length;if($===0)return d8;let Q=J.map((Y)=>Y?1:0),Z=Q.reduce((Y,V)=>Y+V,0)/$,W=3.841458881296,K=(Z+W/(2*$))/(1+W/$),X=1.959964*Math.sqrt(Z*(1-Z)/$+W/(4*$*$))/(1+W/$);return{n:$,mean:Z,stddev:i8(Q,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function F$(J){let $=J.length;if($===0)return d8;let Q=J.reduce((K,X)=>K+X,0)/$,Z=i8(J,Q);if($<2||Z===0)return{n:$,mean:Q,stddev:Z,low:null,high:null};let W=HZ($-1)*Z/Math.sqrt($);return{n:$,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function YJ(J,$,Q){return{before:J.mean,after:$.mean,delta:$.mean-J.mean,p:Q,pAdjusted:Q,significant:!1}}function n8(J,$){if(J.n===0||$.n===0)return YJ(J,$,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return YJ(J,$,zZ(Q(J),J.n,Q($),$.n))}function o8(J,$){if(J.n<2||$.n<2)return YJ(J,$,null);let Q=J.stddev**2/J.n,Z=$.stddev**2/$.n,W=Math.sqrt(Q+Z);if(W===0)return YJ(J,$,null);let K=(Q+Z)**2/(Q**2/(J.n-1)+Z**2/($.n-1));return YJ(J,$,z$(($.mean-J.mean)/W,K))}function s8(J,$,Q){if(Q==="holm"){let Z=J.filter((K)=>K.p!==null).sort((K,X)=>K.p-X.p),W=0;Z.forEach((K,X)=>{W=Math.max(W,Math.min(1,K.p*(Z.length-X))),K.pAdjusted=W})}else for(let Z of J)Z.pAdjusted=Z.p;for(let Z of J)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<$&&Z.delta!==0}class IJ{name;cases;runs;concurrency;graders;pricing;task;constructor(J){this.name=J.name,this.cases=J.cases,this.runs=J.runs??1,this.concurrency=J.concurrency??1,this.task=J.task,this.graders=typeof J.graders==="function"?J.graders({judge:($)=>IJ.judge($)}):J.graders,this.pricing=J.pricing}static create(J){let $=`The eval "${J.name}"`;VJ(J.runs,$,"runs"),VJ(J.concurrency,$,"concurrency");let Q=new Set;for(let W of J.cases){if(Q.has(W.id))throw Error(`${$} has two cases with the id "${W.id}".`);Q.add(W.id)}let Z=new IJ(J);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")VJ(K.samples,`${$}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,$,Q={}){return $9(J,$,Q)}static format(J,$={}){return UZ(J,$)}async run(J={}){let $=`${this.name}.run`;VJ(J.runs,$,"runs"),VJ(J.concurrency,$,"concurrency");let Q=J.only?new Set(J.only):null;if(Q){let P=[...Q].filter((U)=>!this.cases.some((L)=>L.id===U));if(P.length>0)throw Error(`The eval "${this.name}" has no case ${P.map((U)=>`"${U}"`).join(", ")}.`)}let Z=J.runs??this.runs,W=Date.now(),K=new AbortController,X=J.signal?AbortSignal.any([J.signal,K.signal]):K.signal,Y=this.cases.filter((P)=>!Q||Q.has(P.id)),V={};for(let[P,U]of Object.entries(this.graders)){if(X.aborted)break;if(typeof U==="function"||U.kind!=="judge"||!U.calibration)continue;V[P]=await this.calibrate(U,X)}let G=Y.flatMap((P)=>Array.from({length:Z},(U,L)=>({test:P,run:L+1}))),H=Array.from({length:G.length}),D=0,z,F=async()=>{while(D<G.length&&!X.aborted){let P=D++,U=G[P],L=await this.sample(U.test,U.run,X,J.keepOutputs??!1);H[P]=L;try{J.onSample?.(L)}catch(_){z??={error:_},K.abort(_)}}},B=Math.min(J.concurrency??this.concurrency,G.length);if(await Promise.all(Array.from({length:B},F)),z)throw z.error;let N=H.filter((P)=>P!==void 0);return this.report(N,V,Z,new Date(W).toISOString(),Date.now()-W,{aborted:X.aborted||N.length<G.length,planned:Y.map((P)=>P.id)})}async sample(J,$,Q,Z){let W=Date.now(),K,X,Y=await HJ(async()=>{try{K=await this.task(J.input,{case:J,run:$,signal:Q})}catch(B){X=Z9(B)}}),V={},G=!1,H=await HJ(async()=>{if(X!==void 0)return;let B={case:J,input:J.input,run:$};for(let[N,P]of Object.entries(this.graders)){if(J.skip?.includes(N))continue;let U=await a8(P,K,B,Q);if(!U)continue;if(V[N]=U,!U.pass&&typeof P!=="function"&&P.gate)G=!0}}),D=Object.values(V).map((B)=>B.score),z=X===void 0&&D.length===0,F=this.pricing?P$(this.pricing,Y.byModel).cost+P$(this.pricing,H.byModel).cost:void 0;return{case:J.id,run:$,pass:X===void 0&&!z&&Object.values(V).every((B)=>B.pass),excluded:G||z,...z?{ungraded:!0}:{},score:X!==void 0||z?0:Q9(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:Y.usage,byModel:FZ(Y.byModel,H.byModel),judgeUsage:H.usage,...F!==void 0?{cost:F}:{},durationMs:Date.now()-W}}async calibrate(J,$){let Q=J.calibration,Z=[],W=0,K=await HJ(async()=>{for(let[V,G]of Q.examples.entries()){if($.aborted)break;let H=G.id??`example-${V+1}`,D={case:{id:H,input:G.input},input:G.input,run:0},z=await a8(J,G.output,D,$),F=z?.pass??!1;if(F===G.expected)W++;else Z.push({id:H,expected:G.expected,got:F,...z?.note?{note:z.note}:{}})}}),X=Q.examples.length,Y=X===0?1:W/X;return{n:X,agreement:Y,ok:Y>=(Q.minAgreement??0.8),disagreements:Z,usage:K.usage}}report(J,$,Q,Z,W,K){let X=new Set(Object.entries(this.graders).filter(([,z])=>typeof z!=="function"&&z.gate).map(([z])=>z)),Y={};for(let z of this.cases){let F=J.filter((B)=>B.case===z.id);if(F.length===0)continue;Y[z.id]={...t8(F),graders:r8(F,X)}}let V=j(),G=j(),H={};for(let z of J){V=k(V,z.usage),G=k(G,z.judgeUsage);for(let[F,B]of Object.entries(z.byModel))H[F]=k(H[F]??j(),B)}let D=this.pricing?P$(this.pricing,H):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:Q,aborted:K.aborted,planned:K.planned,samples:J,cases:Y,graders:r8(J,X),calibration:$,totals:{...t8(J),usage:V,judgeUsage:G,byModel:H,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(H)}}}}async function a8(J,$,Q,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return U$(await J($,Q),W);if(J.kind!=="judge")return U$(await J.check($,Q),W);return await DZ(J,$,Q,W,Z)}catch(K){return{pass:!1,score:0,error:Z9(K)}}}async function DZ(J,$,Q,Z,W){let K=await J.prompt($,Q),X=typeof K==="string"?{prompt:K}:K,Y=[];for(let D=0;D<(J.samples??1)&&!W.aborted;D++){let z=await N$({signal:W,provider:J.provider,...J.instructions!==void 0?{instructions:J.instructions}:{},...X,output:J.output,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},...J.maxOutputTokens!==void 0?{maxOutputTokens:J.maxOutputTokens}:{},...J.temperature!==void 0?{temperature:J.temperature}:{},logErrors:!1});if(!z.ok){Y.push({pass:!1,score:0,error:`The judge failed: ${z.error.message}`});continue}let F=U$(J.verdict(z.output,Q),Z);if(F)Y.push(F)}if(Y.length===0)return null;if(Y.length===1)return Y[0];let V=Y.filter((D)=>D.pass).length,G=Y.map((D)=>D.note??D.error).filter(Boolean),H=Y.map((D)=>D.error).filter(Boolean);return{pass:V*2>Y.length,score:Q9(Y.map((D)=>D.score)),...G.length>0?{note:G.join(" | ")}:{},...H.length===Y.length?{error:H.join(" | ")}:{}}}function U$(J,$){if(J===null||J===void 0)return null;if(typeof J==="boolean")return{pass:J,score:J?1:0};if(typeof J==="number"){if(!Number.isFinite(J))throw Error(`A grader answered the score ${J}.`);let Q=e8(J);return{pass:Q>=$,score:Q}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:e8(J.score),...J.note!==void 0?{note:J.note}:{}}}function t8(J){let $=J.filter((Q)=>!Q.excluded);return{samples:J.length,kept:$.length,passed:$.filter((Q)=>Q.pass).length,errors:J.filter((Q)=>Q.error!==void 0).length,passRate:D$($.map((Q)=>Q.pass)),score:F$($.map((Q)=>Q.score))}}function r8(J,$){let Q=J.filter((W)=>!W.excluded),Z=[...new Set(J.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let X=($.has(W)?J:Q).flatMap((Y)=>Y.grades[W]?[Y.grades[W]]:[]);return[W,{passRate:D$(X.map((Y)=>Y.pass)),score:F$(X.map((Y)=>Y.score))}]}))}function P$(J,$){let Q=0,Z=[];for(let[W,K]of Object.entries($)){let X=J9(J,W,K);if(X===void 0){Z.push(W);continue}Q+=X}return{cost:Q,unpriced:Z}}function FZ(...J){let $={};for(let Q of J)for(let[Z,W]of Object.entries(Q))$[Z]=k($[Z]??j(),W);return $}function $9(J,$,Q){for(let[P,U]of[["baseline",J],["current report",$]])if(U.aborted)throw Error(`Eval.compare: the ${P} for "${U.name}" was aborted (${U.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`);let Z=Q.alpha??0.05,W=Q.adjust??"holm",K=[],X=(P,U,L)=>{let _={label:P,passRate:n8(U.passRate,L.passRate),score:o8(U.score,L.score)};return K.push(_),{passRate:_.passRate,score:_.score}},Y=(P,U,L)=>Object.fromEntries(Object.keys(L).filter((_)=>(_ in U)).map((_)=>[_,X(`${P} ${_}`,U[_],L[_])])),V=(P,U)=>({fromCurrent:P.filter((L)=>!U.includes(L)),fromBaseline:U.filter((L)=>!P.includes(L))}),G=X("total",J.totals,$.totals),H=Y("case",J.cases,$.cases),D=Y("grader",J.graders,$.graders),z=K.flatMap((P)=>[P.passRate,P.score]);s8(z,Z,W);let F={cases:V([...new Set([...J.planned??[],...Object.keys(J.cases)])],[...new Set([...$.planned??[],...Object.keys($.cases)])]),graders:V(Object.keys(J.graders),Object.keys($.graders))},B=[...F.cases.fromCurrent.map((P)=>`case ${P}: in the baseline, missing from this report`),...F.graders.fromCurrent.map((P)=>`grader ${P}: in the baseline, missing from this report`)],N=[];for(let P of K)for(let[U,L]of[["pass rate",P.passRate],["score",P.score]]){if(!L.significant)continue;let _=`${P.label}: ${U} ${L.before.toFixed(2)} \u2192 ${L.after.toFixed(2)} (p = ${PZ(L.pAdjusted)})`;(L.delta<0?B:N).push(_)}return{totals:G,cases:H,graders:D,missing:F,comparisons:z.filter((P)=>P.p!==null).length,alpha:Z,adjust:W,regressions:B,improvements:N}}function PZ(J){return J<0.001?"<0.001":J.toFixed(3)}function UZ(J,$){let Q=$.baseline&&!$.baseline.aborted&&!J.aborted?$9($.baseline,J,$):void 0,{totals:Z}=J,W=[];if(W.push(`eval ${J.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(J.durationMs/1000).toFixed(1)}s)`),J.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let K=(G)=>{if(G.n===0)return"-";let H=G.mean.toFixed(2);if(G.low===null||G.high===null)return`${H} (${G.n===1?"n=1":"no spread"})`;return`${H} [${G.low.toFixed(2)}, ${G.high.toFixed(2)}]`},X=(G)=>G?` ${G.delta>=0?"+":""}${G.delta.toFixed(2)}${G.significant?"*":""}`:"",Y=(G,H)=>{let D=[0,1,2,3].map((F)=>Math.max(...[[G,"n","pass rate","score"],...H].map((B)=>B[F].length))),z=(F)=>F.map((B,N)=>B.padEnd(D[N])).join(" ").trimEnd();W.push("",z([G,"n","pass rate","score"]),...H.map(z))};Y("case",Object.entries(J.cases).map(([G,H])=>[G,`${H.kept}/${H.samples}`,K(H.passRate)+X(Q?.cases[G]?.passRate),K(H.score)+X(Q?.cases[G]?.score)])),Y("grader",Object.entries(J.graders).map(([G,H])=>[G,String(H.passRate.n),K(H.passRate)+X(Q?.graders[G]?.passRate),K(H.score)+X(Q?.graders[G]?.score)])),W.push("",`total pass rate ${K(Z.passRate)}${X(Q?.totals.passRate)} score ${K(Z.score)}${X(Q?.totals.score)}`);for(let[G,H]of Object.entries(J.calibration))W.push(`judge ${G}: agreement ${H.agreement.toFixed(2)} on ${H.n} examples${H.ok?"":" (BELOW minAgreement)"}`);let V=(G)=>`${G.inputTokens} in, ${G.outputTokens} out`;if(W.push(`tokens: task ${V(Z.usage)}; judges ${V(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),Q){W.push("",`* significant at ${Q.alpha} over ${Q.comparisons} tests (${Q.adjust==="holm"?"Holm-adjusted":"unadjusted"}; Fisher's exact for pass rates, Welch's t for scores)`);for(let G of Q.regressions)W.push(`regression: ${G}`);for(let G of Q.improvements)W.push(`improvement: ${G}`)}return W.join(`
143
- `)}function Q9(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function e8(J){return Math.min(1,Math.max(0,J))}function Z9(J){return J instanceof Error?J.message:String(J)}function VJ(J,$,Q){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${$} sets \`${Q}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var NZ=/^[A-Za-z0-9_-]{1,64}$/;function BZ(J,$){let Q=LZ($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((H)=>B$(J,H,Z));let K=Object.entries(Q.namespaces),X=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,D]of K){if(!NZ.test(H))throw Error(`toAgentTools: "${H}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!X.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let Y=new Map(K.map(([H])=>[H,[]])),V=[];for(let H of W){let D=K.find(([z])=>H.tags.includes(z))?.[0];if(D===void 0)V.push(B$(J,H,Z));else Y.get(D).push(B$(J,H,!1))}let G=[];for(let[H,D]of K){let z=Y.get(H);if(z.length===0)continue;G.push(L$.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...G,...V]}function LZ(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function B$(J,$,Q){if($.kind==="tool")return CZ(J,$,Q);return wJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Q,execute:(Z,W)=>{let K=p.getStore()?.req;if(!K)throw new l(`"${$.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return J.execute({kind:"local",req:K},$.name,Z,W)}})}function CZ(J,$,Q){let Z=J.nativeTool($.name);return wJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:J.nativeApproval($.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,K)=>{let X=p.getStore()?.req;return J.startNative(X?{kind:"local",req:X}:void 0,$.name,W,K)}})}function OZ(J){if(J==="auto")return;let $=/^(\d+)x(\d+)$/.exec(J);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let Q=Number($[1]),Z=Number($[2]);if(Q%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max(Q/Z,Z/Q)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function W9(J,$){if(J.size!==void 0)try{OZ(J.size)}catch(Q){throw Error(`${$}: ${Q.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let Q=J.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Q}.`)}}function K9(J,$){if(J instanceof File)return J;let Q=J.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([J],`${$}.${Z}`,{type:Q})}class C${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;W9(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new C$(J)}async generate(J){let $=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...$,signal:J.signal}))}async edit(J){let $=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...$,images:J.images.map((Q,Z)=>K9(Q,`image-${Z}`)),...J.mask?{mask:K9(J.mask,"mask")}:{},signal:J.signal}))}present(J){return X9(this.provider.model,J.usage),_Z(J)}merge(J){let $={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return W9($,`ImageModel "${this.name}"`),$}}function _Z(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function d(J){return typeof process>"u"?void 0:process.env?.[J]}var MZ="preview";function G9(J){let $=J.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function SZ(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function zJ(J,$={}){return{base:(J.baseURL??d("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??d("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??$.timeoutMs??120000,streamIdleTimeoutMs:J.streamIdleTimeoutMs??120000,streamMaxDurationMs:J.streamMaxDurationMs??300000,maxToolArgumentChars:J.maxToolArgumentChars??0,maxRetries:J.maxRetries??2}}function Y9(J){let $=J.baseURL??J.endpoint??d("AZURE_OPENAI_ENDPOINT");if($)return G9($);let Q=J.resourceName??d("AZURE_OPENAI_RESOURCE_NAME")??d("AZURE_RESOURCE_NAME");return Q?G9(`https://${Q.trim()}.cognitiveservices.azure.com`):""}function DJ(J,$={}){let Q=J.apiVersion??d("AZURE_OPENAI_API_VERSION")??MZ;return{base:`${Y9(J)}${SZ(Q)}`,query:`?api-version=${encodeURIComponent(Q)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??d("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??$.timeoutMs??120000,streamIdleTimeoutMs:J.streamIdleTimeoutMs??120000,streamMaxDurationMs:J.streamMaxDurationMs??300000,maxToolArgumentChars:J.maxToolArgumentChars??0,maxRetries:J.maxRetries??2}}function V9(J,$={}){return{...DJ(J,$),base:`${Y9(J)}/v1`,query:""}}var AZ=500,H9=20000;function RZ(J,$){if(!J)return;let Q=J.trim();if(/^\d+(\.\d+)?$/.test(Q))return Math.max(0,Number(Q)*1000);let Z=Date.parse(Q);if(Number.isNaN(Z))return;return Math.max(0,Z-$)}function qJ(J,$){let Q=Math.min(H9,AZ*2**J);return Math.round(Q*(0.5+$()*0.5))}function EZ(J){return J===429||J===408||J===409||J>=500}function jZ(J,$){return EZ(J)&&T($).retryable}function z9(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function D9(J,$){return new Promise((Q,Z)=>{let W=setTimeout(Q,J);$?.addEventListener("abort",()=>{clearTimeout(W),Z(z9($))},{once:!0})})}async function O$(J,$,Q=D9){if(!$)return await Q(J);$.throwIfAborted();let Z;try{await Promise.race([Q(J,$),new Promise((W,K)=>{Z=()=>K(z9($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function i(J,$,Q){let Z=Q.fetchImpl??((D,z)=>fetch(D,z)),W=Q.sleep??D9,K=Q.random??Math.random,X=Q.now??Date.now,Y=Math.max(0,Q.maxRetries),V=Q.startedAt??X(),G=(D,z,F,B)=>{try{Q.onRetry?.({attempt:z+1,maxRetries:Y,error:T(F),...v(F),timedOut:B,delayMs:D,elapsedMs:X()-V})}catch{}return O$(D,Q.signal,W)},H;for(let D=0;D<=Y;D++){Q.signal?.throwIfAborted();let z=new AbortController,F=()=>z.abort(Q.signal?.reason);Q.signal?.addEventListener("abort",F,{once:!0});let B=!1,N=Q.timeoutMs>0?setTimeout(()=>{B=!0,z.abort()},Q.timeoutMs):void 0,P;try{P=await Z(J,{...$,signal:z.signal})}catch(R){if(N!==void 0)clearTimeout(N);if(Q.signal?.removeEventListener("abort",F),Q.signal?.aborted)throw R;if(H=B?new bJ(Q.timeoutMs):R,B&&Q.retryTimeouts===!1)throw H;if(D===Y)throw H;await G(qJ(D,K),D,H,B);continue}if(N!==void 0)clearTimeout(N);if(P.ok)return P;Q.signal?.removeEventListener("abort",F);let U=await kZ(P),L=new y(P.status,U,P.headers.get("x-request-id")??void 0,RZ(P.headers.get("retry-after"),X()));if(D===Y||!jZ(P.status,L))throw L;let _=L.retryAfter??(P.status===429?T(L).retryAfter:void 0);await G(_===void 0?qJ(D,K):Math.min(_,H9),D,L,!1),H=L}throw H??Error("Provider request failed with no response.")}async function kZ(J){let $;try{$=await J.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function F9(J,$,Q){let Z=$.idleMs>0?$.idleMs:0,W=$.maxMs>0?$.maxMs:0;if(!J||!Z&&!W)return J;let K=W?performance.now()+W:1/0,X=J.getReader();return new ReadableStream({async pull(Y){let V,G,H=Math.max(0,K-performance.now()),D=!Z||H<=Z,z=D?H:Z,F=new Promise((B,N)=>{V=setTimeout(()=>{G=D?Q.max():Q.idle(),N(G)},z)});try{let B=await Promise.race([X.read(),F]);if(B.done)Y.close();else Y.enqueue(B.value)}catch(B){let N=G??B;Y.error(N),X.cancel(N).catch(()=>{})}finally{clearTimeout(V)}},cancel(Y){return X.cancel(Y)}},{highWaterMark:0})}var _$=300000;function M$(J){return{generationsUrl:`${J.base}/images/generations${J.query}`,editsUrl:`${J.base}/images/edits${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}class fJ extends Error{code;retryable;retryAfter;constructor(J,$={}){super(J.message,$);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var TZ={png:"image/png",jpeg:"image/jpeg"};function xZ(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let K=J?.output_tokens_details?.image_tokens;if(typeof K==="number")Z.imageOutputTokens=K;return Z}function IZ(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function wZ(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new fJ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof J.output_format==="string"?J.output_format:"png";return{bytes:IZ(Q),mimeType:TZ[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:xZ(J.usage)}}async function P9(J,$,Q,Z){let W;try{W=await i(J,$,{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(K){if(Z.signal?.aborted)throw K;throw new fJ(T(K),{cause:K})}return wZ(await W.json())}async function U9(J,$,Q={}){return await P9(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function N9(J,$,Q={}){return await P9(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class yJ{static models(){return[]}modelName(){return this.model}async generate(J){return await U9(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let $=new FormData;for(let[Q,Z]of Object.entries(this.body(J)))if(Z!==void 0)$.set(Q,String(Z));for(let Q of J.images)$.append("image[]",Q,Q.name);if(J.mask)$.set("mask",J.mask,J.mask.name);return await N9(this.endpoint(),$,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return T(J)}}var B9=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class S$ extends yJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new S$(J,$)}static models(){return B9}endpoint(){return M$(zJ(this.config,{timeoutMs:_$}))}}class A$ extends yJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new A$(J,$)}static models(){return B9}modelName(){return this.config.deployment??this.model}endpoint(){return M$(DJ(this.config,{timeoutMs:_$}))}}var O9=3;function R$(J){let $=new Map;for(let Q of J)for(let Z of Q.content??[]){if(Z.type!=="file"||!Z.fileId||$.has(Z.fileId))continue;$.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return $}function _9(J,$,Q=new Map){if(!($ instanceof y))return[];if($.status!==400&&$.status!==404)return[];let Z=bZ($.body);if(!Z)return[];let W=qZ(J.input);if(W.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let G=J.input[Number(K[1])],H=j$(G)[Number(K[2])],D=H&&typeof H.file_id==="string"?H.file_id:void 0;if(D)return[D]}let X=Z.message??"",Y=C9(W.map((G)=>G.fileId).filter((G)=>fZ(X,G)));if(Y.length>0)return Y;let V=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(X);if(V){let G=V[1].toLowerCase()==="image type"?"input_image":"input_file",H=V[2].toLowerCase(),D=C9(W.filter((F)=>F.type===G).map((F)=>F.fileId)),z=D.filter((F)=>(Q.get(F)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(z.length===1)return z;if(z.length===0&&D.length===1)return D}return[]}function M9(J,$,Q=new Map){return{...J,input:J.input.map((Z)=>{let W=j$(Z);if(!W.some((K)=>L9(K,$)))return Z;return{...Z,content:W.map((K)=>L9(K,$)?{type:"input_text",text:E$(Q.get(String(K.file_id))?.name)}:K)}})}}function E$(J){return`[${J?`attachment ${JSON.stringify(J)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function L9(J,$){return typeof J.file_id==="string"&&$.has(J.file_id)}function j$(J){let $=J?.content;return Array.isArray($)?$:[]}function qZ(J){let $=[];for(let Q of J)for(let Z of j$(Q))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function bZ(J){if(!J||typeof J!=="object")return null;let $=J,Q=$.error&&typeof $.error==="object"?$.error:J;return{message:typeof Q.message==="string"?Q.message:void 0,param:typeof Q.param==="string"?Q.param:void 0}}function fZ(J,$){let Q=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Q}($|[^A-Za-z0-9_-])`).test(J)}function C9(J){return[...new Set(J)]}async function*yZ(J){let $="",Q="",Z=[],W,K=()=>{if(Z.length===0&&!Q)return null;let V={event:Q,data:Z.join(`
144
- `),id:W};return Q="",Z=[],W=void 0,V.data?V:null},X=(V)=>{let G=V.endsWith("\r")?V.slice(0,-1):V;if(G==="")return K();if(G.startsWith(":"))return null;let H=G.indexOf(":"),D=H===-1?G:G.slice(0,H),z=H===-1?"":G.slice(H+1);if(z.startsWith(" "))z=z.slice(1);if(D==="event")Q=z;else if(D==="data")Z.push(z);else if(D==="id")W=z;return null};for await(let V of J){$+=V;let G=$.indexOf(`
145
- `);while(G!==-1){let H=$.slice(0,G);$=$.slice(G+1);let D=X(H);if(D)yield D;G=$.indexOf(`
146
- `)}}if($.length>0){let V=X($);if(V)yield V}let Y=K();if(Y)yield Y}async function*S9(J,$={}){let Q=new Map,Z=new Set,W,K=!1,X,Y=(V,G)=>({type:"finish",reason:V,usage:G,...X?{model:X}:{}});for await(let V of yZ(J)){if(V.data==="[DONE]")break;let G;try{G=JSON.parse(V.data)}catch{continue}let H=typeof G.type==="string"?G.type:V.event,D=G.response?.model;if(typeof D==="string"&&D)X=D;switch(H){case"response.output_text.delta":{let z=String(G.delta??"");if(!z)break;yield $.structuredOutput?{type:"output-delta",delta:z}:{type:"text-delta",delta:z};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let z=String(G.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:G.item_id};break}case"response.output_item.added":{let z=G.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??G.item_id??z.call_id??"");Q.set(F,{callId:String(z.call_id??F),name:String(z.name??""),namespace:typeof z.namespace==="string"&&z.namespace?z.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let z=Q.get(String(G.item_id??""));if(!z)break;let F=String(G.delta??"");if(!F)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:F,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(G.item_id??""),F=Q.get(z);if(!F)break;F.done=!0,yield{type:"tool-call",toolCallId:F.callId,name:F.name,args:String(G.arguments??""),...F.namespace?{namespace:F.namespace}:{}};break}case"response.output_item.done":{let z=G.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??G.item_id??z.call_id??""),B=Q.get(F);if(B?.done)break;let N=(typeof z.namespace==="string"?z.namespace:"")||B?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??F),name:String(z.name??B?.name??""),args:String(z.arguments??""),...N?{namespace:N}:{}},B)B.done=!0;break}if(z.type==="tool_search_call"||z.type==="tool_search_output"){if(z.type==="tool_search_call"&&z.arguments!==void 0)W=z.arguments;let F=vZ(z);if(F.loaded.length===0&&F.namespaces.length===0)break;let B=String(z.tool_search_call_id??z.id??"");if(Z.has(B))break;Z.add(B);let N=W;W=void 0,yield{type:"tool-search",...F,...N!==void 0&&N!==null?{arguments:N}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(G.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{K=!0,yield Y("stop",k$(G.response?.usage));break}case"response.incomplete":{K=!0;let z=k$(G.response?.usage),F=G.response?.incomplete_details?.reason;if(F==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:hZ(G.response?.content_filters),retryable:!1}},yield Y("error",z);break}yield Y(F==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{K=!0;let z=G.response?.error??G.error??G;yield{type:"error",error:gZ(z)},yield Y("error",k$(G.response?.usage));break}}if(K)return}if(!K)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield Y("error",h())}function vZ(J){let $=[],Q=[];return A9(J.results??J.tools??J.loaded??J.output,$,Q,0),{loaded:T$($),namespaces:T$(Q)}}function A9(J,$,Q,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){$.push(W);continue}if(!W||typeof W!=="object")continue;let K=W,X=typeof K.name==="string"?K.name:typeof K.tool_name==="string"?K.tool_name:"",Y=K.tools??K.functions;if(Array.isArray(Y)){if(X)Q.push(X);A9(Y,$,Q,Z+1);continue}if(X)$.push(X)}}function T$(J){return J.filter(($,Q)=>J.indexOf($)===Q)}function hZ(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let Q=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,K=W.content_filter_results;if(!K||typeof K!=="object")continue;for(let[X,Y]of Object.entries(K))if(Y&&typeof Y==="object"&&Y.filtered===!0)Q.push(`${X} (${String(W.source_type??"unknown")})`)}return Q.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${T$(Q).join(", ")}.`}function gZ(J){let $=typeof J?.message==="string"?J.message:"The provider stream failed.",Q=String(J?.code??"").toLowerCase();if(Q==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Q==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Q.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function h(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function k$(J){if(!J)return h();let $=Number(J.input_tokens??0),Q=Number(J.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J.total_tokens??$+Q)},W=J.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let K=J.input_tokens_details?.cached_tokens;if(typeof K==="number")Z.cachedInputTokens=K;return Z}async function*R9(J){if(!J)return;let $=J.getReader(),Q=new TextDecoder;try{while(!0){let{done:W,value:K}=await $.read();if(W)break;if(K)yield Q.decode(K,{stream:!0})}let Z=Q.decode();if(Z)yield Z}finally{$.releaseLock()}}function x$(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,streamIdleTimeoutMs:J.streamIdleTimeoutMs,streamMaxDurationMs:J.streamMaxDurationMs,maxToolArgumentChars:J.maxToolArgumentChars,maxRetries:J.maxRetries}}async function*I$(J,$,Q){let Z=$,W=new Set,K=0,X=Math.max(0,J.maxRetries),Y=J.random??Math.random,V,G=(P)=>{if(!V)return P;let U=k(k(h(),V),P.usage);return V=void 0,{...P,usage:U}},H=()=>G({type:"finish",reason:"aborted",usage:h()}),D=J.streamIdleTimeoutMs??0,z=J.streamMaxDurationMs??0,F=J.maxToolArgumentChars??0,B=J.now??Date.now,N=B();for(let P=0;;P++){let U=new AbortController,L=Q.signal?AbortSignal.any([Q.signal,U.signal]):U.signal,_;while(_===void 0)try{let O=[],C=()=>{},M=i(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Z)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:L,fetchImpl:J.fetchImpl,sleep:J.sleep,random:J.random,now:J.now,startedAt:N,onRetry:(I)=>{O.push({type:"retry",...I,phase:"request"}),C()}}),w=M.then(()=>!0,()=>!0);for(;;){let I=new Promise(($$)=>C=()=>$$(!1)),J$=await Promise.race([w,I]);if(yield*O.splice(0),J$)break}_=await M}catch(O){let C=K<O9?_9(Z,O,Q.files).filter((w)=>!W.has(w)):[];if(C.length>0){K++;let w=T(O).message;for(let I of C)W.add(I),yield{type:"file-rejected",fileId:I,message:w,...v(O)};Z=M9(Z,new Set(C),Q.files);continue}let M=T(O);if(M.code==="aborted"){yield H();return}yield{type:"error",error:M,...v(O)},yield G({type:"finish",reason:"error",usage:h()});return}let R=[],A=!1,x,f=!1,q=new Map;try{let O=F9(_.body,{idleMs:D,maxMs:z},{idle:()=>{let C=new E9(D);return U.abort(C),C},max:()=>{let C=new j9(z);return U.abort(C),C}});for await(let C of S9(R9(O),{structuredOutput:Q.structuredOutput})){if(C.type==="tool-call-delta"){let M=(q.get(C.toolCallId)??0)+C.argsDelta.length;if(q.set(C.toolCallId,M),F>0&&M>F){let w=new k9(F,C.name);throw U.abort(w),w}yield C;continue}if(C.type==="tool-call")q.delete(C.toolCallId);if(A){yield C.type==="finish"?G(C):C;continue}if(vJ(C)){A=!0,yield*R.splice(0),yield C;continue}if(C.type==="error")x=C.error;R.push(C)}}catch(O){f=O instanceof bJ;let C=T(O);if(C.code==="aborted"||Q.signal?.aborted){yield H();return}if(A){yield{type:"error",error:C},yield G({type:"finish",reason:"error",usage:h()});return}x=C,R.push({type:"error",error:C},{type:"finish",reason:"error",usage:h()})}if(A)return;if(x?.retryable&&P<X&&!Q.signal?.aborted){let O={};for(let M of R){if(M.type==="finish")V=k(V??h(),M.usage);if(M.type==="error")O=v(M)}if(q.size>0)yield{type:"tool-call-discard",toolCallIds:[...q.keys()]};let C=qJ(P,Y);yield{type:"retry",attempt:P+1,maxRetries:X,error:x,...O,phase:"stream",timedOut:f,delayMs:C,elapsedMs:B()-N};try{await O$(C,Q.signal,J.sleep)}catch{yield H();return}continue}for(let O of R)yield O.type==="finish"?G(O):O;return}}async function w$(J,$,Q="user_data"){let Z=new FormData;Z.set("purpose",Q),Z.set("file",$);let K=await(await i(J.filesUrl,{method:"POST",headers:await J.headers(),body:Z},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,fetchImpl:J.fetchImpl})).json();if(!K?.id)throw Error("The provider accepted the upload but returned no file id.");return K.id}function q$(J){let $=uZ(J);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Q=cZ($);if(Q?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Q.major>1,toolSearch:T9(Q)};if(Q?.kind==="gpt")return{reasoning:Q.major>=5,structuredOutput:Q.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Q.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:T9(Q)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function T9(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function uZ(J){return J.trim().toLowerCase()}function cZ(J){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Q=/^o(\d+)(?:[-.]|$)/.exec(J);if(Q?.[1])return{kind:"o",major:Number(Q[1]),minor:0};return null}var mZ={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function pZ(J){if(typeof J!=="string")return;let $;try{$=JSON.parse(J)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let Q=mZ[$.type];if(Q)$.type=Q;if($.type==="response.done"&&$.response?.usage)$.usage=hJ($.response.usage);if($.type==="conversation.item.input_audio_transcription.completed"&&$.usage)if($.usage.type==="duration"){let Z=Number($.usage.seconds);if(Number.isFinite(Z))$.transcriptionSeconds=Z}else $.transcriptionUsage=hJ($.usage);return $}var x9=1,lZ=500;function dZ(J,$){let Q=globalThis.WebSocket;if(!Q)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new Q(J,{headers:$.headers})}class gJ{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(J){this.init=J,this.callId=J.callId,this.ready=new Promise(($,Q)=>{this.resolveReady=$,this.rejectReady=Q}),this.ready.catch(()=>{}),this.closed=new Promise(($)=>this.resolveClosed=$),this.open()}send(J){if(this.finished||this.closing)return;let $=JSON.stringify(J);if(this.socket?.readyState===x9)this.socket.send($);else this.outbox.push($)}updateSession(J){this.send({type:"session.update",session:uJ(J)})}addItem(J){this.send({type:"conversation.item.create",item:J})}addNote(J){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:J}]})}functionOutput(J,$){this.addItem({type:"function_call_output",call_id:J,output:typeof $==="string"?$:JSON.stringify($)})}createResponse(J={}){let $={};if(J.instructions!==void 0)$.instructions=J.instructions;if(J.toolChoice!==void 0)$.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};if(J.outputModalities)$.output_modalities=J.outputModalities;if(J.conversation)$.conversation=J.conversation;if(J.metadata)$.metadata=J.metadata;Object.assign($,J.vendor),this.send(Object.keys($).length?{type:"response.create",response:$}:{type:"response.create"})}cancelResponse(J){this.send(J?{type:"response.cancel",response_id:J}:{type:"response.cancel"})}on(J){return this.listeners.add(J),()=>this.listeners.delete(J)}[Symbol.asyncIterator](){let J={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(J),{next:async()=>{for(;;){let Q=J.queue.shift();if(Q)return{value:Q,done:!1};if(J.done)return this.subscribers.delete(J),{value:void 0,done:!0};await new Promise((Z)=>J.wake=Z),J.wake=void 0}},return:async()=>{return J.done=!0,J.queue.length=0,this.subscribers.delete(J),{value:void 0,done:!0}}}}close(J=1000,$="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=x9)this.socket.close(J,$);else this.finish(J,$,!0)}async hangup(){try{await this.init.hangup()}catch(J){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw J}this.close(1000,"hangup")}async open(){let J;try{let Q=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);J=(this.init.webSocket??dZ)(this.init.url,{headers:Q})}catch(Q){return this.dropped(1006,Q instanceof Error?Q.message:String(Q),!1)}this.socket=J;let $=!1;J.addEventListener("open",()=>{$=!0;let Q=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let W of this.outbox.splice(0))J.send(W);if(this.resolveReady(),Q)this.emit({type:"sideband.reconnected",attempt:Z})}),J.addEventListener("message",(Q)=>{let Z=pZ(Q.data);if(Z)this.emit(Z)}),J.addEventListener("close",(Q)=>{if(this.socket!==J)return;this.dropped(Q.code??1006,Q.reason??"",$)}),J.addEventListener("error",()=>{})}dropped(J,$,Q){if(this.socket=void 0,this.closing)return this.finish(J,$,!0);let Z=this.init.reconnect?.attempts??3;if(!((J!==1000||!Q)&&this.failures<Z))return this.finish(J,$,!1);this.failures+=1;let K=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),K)}finish(J,$,Q){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:J,reason:$,byClient:Q};this.finalEvent=Z,this.emit(Z);for(let W of this.subscribers)W.done=!0,W.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${J} ${$}).`));this.resolveClosed(Z)}emit(J){if(this.backlog){if(this.backlog.push(J),this.backlog.length>lZ)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(J),$.wake?.()}for(let $ of this.listeners)try{$(J)}catch{}}}var b$=30000,I9=10,w9=7200,iZ=600,b9="gpt-live-transcribe";function nZ(J){return J.type==="transcription"}function oZ(J){if(J.language!==void 0&&J.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let W of J.keywords??[])if(/[<>\r\n]/.test(W))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(W)}.`);let $={model:J.model??b9};if(J.prompt!==void 0)$.prompt=J.prompt;if(J.keywords?.length)$.keywords=J.keywords;if(J.languages?.length)$.languages=J.languages;if(J.language!==void 0)$.language=J.language;if(J.delay!==void 0)$.delay=J.delay;let Q={transcription:$,turn_detection:J.turnDetection?f9(J.turnDetection):null};if(J.noiseReduction!==void 0)Q.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let Z={type:"transcription",audio:{input:Q}};if(J.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...J.vendor}}function sZ(J){if(!J)return{type:"object",properties:{}};return q9(J)?J.toJSONSchema():J}function uJ(J,$){if(nZ(J))return oZ(J);let Q={type:"realtime"},Z=J.model??$;if(Z)Q.model=Z;if(J.instructions!==void 0)Q.instructions=J.instructions;if(J.outputModalities)Q.output_modalities=J.outputModalities;if(J.maxOutputTokens!==void 0)Q.max_output_tokens=J.maxOutputTokens;if(J.truncation!==void 0)Q.truncation=J.truncation;if(J.tools)Q.tools=J.tools.map((X)=>({type:"function",name:X.name,...X.description?{description:X.description}:{},parameters:sZ(X.parameters)}));if(J.toolChoice!==void 0)Q.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};let W={};if(J.turnDetection!==void 0)W.turn_detection=J.turnDetection&&f9(J.turnDetection);if(J.transcription!==void 0)W.transcription=J.transcription;if(J.noiseReduction!==void 0)W.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let K={};if(J.voice!==void 0)K.voice=J.voice;if(J.speed!==void 0)K.speed=J.speed;if(Object.keys(W).length||Object.keys(K).length)Q.audio={...Object.keys(W).length?{input:W}:{},...Object.keys(K).length?{output:K}:{}};return{...Q,...J.vendor}}function f9(J){let $={type:J.type};if(J.createResponse!==void 0)$.create_response=J.createResponse;if(J.interruptResponse!==void 0)$.interrupt_response=J.interruptResponse;if(J.type==="semantic_vad"){if(J.eagerness!==void 0)$.eagerness=J.eagerness}else{if(J.threshold!==void 0)$.threshold=J.threshold;if(J.prefixPaddingMs!==void 0)$.prefix_padding_ms=J.prefixPaddingMs;if(J.silenceDurationMs!==void 0)$.silence_duration_ms=J.silenceDurationMs;if(J.idleTimeoutMs!==void 0)$.idle_timeout_ms=J.idleTimeoutMs}return $}function hJ(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_token_details??J?.input_tokens_details,K=J?.output_token_details??J?.output_tokens_details;if(typeof W?.cached_tokens==="number")Z.cachedInputTokens=W.cached_tokens;if(typeof W?.audio_tokens==="number")Z.audioInputTokens=W.audio_tokens;let X=W?.cached_tokens_details?.audio_tokens;if(typeof X==="number")Z.cachedAudioInputTokens=X;if(typeof W?.image_tokens==="number"&&W.image_tokens>0)Z.imageInputTokens=W.image_tokens;if(typeof K?.audio_tokens==="number")Z.audioOutputTokens=K.audio_tokens;return Z}class g extends Error{code;retryable;status;constructor(J,$={}){super(J.message,{cause:$.cause});if(this.name="RealtimeRequestError",this.code=J.code,this.retryable=J.retryable,$.status!==void 0)this.status=$.status}}var aZ=60;class FJ{model;target;options;constructor(J,$){this.target=J,this.options=$,this.model=$.model}url(J){return`${this.target.base}/realtime${J}${this.target.query}`}sidebandUrl(J){let $=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),Q=this.target.query?`${this.target.query}&`:"?";return`${$}/realtime${Q}call_id=${encodeURIComponent(J)}`}async createCall(J){let $=J.flow??this.options.callFlow??"unified",Q,Z;if($==="ephemeral")Q={authorization:`Bearer ${(await this.clientSecret({session:J.session,ttlSeconds:aZ,signal:J.signal})).value}`,"content-type":"application/sdp"},Z=J.sdp;else{let V=new FormData;V.set("sdp",J.sdp),V.set("session",JSON.stringify(uJ(J.session??{},this.model))),Q=await this.target.headers(),Z=V}if(J.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=this.url("/calls"),K=await this.request(J.webrtcFilter?`${W}${W.includes("?")?"&":"?"}webrtcfilter=on`:W,{method:"POST",headers:Q,body:Z},J.signal),X=await K.text(),Y=tZ(K);if(!Y)throw new g({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:X,callId:Y}}async clientSecret(J={}){let $=J.ttlSeconds??iZ;if(!Number.isInteger($)||$<I9||$>w9)throw RangeError(`ttlSeconds must be a whole number from ${I9} to ${w9}, got ${$}.`);let Q={...await this.target.headers(),"content-type":"application/json"};if(J.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:Q,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:uJ(J.session??{},this.model)})},J.signal)).json();if(typeof W?.value!=="string")throw new g({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:W.value,expiresAt:Number(W.expires_at??0),session:W.session,callsUrl:this.url("/calls")}}async hangup(J,$={}){try{await this.request(this.url(`/calls/${encodeURIComponent(J)}/hangup`),{method:"POST",headers:await this.target.headers()},$.signal)}catch(Q){if(y9(Q,J))return;throw Q}}sideband(J,$={}){return new gJ({...$,callId:J,url:this.sidebandUrl(J),headers:this.target.headers,webSocket:$.webSocket??this.options.webSocket,hangup:()=>this.hangup(J)})}async request(J,$,Q){try{return await i(J,$,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:Q,fetchImpl:this.options.fetchImpl})}catch(Z){if(Q?.aborted)throw Z;throw new g(T(Z),{cause:Z,...Z instanceof y?{status:Z.status}:{}})}}}function y9(J,$){if(!(J instanceof g)||J.status!==404)return!1;let Q=J.cause instanceof y?J.cause.body:void 0,Z=Q?.error??Q,W=String(Z?.code??"").toLowerCase(),K=String(Z?.message??"").toLowerCase();if(W.includes("call"))return!0;if(K.includes($.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function tZ(J){let $=J.headers.get("location");if(!$)return;let Q=$.split("?")[0].replace(/\/+$/,""),Z=Q.slice(Q.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function y$(J,$){let{capabilities:Q}=$,Z={model:$.model,input:rZ(J.messages,Q,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=Y6(J.tools,Q);if(W.length>0){if(Z.tools=W,!Q.parallelToolCalls)Z.parallel_tool_calls=!1;if(J.toolChoice!==void 0)Z.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name}}if(J.output)Z.text={format:{type:"json_schema",name:J.output.name,schema:J.output.schema,strict:J.output.strict}};if(J.reasoning&&Q.reasoning)Z.reasoning=J.reasoning==="none"?{effort:"none"}:{effort:J.reasoning,summary:"auto"};if(typeof J.temperature==="number")Z.temperature=J.temperature;if(typeof J.maxOutputTokens==="number")Z.max_output_tokens=J.maxOutputTokens;return Z}function rZ(J,$,Q){let Z=[],W=new Map;if($.toolSearch){for(let K of Q??[])if(cJ(K))W.set(K.name,K)}for(let K of J){let X=K.role,Y=[],V=()=>{if(Y.length===0)return;Z.push({type:"message",role:X,content:Y}),Y=[]};for(let G of K.content??[])switch(G.type){case"text":{if(!G.text)break;Y.push(e(X,G.text));break}case"output":{if(G.partial)break;Y.push(e(X,JSON.stringify(G.value)));break}case"file":{if(X==="assistant")break;let H=$6(G);if(!$.fileInput){if(H)Y.push(e(X,f$(G,!1)));break}if(G.fileId?.startsWith(n))throw Error(`FilePart.fileId holds a gemi attachment id (${G.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!G.fileId&&!H)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(G.providerRejected){if(H)Y.push(e(X,f$(G,!1)));Y.push(e(X,E$(G.name)));break}if(H)Y.push(e(X,f$(G,!!G.fileId)));if(G.fileId)Y.push(Q6(G));break}case"reasoning":{V();let H=K6(G);if(H)Z.push(H);break}case"tool-call":{if(G.partial)break;if(V(),$.toolSearch&&Array.isArray(G.toolSearches))for(let D of G.toolSearches)Z.push(...G6(D,Q??[]));let H={type:"function_call",call_id:G.toolCallId,name:String(G.name),arguments:JSON.stringify(G.input??{})};if(G.namespace&&W.has(G.namespace))H.namespace=G.namespace;Z.push(H);break}case"tool-result":{V(),Z.push({type:"function_call_output",call_id:G.toolCallId,output:X6(G)});break}}V()}return J6(Z)}var eZ="No result was recorded for this tool call. Assume it did not complete.";function J6(J){let $=new Set,Q=new Set,Z=[];for(let K of J){if(K.type==="function_call"){let X=String(K.call_id);if($.has(X))continue;$.add(X)}else if(K.type==="function_call_output"){let X=String(K.call_id);if(!$.has(X)||Q.has(X))continue;Q.add(X)}Z.push(K)}if(Q.size===$.size)return Z;let W=[];for(let K of Z){if(W.push(K),K.type!=="function_call")continue;let X=String(K.call_id);if(Q.has(X))continue;Q.add(X),W.push({type:"function_call_output",call_id:X,output:eZ})}return W}function e(J,$){return{type:J==="assistant"?"output_text":"input_text",text:$}}function $6(J){let $=J.attachmentId;return typeof $==="string"&&$.startsWith(n)?$:void 0}function f$(J,$){let Q=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)Q.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)Q.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${Q.join(" ")}`;return $?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function Q6(J){let $=J.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":Z6(J.name))?"input_image":"input_file",file_id:J.fileId}}function Z6(J){let $=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return $?.[1]!==void 0&&W6.has($[1])}var W6=new Set(["jpeg","jpg","png","gif","webp"]);function K6(J){if(!J.id)return null;let $={type:"reasoning",id:J.id};return $.summary=J.text?[{type:"summary_text",text:J.text}]:[],$}function X6(J){if(J.status==="ok"){let $=J.modelOutput!==void 0?J.modelOutput:J.output;return typeof $==="string"?$:JSON.stringify($??null)}if(J.status==="running"){let $=J.job?.summary===void 0?"":` Started with: ${JSON.stringify(J.job.summary)}.`;return`Started background job ${J.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${$}`}if(J.status==="denied"){let $=J.reason?` Reason given: ${J.reason}`:"";if(J.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(J.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function G6(J,$){let Q=new Set(v9(J?.loaded)),Z=v9(J?.namespaces),W=new Set(Z),K=[];for(let Y of $)if(cJ(Y)){if(!W.has(Y.name))continue;let V=Y.tools.filter((G)=>Q.size===0||Q.has(G.name));if(V.length===0)continue;K.push({type:"namespace",name:Y.name,description:Y.description,tools:V.map((G)=>JJ(G,!0))})}else if(Y.deferred&&Q.has(Y.name))K.push(JJ(Y,!0));if(K.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:J.arguments&&typeof J.arguments==="object"?J.arguments:{paths:Z.length>0?Z:[...Q]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function v9(J){return Array.isArray(J)?J.filter(($)=>typeof $==="string"):[]}function cJ(J){return Array.isArray(J.tools)}function Y6(J,$){if(!J||J.length===0)return[];if(!$.toolSearch){let W=[];for(let K of J)if(cJ(K))for(let X of K.tools)W.push(JJ(X,!1));else W.push(JJ(K,!1));return W}let Q=[],Z=!1;for(let W of J)if(cJ(W)){let K=W.tools.map((X)=>{if(X.deferred)Z=!0;return JJ(X,!0)});Q.push({type:"namespace",name:W.name,description:W.description,tools:K})}else{if(W.deferred)Z=!0;Q.push(JJ(W,!0))}if(Z)Q.push({type:"tool_search"});return Q}function JJ(J,$){let Q={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if($&&J.deferred)Q.defer_loading=!0;return Q}class $J{static models(){return[]}normalizeError(J){return T(J)}}var h9=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class v$ extends $J{model;capabilities;config;constructor(J,$={}){super();this.model=J,this.capabilities=q$(J),this.config=$}static model(J,$){return new v$(J,$)}static models(){return h9}stream(J){let $=y$(J,{model:this.model,capabilities:this.capabilities});return I$(this.endpoint(),$,{signal:J.signal,structuredOutput:Boolean(J.output),files:R$(J.messages)})}upload(J){return w$(this.endpoint(),J)}endpoint(){return x$(zJ(this.config))}get realtime(){return new FJ(zJ(this.config,{timeoutMs:b$}),{model:this.model})}}class h$ extends $J{model;capabilities;config;constructor(J,$={}){super();this.model=J,this.capabilities=q$(J),this.config=$}static model(J,$){return new h$(J,$)}static models(){return h9}stream(J){let $=y$(J,{model:this.deployment(),capabilities:this.capabilities});return I$(this.endpoint(),$,{signal:J.signal,structuredOutput:Boolean(J.output),files:R$(J.messages)})}upload(J){return w$(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return x$(DJ(this.config))}get realtime(){return new FJ(V9(this.config,{timeoutMs:b$}),{model:this.deployment(),callFlow:"ephemeral"})}}class mJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,$){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return!0;let Z=this.now();if(Z<Q.openUntil)return!1;if(Q.probeUntil!==void 0&&Z<Q.probeUntil)return!1;return Q.probeUntil=Z+$.cooldownMs,!0}record(J,$,Q){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if($==="success")return this.entries.delete(J),W?"closed":void 0;if($==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let $=this.entries.get(J);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}var g9=Symbol("timed-out");class PJ extends $J{model;capabilities;entries;options;circuit;constructor(J,$={}){super();if(J.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of J)if(Z.timeoutMs!==void 0&&!(Z.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${Z.provider.model} must be a positive number, got ${Z.timeoutMs}.`);this.entries=[...J];let Q=$.circuit;if(Q){let Z=Q.failures??3,W=Q.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let K=new Set;for(let Y of J){let V=g$(Y);if(K.has(V))throw Error(`FallbackProvider: two legs share the circuit key "${V}". Give one of them a \`circuitKey\`.`);K.add(V)}let X=Q.store??new mJ;this.options={...$,circuit:{...Q,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=V6(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new PJ(J,$)}from(J){if(!Number.isInteger(J)||J<0||J>=this.entries.length)throw RangeError(`FallbackProvider.from(${J}): the chain has ${this.entries.length} entries.`);return new PJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new PJ([$],this.options)}upload(J){return this.entries[0].provider.upload(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let $,Q=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let K=this.entries[W],X=W===this.entries.length-1,Y=K.provider.model;if(this.circuit&&!X&&!await this.allow(K))continue;Z+=1;let V=!1,G=async(O)=>{if(V)return;V=!0,await this.record(W,K,O)},H=new AbortController,D=()=>H.abort(Q?.reason);if(Q?.aborted)H.abort(Q.reason);else Q?.addEventListener("abort",D,{once:!0});let z=[],F=!1,B=!1,N,P,U,L=!1,_,R=!1,A=(O)=>{let C=$?k(k(j(),$),O.usage):O.usage;return $=void 0,{...O,usage:C}};try{_=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let O=K.timeoutMs!==void 0?Date.now()+K.timeoutMs:void 0;for(;;){let C=!F&&O!==void 0?await H6(_.next(),Math.max(0,O-Date.now())):await _.next();if(C===g9){L=!0,U={error:{code:"provider_error",message:`${Y} did not start answering within ${K.timeoutMs}ms.`,retryable:!0}};break}if(C.done){R=!0;break}let M=C.value;if(M.type==="finish"&&M.model)P=M.model;if(M.type==="retry"){yield M;continue}if(F){if(M.type==="finish")N=k(N??j(),M.usage),B=!0,yield A(M);else{if(M.type==="error")U={error:M.error};yield M}continue}if(vJ(M)){F=!0,await G("success"),yield*z.splice(0),yield M;continue}if(M.type==="error")U={error:M.error,...M.status!==void 0?{status:M.status}:{},...M.requestId!==void 0?{requestId:M.requestId}:{}};else if(M.type==="finish"){if(N=k(N??j(),M.usage),M.reason==="error"&&!U)U={error:{code:"provider_error",message:`${Y} ended the call with an error and did not say which.`,retryable:!1}}}z.push(M)}}catch(O){let C=K.provider.normalizeError(O);if(F){if(C.code!=="aborted")yield{type:"error",error:C,...v(O)};this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:u$(C),error:C}),yield A({type:"finish",reason:C.code==="aborted"?"aborted":"error",usage:j(),...P?{model:P}:{}});return}U={error:C,...v(O)}}finally{if(Q?.removeEventListener("abort",D),!R)H.abort(),_?.return?.()?.catch(()=>{})}if(F){if(!B&&$)yield{type:"finish",reason:U?"error":"stop",usage:$},$=void 0;this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:U?u$(U.error):"ok",...U?{error:U.error}:{}});return}if(Q?.aborted){await G("none"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:"aborted"}),yield A({type:"finish",reason:"aborted",usage:N??j(),...P?{model:P}:{}});return}if(!U){await G("success"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:"ok"});for(let O of z)yield O.type==="finish"?A(O):O;return}let x=!X&&U.error.code!=="aborted"&&this.shouldFallBack(U.error,{index:W,model:Y,timedOut:L,...U.status!==void 0?{status:U.status}:{},...U.requestId!==void 0?{requestId:U.requestId}:{}});if(await G(x?"failure":"none"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:x?"fallback":u$(U.error),error:U.error}),x){if(N)$=k($??j(),N);continue}let f=!1,q;for(let O of z){if(O.type==="finish"){q=O;continue}if(O.type==="error")f=!0;yield O}if(!f&&U.error.code!=="aborted")yield{type:"error",error:U.error,...U.status!==void 0?{status:U.status}:{},...U.requestId!==void 0?{requestId:U.requestId}:{}};yield A({type:"finish",reason:U.error.code==="aborted"?"aborted":q?.reason??"error",usage:N??j(),...P?{model:P}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(g$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=g$($),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:$.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,$){let Q=this.options.fallbackOn??((Z)=>Z.retryable);try{return Q(J,$)}catch{return!1}}report(J){if(J.usage===void 0)delete J.usage;if(J.responseModel===void 0)delete J.responseModel;try{this.options.onUsage?.(J)}catch{}}}function g$(J){return J.circuitKey??J.provider.model}function u$(J){return J.code==="aborted"?"aborted":"failed"}function V6(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch)}}function H6(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(g9),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function z6(J,$,Q={}){let Z=Q.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let K=0;K<J.entries.length;K++){let X=J.leg(K),Y={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{Y.results.push(await $(X,{index:K,sample:V}))}catch(G){Y.errors.push({sample:V,error:G})}W.push(Y)}return W}class lJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var NJ="ask_agent",D6={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},F6={maxDuration:"We've reached the time limit for this voice session. Tap the microphone to start again.",idle:"It's gone quiet, so I'll hang up. Tap the microphone when you want to talk again.",error:null};function UJ(J={}){return[{name:J.name??NJ,description:J.description??"Hand one self-contained request to the agent that does the work, in the user's own words with references resolved. It can take minutes; the result comes back when it is done, so tell the user you are on it.",parameters:{type:"object",properties:{request:{type:"string",description:"What the user wants done."}},required:["request"],additionalProperties:!1}},{name:"stop_work",description:"Stop the work that is running, and drop any requests waiting behind it.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"work_status",description:"What the agent is doing right now, and what is waiting.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"answer_question",description:"Answer the question the agent asked (it came back from a request with status needs_input). For an approval, set approve.",parameters:{type:"object",properties:{answer:{type:"string",description:"The user's answer, in their words."},approve:{type:"boolean",description:"For an approval: whether the user approved."}},required:["answer"],additionalProperties:!1}}]}var pJ=new Map;class o{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=j();transcription={usage:j(),seconds:0};hooks=Promise.resolve();pendingCreate;transcript=[];requests=[];toolCalls=[];toolHandlers=new Map;toolsRunning=0;toolCallTimes=[];errors=[];running;queue=[];pending=[];lastProgress;lastNoteAt=0;noteTimer;responseActive=!1;responseWanted=!1;ending;timers=[];idleTimer;tickTimer;resolveEnded;closingWaiter;static start(J){return new o(J)}static get(J){return pJ.get(J)}static async endAll(J){await Promise.all([...pJ.values()].map(($)=>$.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...D6,...u9(J.limits)},this.lines={...F6,...u9(J.lines)},this.delegateName=J.delegate?.name??NJ;let $=new Set(UJ(J.delegate).map((Q)=>Q.name));for(let Q of J.tools??[]){if($.has(Q.tool.name)||this.toolHandlers.has(Q.tool.name))throw Error(`VoiceBridge: two tools are named "${Q.tool.name}".`);this.toolHandlers.set(Q.tool.name,Q)}if("realtime"in J.call){let{realtime:Q,callId:Z}=J.call;this.callId=Z,this.sideband=Q.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=J.call.callId??J.call.sideband.callId,this.sideband=J.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise((Q)=>this.resolveEnded=Q),pJ.set(this.sessionId,this),this.timers.push(setTimeout(()=>void this.end("max_duration",this.lines.maxDuration),this.limits.maxDurationMs)),this.tickTimer=setInterval(()=>void this.tick(),this.limits.tickMs),this.touch(),this.listen()}setBody(J){this.body=J;let $=this.params.contextNote?.(J);if($)this.sideband.addNote($)}end(J="hangup",$){return this.ending??=this.finish(J,$??null)}async listen(){for await(let J of this.sideband){try{this.params.onEvent?.(J)}catch{}this.closingWaiter?.(J),await this.handle(J)}}async handle(J){switch(J.type){case"input_audio_buffer.speech_started":this.touch();return;case"response.created":this.responseActive=!0,this.pendingCreate=void 0,this.touch();return;case"response.done":{if(this.responseActive=!1,this.responseWanted&&!this.ending)this.responseWanted=!1,this.createResponse();let $=J.usage;if($){this.usage=k(this.usage,$);let Q=this.info();this.hook(()=>this.params.onUsage?.($,Q))}return}case"conversation.item.input_audio_transcription.completed":{let $=J;if(this.say("user",String($.transcript??"")),$.transcriptionUsage||$.transcriptionSeconds!==void 0){this.transcription={usage:$.transcriptionUsage?k(this.transcription.usage,$.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+($.transcriptionSeconds??0)};let Q=this.info(),Z={...$.transcriptionUsage?{usage:$.transcriptionUsage}:{},...$.transcriptionSeconds!==void 0?{seconds:$.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}return}case"response.output_audio_transcript.done":this.say("assistant",String(J.transcript??""));return;case"response.output_text.done":this.say("assistant",String(J.text??""));return;case"response.function_call_arguments.done":{let $=J;if(this.touch(),!this.ending)this.call($.call_id,$.name,$.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let $=J.error;if(this.errors.push({code:$?.code,message:String($?.message??"")}),this.pendingCreate&&$?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,$.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let $=J;if(!this.ending&&!$.byClient)this.end($.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,$){if($.trim())this.transcript.push({role:J,text:$,at:Date.now()})}call(J,$,Q){let Z=P6(Q);if($===this.delegateName){let K=typeof Z.request==="string"?Z.request.trim():"";if(!K)return this.answer(J,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:K,status:"queued"},turn:{text:K},callId:J})}let W=this.toolHandlers.get($);if(W)return void this.runTool(J,W,Z);switch($){case"stop_work":{let K=this.running;if(K)K.stopRequested=!0,K.handle?.stop({reason:"Stopped by voice."});let X=this.dropQueue();return this.answer(J,{stopped:Boolean(K),dropped:X})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((K)=>K.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(J,{status:"error",message:"There is no open question."});let K=typeof Z.answer==="string"?Z.answer:"",X=typeof Z.approve==="boolean"?Z.approve:void 0,Y=this.pending.map((V)=>U6(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:Y},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${$}.`})}}enqueue(J){if(!this.running){this.requests.push(J.record),this.run(J);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(J.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(J.record),this.queue.push(J),this.answer(J.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),J.callId=void 0}async run(J){this.running=J,J.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let $=new Set;await this.waitForThread($);let Q=await this.latestBody();while(!J.stopRequested&&await this.waitForThread($));if(J.stopRequested||this.ending){J.record.status="dropped",this.complete(J,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:Q,turn:J.turn})}catch(K){J.record.status="refused",this.complete(J,{status:"refused",message:K instanceof Error?K.message:"The request could not be started."});return}J.handle=Z,J.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(J.record.status="done",J.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(J,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(J,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(J,{status:"stopped",text:W.text});else this.complete(J,{status:"done",text:W.text})}catch($){J.record.status="done",this.complete(J,{status:"failed",message:$ instanceof Error?$.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let $=this.queue.shift();if($&&!this.ending)this.run($);else this.touch()}}async runTool(J,$,Q){let Z=$.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let K={name:Z,status:"running"};this.toolCalls.push(K),this.toolsRunning+=1,this.pauseIdle();let X=new AbortController,Y=$.timeoutMs??this.limits.toolTimeoutMs,V,G;try{let D=await Promise.race([$.run(Q,{sessionId:this.sessionId,signal:X.signal}),new Promise((z,F)=>{V=setTimeout(()=>{F(new l(`"${Z}" took longer than ${Math.round(Y/1000)} s.`)),X.abort()},Y)})]);K.status="done",G={status:"done",output:this.clip(D)}}catch(D){if(D instanceof lJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let z=D instanceof l?D.message:"The tool failed.";if(!(D instanceof l))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);K.status="failed",K.message=z,G={status:"failed",message:z}}finally{clearTimeout(V),K.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let H=this.info();if(this.hook(()=>this.params.onToolCall?.({...K},H)),!this.ending)this.answer(J,G)}clip(J){let $;try{$=JSON.stringify(J)}catch{return String(J)}if($===void 0||$.length<=this.limits.toolOutputChars)return J;return`${$.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${$.length} characters in all)`}async waitForThread(J=new Set){let $=this.params.liveRuns;if(!$)return!1;let Q=await $.find({threadId:this.threadId}),Z=Q&&!J.has(Q.runId)?$.get(Q.runId):null;if(!Q||!Z)return!1;return J.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let $=await J.get(this.sessionId).catch(()=>null);if($)this.body=$.body;return this.body}async follow(J){let $=this.params.progress??N6();try{for await(let Q of J.run){let Z=$(Q);if(Z)this.note(Z)}}catch{}}complete(J,$){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,$),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify($)}`);this.respond()}answer(J,$){this.sideband.functionOutput(J,$),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let J=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=J,this.sideband.send({type:"response.create",event_id:J})}questions(){return this.pending.map((J)=>({kind:J.kind,tool:String(J.name),input:J.input}))}dropQueue(){let J=this.queue.splice(0);for(let $ of J)$.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let $=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if($<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),$)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let J=this.info();this.hook(()=>this.params.onTick?.(J))}hook(J){this.hooks=this.hooks.then(async()=>{try{await J()}catch($){if($ instanceof lJ)this.end("usage",$.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",$),this.end("error",this.lines.error)}})}tampered(J){let $=this.params.session;if(!$||!J)return!1;if($.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==$.instructions)return!0;if(Array.isArray(J.tools)){let Q=new Set([...UJ(this.params.delegate),...$.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if(Q.size!==Z.size||[...Q].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,$){for(let X of this.timers)clearTimeout(X);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),$&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine($);if(J!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,K={sessionId:this.sessionId,...this.callId?{callId:this.callId}:{},threadId:this.threadId,reason:J,startedAt:this.startedAt,endedAt:Z,durationMs:W,seconds:Math.ceil(W/1000),usage:this.usage,transcription:this.transcription,transcript:this.transcript,requests:this.requests,toolCalls:this.toolCalls,errors:this.errors};pJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(K)}catch(X){console.error("[gemi/ai] a voice session's onEnd threw.",X)}return this.resolveEnded(K),K}async hangUp(){try{await this.hangupCall()}catch(J){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",J),this.errors.push({code:"hangup_failed",message:J instanceof Error?J.message:String(J)});let $;await Promise.race([this.sideband.closed,new Promise((Q)=>$=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout($),this.sideband.close()}}async closingLine(J){await new Promise(($)=>{let Q=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",K,X=setTimeout(Y,this.limits.closingLineMs);function Y(){clearTimeout(X),$()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(G)=>{let H=G;if(H.type==="sideband.closed")return Y();if(W==="cancelling"){if(H.type==="response.done"||H.type==="error"&&H.error?.event_id===Z)V();return}if(H.type==="error"&&H.error?.event_id===Q)return Y();if(H.type==="response.created"&&!K){K=H.response?.id;return}let D=(z)=>!K||!z||z===K;if(H.type==="response.done"&&D(H.response?.id))W="playing";else if(H.type==="output_audio_buffer.stopped"&&W==="playing"&&D(H.response_id))Y()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function u9(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function P6(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function U6(J,$,Q){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:$};if(J.kind==="approval")return{...Z,approve:Q===!0,...$?{reason:$}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function N6(){let J=new Set;return($)=>{if($.type==="tool-call"){if($.part.partial||$.resent||J.has($.part.toolCallId))return;return J.add($.part.toolCallId),`running ${String($.part.name)}`}if($.type==="tool-progress"){let Q=$.data;if(typeof Q==="string")return Q;if(Q&&typeof Q==="object")for(let Z of["message","label","title"]){let W=Q[Z];if(typeof W==="string"&&W)return W}}return}}var c9="http://gemi.internal/__gemi__/voice/mcp";async function c$(J,$){if(!$.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:Q}=J,Z=J.scopes??Q.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:$.user,via:"voice",id:`voice:${$.sessionId}`,scopes:Z}});return(await Q.available(W(m9()),J.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(Y,V)=>{let G=m9();return p.run(G,async()=>{return await J.authorize?.({name:X.name,input:Y,sessionId:V.sessionId}),Q.execute(W(G),X.name,Y,void 0,{signal:V.signal})},{user:$.user})}}))}function m9(){return new b(new Request(c9,{method:"POST"}),{},"api",new URL(c9).pathname)}class m${records=new Map;retainEndedMs;constructor(J={}){this.retainEndedMs=J.retainEndedMs??600000}async create(J){this.sweep(),this.records.set(J.id,structuredClone(J))}async get(J){let $=this.records.get(J);return $?structuredClone($):null}async update(J,$){let Q=this.records.get(J);if(!Q)return;this.records.set(J,{...Q,...structuredClone($),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[$,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<J)this.records.delete($)}}var p$=new m$;var p9=new WeakMap,l9=100;class l${threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(J,$={}){this.threadsTable=d9($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=d9($.messagesTable??"gemi_agent_messages","messages"),this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.options=$}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A DatabaseAgentStore scope is a non-empty string.");let $=new l$({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return $.scope=J,$}async createTable(){let J=C6(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($);await this.addScopeColumns()}async addScopeColumns(){let J=O6(this.dialect,this.threadsTable,this.messagesTable);for(let[$,Q]of J){if(await this.hasColumn($,"scope"))continue;for(let Z of Q)await this.sql.unsafe(Z)}}async hasColumn(J,$){try{return await this.sql.unsafe(`SELECT ${$} FROM ${this.quote(J)} WHERE 1 = 0`),!0}catch{return!1}}async createThread(J){let $=crypto.randomUUID(),Q=J.userId===void 0||J.userId===null?null:String(J.userId);return await this.run(async(Z)=>{let W=this.clock(Z);if(this.scope===null)await Z`
180
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_scope_kind_created_at_idx" ON "${$}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${$}_scope_key_key" ON "${$}"("scope", "key")`]}var NQ={n:0,mean:0,stddev:0,low:null,high:null};function v(J){let $=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if(J<0.5)return Math.log(Math.PI/Math.sin(Math.PI*J))-v(1-J);J-=1;let Q=$[0],Z=J+7.5;for(let W=1;W<9;W++)Q+=$[W]/(J+W);return 0.5*Math.log(2*Math.PI)+(J+0.5)*Math.log(Z)-Z+Math.log(Q)}function FQ(J,$,Q){let W=1,K=1-(J+$)*Q/(J+1);if(Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let X=K;for(let G=1;G<=300;G++){let V=2*G,Y=G*($-G)*Q/((J+V-1)*(J+V));if(K=1+Y*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+Y/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(K=1/K,X*=K*W,Y=-(J+G)*(J+$+G)*Q/((J+V)*(J+V+1)),K=1+Y*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+Y/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let z=K*W;if(X*=z,Math.abs(z-1)<0.00000000000001)break}return X}function F8(J,$,Q){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(v($+Q)-v($)-v(Q)+$*Math.log(J)+Q*Math.log(1-J));return J<($+1)/($+Q+2)?Z*FQ($,Q,J)/$:1-Z*FQ(Q,$,1-J)/Q}function dJ(J,$){return F8($/($+J*J),$/2,0.5)}function N8(J){if(!(J>0))return Number.POSITIVE_INFINITY;let $=1.959964,Q=2;while(dJ(Q,J)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=($+Q)/2;if(dJ(W,J)>0.05)$=W;else Q=W}return($+Q)/2}function O8(J,$,Q,Z){let W=J+Q,K=$+Z,X=(z,D)=>v(z+1)-v(D+1)-v(z-D+1),G=(z)=>Math.exp(X($,z)+X(Z,W-z)-X(K,W)),V=G(J),Y=0;for(let z=Math.max(0,W-Z);z<=Math.min($,W);z++){let D=G(z);if(D<=V*1.0000001)Y+=D}return Math.min(1,Y)}function OQ(J,$){if(J.length<2)return 0;let Q=J.reduce((W,K)=>W+(K-$)**2,0),Z=Math.sqrt(Q/(J.length-1));return Z<0.000000000001*Math.max(1,Math.abs($))?0:Z}function nJ(J){let $=J.length;if($===0)return NQ;let Q=J.map((G)=>G?1:0),Z=Q.reduce((G,V)=>G+V,0)/$,W=3.841458881296,K=(Z+W/(2*$))/(1+W/$),X=1.959964*Math.sqrt(Z*(1-Z)/$+W/(4*$*$))/(1+W/$);return{n:$,mean:Z,stddev:OQ(Q,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function oJ(J){let $=J.length;if($===0)return NQ;let Q=J.reduce((K,X)=>K+X,0)/$,Z=OQ(J,Q);if($<2||Z===0)return{n:$,mean:Q,stddev:Z,low:null,high:null};let W=N8($-1)*Z/Math.sqrt($);return{n:$,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function $J(J,$,Q){return{before:J.mean,after:$.mean,delta:$.mean-J.mean,p:Q,pAdjusted:Q,significant:!1}}function CQ(J,$){if(J.n===0||$.n===0)return $J(J,$,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return $J(J,$,O8(Q(J),J.n,Q($),$.n))}function UQ(J,$){if(J.n<2||$.n<2)return $J(J,$,null);let Q=J.stddev**2/J.n,Z=$.stddev**2/$.n,W=Math.sqrt(Q+Z);if(W===0)return $J(J,$,null);let K=(Q+Z)**2/(Q**2/(J.n-1)+Z**2/($.n-1));return $J(J,$,dJ(($.mean-J.mean)/W,K))}function LQ(J,$,Q){if(Q==="holm"){let Z=J.filter((K)=>K.p!==null).sort((K,X)=>K.p-X.p),W=0;Z.forEach((K,X)=>{W=Math.max(W,Math.min(1,K.p*(Z.length-X))),K.pAdjusted=W})}else for(let Z of J)Z.pAdjusted=Z.p;for(let Z of J)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<$&&Z.delta!==0}class MJ{name;cases;runs;concurrency;graders;pricing;task;constructor(J){this.name=J.name,this.cases=J.cases,this.runs=J.runs??1,this.concurrency=J.concurrency??1,this.task=J.task,this.graders=typeof J.graders==="function"?J.graders({judge:($)=>MJ.judge($)}):J.graders,this.pricing=J.pricing}static create(J){let $=`The eval "${J.name}"`;QJ(J.runs,$,"runs"),QJ(J.concurrency,$,"concurrency");let Q=new Set;for(let W of J.cases){if(Q.has(W.id))throw Error(`${$} has two cases with the id "${W.id}".`);Q.add(W.id)}let Z=new MJ(J);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")QJ(K.samples,`${$}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,$,Q={}){return RQ(J,$,Q)}static format(J,$={}){return _8(J,$)}async run(J={}){let $=`${this.name}.run`;QJ(J.runs,$,"runs"),QJ(J.concurrency,$,"concurrency");let Q=J.only?new Set(J.only):null;if(Q){let F=[...Q].filter((H)=>!this.cases.some((C)=>C.id===H));if(F.length>0)throw Error(`The eval "${this.name}" has no case ${F.map((H)=>`"${H}"`).join(", ")}.`)}let Z=J.runs??this.runs,W=Date.now(),K=new AbortController,X=J.signal?AbortSignal.any([J.signal,K.signal]):K.signal,G=this.cases.filter((F)=>!Q||Q.has(F.id)),V={};for(let[F,H]of Object.entries(this.graders)){if(X.aborted)break;if(typeof H==="function"||H.kind!=="judge"||!H.calibration)continue;V[F]=await this.calibrate(H,X)}let Y=G.flatMap((F)=>Array.from({length:Z},(H,C)=>({test:F,run:C+1}))),z=Array.from({length:Y.length}),D=0,N,P=async()=>{while(D<Y.length&&!X.aborted){let F=D++,H=Y[F],C=await this.sample(H.test,H.run,X,J.keepOutputs??!1);z[F]=C;try{J.onSample?.(C)}catch(L){N??={error:L},K.abort(L)}}},U=Math.min(J.concurrency??this.concurrency,Y.length);if(await Promise.all(Array.from({length:U},P)),N)throw N.error;let O=z.filter((F)=>F!==void 0);return this.report(O,V,Z,new Date(W).toISOString(),Date.now()-W,{aborted:X.aborted||O.length<Y.length,planned:G.map((F)=>F.id)})}async sample(J,$,Q,Z){let W=Date.now(),K,X,G=await ZJ(async()=>{try{K=await this.task(J.input,{case:J,run:$,signal:Q})}catch(U){X=kQ(U)}}),V={},Y=!1,z=await ZJ(async()=>{if(X!==void 0)return;let U={case:J,input:J.input,run:$};for(let[O,F]of Object.entries(this.graders)){if(J.skip?.includes(O))continue;let H=await _Q(F,K,U,Q);if(!H)continue;if(V[O]=H,!H.pass&&typeof F!=="function"&&F.gate)Y=!0}}),D=Object.values(V).map((U)=>U.score),N=X===void 0&&D.length===0,P=this.pricing?sJ(this.pricing,G.byModel).cost+sJ(this.pricing,z.byModel).cost:void 0;return{case:J.id,run:$,pass:X===void 0&&!N&&Object.values(V).every((U)=>U.pass),excluded:Y||N,...N?{ungraded:!0}:{},score:X!==void 0||N?0:EQ(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:G.usage,byModel:U8(G.byModel,z.byModel),judgeUsage:z.usage,...P!==void 0?{cost:P}:{},durationMs:Date.now()-W}}async calibrate(J,$){let Q=J.calibration,Z=[],W=0,K=await ZJ(async()=>{for(let[V,Y]of Q.examples.entries()){if($.aborted)break;let z=Y.id??`example-${V+1}`,D={case:{id:z,input:Y.input},input:Y.input,run:0},N=await _Q(J,Y.output,D,$),P=N?.pass??!1;if(P===Y.expected)W++;else Z.push({id:z,expected:Y.expected,got:P,...N?.note?{note:N.note}:{}})}}),X=Q.examples.length,G=X===0?1:W/X;return{n:X,agreement:G,ok:G>=(Q.minAgreement??0.8),disagreements:Z,usage:K.usage}}report(J,$,Q,Z,W,K){let X=new Set(Object.entries(this.graders).filter(([,N])=>typeof N!=="function"&&N.gate).map(([N])=>N)),G={};for(let N of this.cases){let P=J.filter((U)=>U.case===N.id);if(P.length===0)continue;G[N.id]={...BQ(P),graders:MQ(P,X)}}let V=A(),Y=A(),z={};for(let N of J){V=k(V,N.usage),Y=k(Y,N.judgeUsage);for(let[P,U]of Object.entries(N.byModel))z[P]=k(z[P]??A(),U)}let D=this.pricing?sJ(this.pricing,z):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:Q,aborted:K.aborted,planned:K.planned,samples:J,cases:G,graders:MQ(J,X),calibration:$,totals:{...BQ(J),usage:V,judgeUsage:Y,byModel:z,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(z)}}}}async function _Q(J,$,Q,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return aJ(await J($,Q),W);if(J.kind!=="judge")return aJ(await J.check($,Q),W);return await C8(J,$,Q,W,Z)}catch(K){return{pass:!1,score:0,error:kQ(K)}}}async function C8(J,$,Q,Z,W){let K=await J.prompt($,Q),X=typeof K==="string"?{prompt:K}:K,G=[];for(let D=0;D<(J.samples??1)&&!W.aborted;D++){let N=await tJ({signal:W,provider:J.provider,...J.instructions!==void 0?{instructions:J.instructions}:{},...X,output:J.output,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},...J.maxOutputTokens!==void 0?{maxOutputTokens:J.maxOutputTokens}:{},...J.temperature!==void 0?{temperature:J.temperature}:{},logErrors:!1});if(!N.ok){G.push({pass:!1,score:0,error:`The judge failed: ${N.error.message}`});continue}let P=aJ(J.verdict(N.output,Q),Z);if(P)G.push(P)}if(G.length===0)return null;if(G.length===1)return G[0];let V=G.filter((D)=>D.pass).length,Y=G.map((D)=>D.note??D.error).filter(Boolean),z=G.map((D)=>D.error).filter(Boolean);return{pass:V*2>G.length,score:EQ(G.map((D)=>D.score)),...Y.length>0?{note:Y.join(" | ")}:{},...z.length===G.length?{error:z.join(" | ")}:{}}}function aJ(J,$){if(J===null||J===void 0)return null;if(typeof J==="boolean")return{pass:J,score:J?1:0};if(typeof J==="number"){if(!Number.isFinite(J))throw Error(`A grader answered the score ${J}.`);let Q=SQ(J);return{pass:Q>=$,score:Q}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:SQ(J.score),...J.note!==void 0?{note:J.note}:{}}}function BQ(J){let $=J.filter((Q)=>!Q.excluded);return{samples:J.length,kept:$.length,passed:$.filter((Q)=>Q.pass).length,errors:J.filter((Q)=>Q.error!==void 0).length,passRate:nJ($.map((Q)=>Q.pass)),score:oJ($.map((Q)=>Q.score))}}function MQ(J,$){let Q=J.filter((W)=>!W.excluded),Z=[...new Set(J.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let X=($.has(W)?J:Q).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:nJ(X.map((G)=>G.pass)),score:oJ(X.map((G)=>G.score))}]}))}function sJ(J,$){let Q=0,Z=[];for(let[W,K]of Object.entries($)){let X=AQ(J,W,K);if(X===void 0){Z.push(W);continue}Q+=X}return{cost:Q,unpriced:Z}}function U8(...J){let $={};for(let Q of J)for(let[Z,W]of Object.entries(Q))$[Z]=k($[Z]??A(),W);return $}function RQ(J,$,Q){for(let[F,H]of[["baseline",J],["current report",$]])if(H.aborted)throw Error(`Eval.compare: the ${F} for "${H.name}" was aborted (${H.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`);let Z=Q.alpha??0.05,W=Q.adjust??"holm",K=[],X=(F,H,C)=>{let L={label:F,passRate:CQ(H.passRate,C.passRate),score:UQ(H.score,C.score)};return K.push(L),{passRate:L.passRate,score:L.score}},G=(F,H,C)=>Object.fromEntries(Object.keys(C).filter((L)=>(L in H)).map((L)=>[L,X(`${F} ${L}`,H[L],C[L])])),V=(F,H)=>({fromCurrent:F.filter((C)=>!H.includes(C)),fromBaseline:H.filter((C)=>!F.includes(C))}),Y=X("total",J.totals,$.totals),z=G("case",J.cases,$.cases),D=G("grader",J.graders,$.graders),N=K.flatMap((F)=>[F.passRate,F.score]);LQ(N,Z,W);let P={cases:V([...new Set([...J.planned??[],...Object.keys(J.cases)])],[...new Set([...$.planned??[],...Object.keys($.cases)])]),graders:V(Object.keys(J.graders),Object.keys($.graders))},U=[...P.cases.fromCurrent.map((F)=>`case ${F}: in the baseline, missing from this report`),...P.graders.fromCurrent.map((F)=>`grader ${F}: in the baseline, missing from this report`)],O=[];for(let F of K)for(let[H,C]of[["pass rate",F.passRate],["score",F.score]]){if(!C.significant)continue;let L=`${F.label}: ${H} ${C.before.toFixed(2)} \u2192 ${C.after.toFixed(2)} (p = ${L8(C.pAdjusted)})`;(C.delta<0?U:O).push(L)}return{totals:Y,cases:z,graders:D,missing:P,comparisons:N.filter((F)=>F.p!==null).length,alpha:Z,adjust:W,regressions:U,improvements:O}}function L8(J){return J<0.001?"<0.001":J.toFixed(3)}function _8(J,$){let Q=$.baseline&&!$.baseline.aborted&&!J.aborted?RQ($.baseline,J,$):void 0,{totals:Z}=J,W=[];if(W.push(`eval ${J.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(J.durationMs/1000).toFixed(1)}s)`),J.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let K=(Y)=>{if(Y.n===0)return"-";let z=Y.mean.toFixed(2);if(Y.low===null||Y.high===null)return`${z} (${Y.n===1?"n=1":"no spread"})`;return`${z} [${Y.low.toFixed(2)}, ${Y.high.toFixed(2)}]`},X=(Y)=>Y?` ${Y.delta>=0?"+":""}${Y.delta.toFixed(2)}${Y.significant?"*":""}`:"",G=(Y,z)=>{let D=[0,1,2,3].map((P)=>Math.max(...[[Y,"n","pass rate","score"],...z].map((U)=>U[P].length))),N=(P)=>P.map((U,O)=>U.padEnd(D[O])).join(" ").trimEnd();W.push("",N([Y,"n","pass rate","score"]),...z.map(N))};G("case",Object.entries(J.cases).map(([Y,z])=>[Y,`${z.kept}/${z.samples}`,K(z.passRate)+X(Q?.cases[Y]?.passRate),K(z.score)+X(Q?.cases[Y]?.score)])),G("grader",Object.entries(J.graders).map(([Y,z])=>[Y,String(z.passRate.n),K(z.passRate)+X(Q?.graders[Y]?.passRate),K(z.score)+X(Q?.graders[Y]?.score)])),W.push("",`total pass rate ${K(Z.passRate)}${X(Q?.totals.passRate)} score ${K(Z.score)}${X(Q?.totals.score)}`);for(let[Y,z]of Object.entries(J.calibration))W.push(`judge ${Y}: agreement ${z.agreement.toFixed(2)} on ${z.n} examples${z.ok?"":" (BELOW minAgreement)"}`);let V=(Y)=>`${Y.inputTokens} in, ${Y.outputTokens} out`;if(W.push(`tokens: task ${V(Z.usage)}; judges ${V(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),Q){W.push("",`* significant at ${Q.alpha} over ${Q.comparisons} tests (${Q.adjust==="holm"?"Holm-adjusted":"unadjusted"}; Fisher's exact for pass rates, Welch's t for scores)`);for(let Y of Q.regressions)W.push(`regression: ${Y}`);for(let Y of Q.improvements)W.push(`improvement: ${Y}`)}return W.join(`
181
+ `)}function EQ(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function SQ(J){return Math.min(1,Math.max(0,J))}function kQ(J){return J instanceof Error?J.message:String(J)}function QJ(J,$,Q){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${$} sets \`${Q}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var B8=/^[A-Za-z0-9_-]{1,64}$/;function M8(J,$){let Q=S8($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((z)=>rJ(J,z,Z));let K=Object.entries(Q.namespaces),X=new Set(J.descriptors().flatMap((z)=>z.tags));for(let[z,D]of K){if(!B8.test(z))throw Error(`toAgentTools: "${z}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${z}" needs a description. It is what the model reads to decide whether to look inside.`);if(!X.has(z))throw Error(`toAgentTools: no tool is tagged "${z}", so its namespace would be empty.`)}let G=new Map(K.map(([z])=>[z,[]])),V=[];for(let z of W){let D=K.find(([N])=>z.tags.includes(N))?.[0];if(D===void 0)V.push(rJ(J,z,Z));else G.get(D).push(rJ(J,z,!1))}let Y=[];for(let[z,D]of K){let N=G.get(z);if(N.length===0)continue;Y.push(eJ.create({name:z,description:D.description,tools:N,deferred:D.deferred??Z}))}return[...Y,...V]}function S8(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function rJ(J,$,Q){if($.kind==="tool")return A8(J,$,Q);return SJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Q,execute:(Z,W)=>{let K=h.getStore()?.req;if(!K)throw new g(`"${$.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return J.execute({kind:"local",req:K},$.name,Z,W)}})}function A8(J,$,Q){let Z=J.nativeTool($.name);return SJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:J.nativeApproval($.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,K)=>{let X=h.getStore()?.req;return J.startNative(X?{kind:"local",req:X}:void 0,$.name,W,K)}})}function R8(J){if(J==="auto")return;let $=/^(\d+)x(\d+)$/.exec(J);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let Q=Number($[1]),Z=Number($[2]);if(Q%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max(Q/Z,Z/Q)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function TQ(J,$){if(J.size!==void 0)try{R8(J.size)}catch(Q){throw Error(`${$}: ${Q.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let Q=J.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Q}.`)}}function jQ(J,$){if(J instanceof File)return J;let Q=J.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([J],`${$}.${Z}`,{type:Q})}class J${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;TQ(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new J$(J)}async generate(J){let $=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...$,signal:J.signal}))}async edit(J){let $=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...$,images:J.images.map((Q,Z)=>jQ(Q,`image-${Z}`)),...J.mask?{mask:jQ(J.mask,"mask")}:{},signal:J.signal}))}present(J){return xQ(this.provider.model,J.usage),E8(J)}merge(J){let $={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return TQ($,`ImageModel "${this.name}"`),$}}function E8(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}var $$=300000;function Q$(J){return{generationsUrl:`${J.base}/images/generations${J.query}`,editsUrl:`${J.base}/images/edits${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}class AJ extends Error{code;retryable;retryAfter;constructor(J,$={}){super(J.message,$);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var k8={png:"image/png",jpeg:"image/jpeg"};function T8(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let K=J?.output_tokens_details?.image_tokens;if(typeof K==="number")Z.imageOutputTokens=K;return Z}function j8(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function x8(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new AJ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof J.output_format==="string"?J.output_format:"png";return{bytes:j8(Q),mimeType:k8[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:T8(J.usage)}}async function wQ(J,$,Q,Z){let W;try{W=await IQ(J,$,{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(K){if(Z.signal?.aborted)throw K;throw new AJ(o(K),{cause:K})}return x8(await W.json())}async function fQ(J,$,Q={}){return await wQ(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function qQ(J,$,Q={}){return await wQ(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class RJ{static models(){return[]}modelName(){return this.model}async generate(J){return await fQ(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let $=new FormData;for(let[Q,Z]of Object.entries(this.body(J)))if(Z!==void 0)$.set(Q,String(Z));for(let Q of J.images)$.append("image[]",Q,Q.name);if(J.mask)$.set("mask",J.mask,J.mask.name);return await qQ(this.endpoint(),$,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return o(J)}}var vQ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class Z$ extends RJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new Z$(J,$)}static models(){return vQ}endpoint(){return Q$(bQ(this.config,{timeoutMs:$$}))}}class W$ extends RJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new W$(J,$)}static models(){return vQ}modelName(){return this.config.deployment??this.model}endpoint(){return Q$(yQ(this.config,{timeoutMs:$$}))}}class EJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,$){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return!0;let Z=this.now();if(Z<Q.openUntil)return!1;if(Q.probeUntil!==void 0&&Z<Q.probeUntil)return!1;return Q.probeUntil=Z+$.cooldownMs,!0}record(J,$,Q){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if($==="success")return this.entries.delete(J),W?"closed":void 0;if($==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let $=this.entries.get(J);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}var gQ=Symbol("timed-out");class WJ extends Y${model;capabilities;entries;options;circuit;constructor(J,$={}){super();if(J.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of J)if(Z.timeoutMs!==void 0&&!(Z.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${Z.provider.model} must be a positive number, got ${Z.timeoutMs}.`);this.entries=[...J];let Q=$.circuit;if(Q){let Z=Q.failures??3,W=Q.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let K=new Set;for(let G of J){let V=K$(G);if(K.has(V))throw Error(`FallbackProvider: two legs share the circuit key "${V}". Give one of them a \`circuitKey\`.`);K.add(V)}let X=Q.store??new EJ;this.options={...$,circuit:{...Q,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=I8(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new WJ(J,$)}from(J){if(!Number.isInteger(J)||J<0||J>=this.entries.length)throw RangeError(`FallbackProvider.from(${J}): the chain has ${this.entries.length} entries.`);return new WJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new WJ([$],this.options)}upload(J){return this.entries[0].provider.upload(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let $,Q=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let K=this.entries[W],X=W===this.entries.length-1,G=K.provider.model;if(this.circuit&&!X&&!await this.allow(K))continue;Z+=1;let V=!1,Y=async(B)=>{if(V)return;V=!0,await this.record(W,K,B)},z=new AbortController,D=()=>z.abort(Q?.reason);if(Q?.aborted)z.abort(Q.reason);else Q?.addEventListener("abort",D,{once:!0});let N=[],P=!1,U=!1,O,F,H,C=!1,L,T=!1,R=(B)=>{let E=$?k(k(A(),$),B.usage):B.usage;return $=void 0,{...B,usage:E}};try{L=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:z.signal})[Symbol.asyncIterator]();let B=K.timeoutMs!==void 0?Date.now()+K.timeoutMs:void 0;for(;;){let E=!P&&B!==void 0?await w8(L.next(),Math.max(0,B-Date.now())):await L.next();if(E===gQ){C=!0,H={error:{code:"provider_error",message:`${G} did not start answering within ${K.timeoutMs}ms.`,retryable:!0}};break}if(E.done){T=!0;break}let _=E.value;if(_.type==="finish"&&_.model)F=_.model;if(_.type==="retry"){yield _;continue}if(P){if(_.type==="finish")O=k(O??A(),_.usage),U=!0,yield R(_);else{if(_.type==="error")H={error:_.error};yield _}continue}if(hQ(_)){P=!0,await Y("success"),yield*N.splice(0),yield _;continue}if(_.type==="error")H={error:_.error,..._.status!==void 0?{status:_.status}:{},..._.requestId!==void 0?{requestId:_.requestId}:{}};else if(_.type==="finish"){if(O=k(O??A(),_.usage),_.reason==="error"&&!H)H={error:{code:"provider_error",message:`${G} ended the call with an error and did not say which.`,retryable:!1}}}N.push(_)}}catch(B){let E=K.provider.normalizeError(B);if(P){if(E.code!=="aborted")yield{type:"error",error:E,...G$(B)};this.report({index:W,model:G,responseModel:F,attempt:Z,usage:O,outcome:X$(E),error:E}),yield R({type:"finish",reason:E.code==="aborted"?"aborted":"error",usage:A(),...F?{model:F}:{}});return}H={error:E,...G$(B)}}finally{if(Q?.removeEventListener("abort",D),!T)z.abort(),L?.return?.()?.catch(()=>{})}if(P){if(!U&&$)yield{type:"finish",reason:H?"error":"stop",usage:$},$=void 0;this.report({index:W,model:G,responseModel:F,attempt:Z,usage:O,outcome:H?X$(H.error):"ok",...H?{error:H.error}:{}});return}if(Q?.aborted){await Y("none"),this.report({index:W,model:G,responseModel:F,attempt:Z,usage:O,outcome:"aborted"}),yield R({type:"finish",reason:"aborted",usage:O??A(),...F?{model:F}:{}});return}if(!H){await Y("success"),this.report({index:W,model:G,responseModel:F,attempt:Z,usage:O,outcome:"ok"});for(let B of N)yield B.type==="finish"?R(B):B;return}let x=!X&&H.error.code!=="aborted"&&this.shouldFallBack(H.error,{index:W,model:G,timedOut:C,...H.status!==void 0?{status:H.status}:{},...H.requestId!==void 0?{requestId:H.requestId}:{}});if(await Y(x?"failure":"none"),this.report({index:W,model:G,responseModel:F,attempt:Z,usage:O,outcome:x?"fallback":X$(H.error),error:H.error}),x){if(O)$=k($??A(),O);continue}let m=!1,p;for(let B of N){if(B.type==="finish"){p=B;continue}if(B.type==="error")m=!0;yield B}if(!m&&H.error.code!=="aborted")yield{type:"error",error:H.error,...H.status!==void 0?{status:H.status}:{},...H.requestId!==void 0?{requestId:H.requestId}:{}};yield R({type:"finish",reason:H.error.code==="aborted"?"aborted":p?.reason??"error",usage:O??A(),...F?{model:F}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(K$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=K$($),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:$.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,$){let Q=this.options.fallbackOn??((Z)=>Z.retryable);try{return Q(J,$)}catch{return!1}}report(J){if(J.usage===void 0)delete J.usage;if(J.responseModel===void 0)delete J.responseModel;try{this.options.onUsage?.(J)}catch{}}}function K$(J){return J.circuitKey??J.provider.model}function X$(J){return J.code==="aborted"?"aborted":"failed"}function I8(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch)}}function w8(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(gQ),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function f8(J,$,Q={}){let Z=Q.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let K=0;K<J.entries.length;K++){let X=J.leg(K),G={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{G.results.push(await $(X,{index:K,sample:V}))}catch(Y){G.errors.push({sample:V,error:Y})}W.push(G)}return W}class TJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var XJ="ask_agent",q8={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},b8={maxDuration:"We've reached the time limit for this voice session. Tap the microphone to start again.",idle:"It's gone quiet, so I'll hang up. Tap the microphone when you want to talk again.",error:null};function KJ(J={}){return[{name:J.name??XJ,description:J.description??"Hand one self-contained request to the agent that does the work, in the user's own words with references resolved. It can take minutes; the result comes back when it is done, so tell the user you are on it.",parameters:{type:"object",properties:{request:{type:"string",description:"What the user wants done."}},required:["request"],additionalProperties:!1}},{name:"stop_work",description:"Stop the work that is running, and drop any requests waiting behind it.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"work_status",description:"What the agent is doing right now, and what is waiting.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"answer_question",description:"Answer the question the agent asked (it came back from a request with status needs_input). For an approval, set approve.",parameters:{type:"object",properties:{answer:{type:"string",description:"The user's answer, in their words."},approve:{type:"boolean",description:"For an approval: whether the user approved."}},required:["answer"],additionalProperties:!1}}]}var kJ=new Map;class u{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=A();transcription={usage:A(),seconds:0};hooks=Promise.resolve();pendingCreate;transcript=[];requests=[];toolCalls=[];toolHandlers=new Map;toolsRunning=0;toolCallTimes=[];errors=[];running;queue=[];pending=[];lastProgress;lastNoteAt=0;noteTimer;responseActive=!1;responseWanted=!1;ending;timers=[];idleTimer;tickTimer;resolveEnded;closingWaiter;static start(J){return new u(J)}static get(J){return kJ.get(J)}static async endAll(J){await Promise.all([...kJ.values()].map(($)=>$.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...q8,...uQ(J.limits)},this.lines={...b8,...uQ(J.lines)},this.delegateName=J.delegate?.name??XJ;let $=new Set(KJ(J.delegate).map((Q)=>Q.name));for(let Q of J.tools??[]){if($.has(Q.tool.name)||this.toolHandlers.has(Q.tool.name))throw Error(`VoiceBridge: two tools are named "${Q.tool.name}".`);this.toolHandlers.set(Q.tool.name,Q)}if("realtime"in J.call){let{realtime:Q,callId:Z}=J.call;this.callId=Z,this.sideband=Q.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=J.call.callId??J.call.sideband.callId,this.sideband=J.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise((Q)=>this.resolveEnded=Q),kJ.set(this.sessionId,this),this.timers.push(setTimeout(()=>void this.end("max_duration",this.lines.maxDuration),this.limits.maxDurationMs)),this.tickTimer=setInterval(()=>void this.tick(),this.limits.tickMs),this.touch(),this.listen()}setBody(J){this.body=J;let $=this.params.contextNote?.(J);if($)this.sideband.addNote($)}end(J="hangup",$){return this.ending??=this.finish(J,$??null)}async listen(){for await(let J of this.sideband){try{this.params.onEvent?.(J)}catch{}this.closingWaiter?.(J),await this.handle(J)}}async handle(J){switch(J.type){case"input_audio_buffer.speech_started":this.touch();return;case"response.created":this.responseActive=!0,this.pendingCreate=void 0,this.touch();return;case"response.done":{if(this.responseActive=!1,this.responseWanted&&!this.ending)this.responseWanted=!1,this.createResponse();let $=J.usage;if($){this.usage=k(this.usage,$);let Q=this.info();this.hook(()=>this.params.onUsage?.($,Q))}return}case"conversation.item.input_audio_transcription.completed":{let $=J;if(this.say("user",String($.transcript??"")),$.transcriptionUsage||$.transcriptionSeconds!==void 0){this.transcription={usage:$.transcriptionUsage?k(this.transcription.usage,$.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+($.transcriptionSeconds??0)};let Q=this.info(),Z={...$.transcriptionUsage?{usage:$.transcriptionUsage}:{},...$.transcriptionSeconds!==void 0?{seconds:$.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}return}case"response.output_audio_transcript.done":this.say("assistant",String(J.transcript??""));return;case"response.output_text.done":this.say("assistant",String(J.text??""));return;case"response.function_call_arguments.done":{let $=J;if(this.touch(),!this.ending)this.call($.call_id,$.name,$.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let $=J.error;if(this.errors.push({code:$?.code,message:String($?.message??"")}),this.pendingCreate&&$?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,$.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let $=J;if(!this.ending&&!$.byClient)this.end($.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,$){if($.trim())this.transcript.push({role:J,text:$,at:Date.now()})}call(J,$,Q){let Z=y8(Q);if($===this.delegateName){let K=typeof Z.request==="string"?Z.request.trim():"";if(!K)return this.answer(J,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:K,status:"queued"},turn:{text:K},callId:J})}let W=this.toolHandlers.get($);if(W)return void this.runTool(J,W,Z);switch($){case"stop_work":{let K=this.running;if(K)K.stopRequested=!0,K.handle?.stop({reason:"Stopped by voice."});let X=this.dropQueue();return this.answer(J,{stopped:Boolean(K),dropped:X})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((K)=>K.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(J,{status:"error",message:"There is no open question."});let K=typeof Z.answer==="string"?Z.answer:"",X=typeof Z.approve==="boolean"?Z.approve:void 0,G=this.pending.map((V)=>v8(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:G},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${$}.`})}}enqueue(J){if(!this.running){this.requests.push(J.record),this.run(J);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(J.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(J.record),this.queue.push(J),this.answer(J.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),J.callId=void 0}async run(J){this.running=J,J.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let $=new Set;await this.waitForThread($);let Q=await this.latestBody();while(!J.stopRequested&&await this.waitForThread($));if(J.stopRequested||this.ending){J.record.status="dropped",this.complete(J,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:Q,turn:J.turn})}catch(K){J.record.status="refused",this.complete(J,{status:"refused",message:K instanceof Error?K.message:"The request could not be started."});return}J.handle=Z,J.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(J.record.status="done",J.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(J,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(J,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(J,{status:"stopped",text:W.text});else this.complete(J,{status:"done",text:W.text})}catch($){J.record.status="done",this.complete(J,{status:"failed",message:$ instanceof Error?$.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let $=this.queue.shift();if($&&!this.ending)this.run($);else this.touch()}}async runTool(J,$,Q){let Z=$.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let K={name:Z,status:"running"};this.toolCalls.push(K),this.toolsRunning+=1,this.pauseIdle();let X=new AbortController,G=$.timeoutMs??this.limits.toolTimeoutMs,V,Y;try{let D=await Promise.race([$.run(Q,{sessionId:this.sessionId,signal:X.signal}),new Promise((N,P)=>{V=setTimeout(()=>{P(new g(`"${Z}" took longer than ${Math.round(G/1000)} s.`)),X.abort()},G)})]);K.status="done",Y={status:"done",output:this.clip(D)}}catch(D){if(D instanceof TJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let N=D instanceof g?D.message:"The tool failed.";if(!(D instanceof g))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);K.status="failed",K.message=N,Y={status:"failed",message:N}}finally{clearTimeout(V),K.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let z=this.info();if(this.hook(()=>this.params.onToolCall?.({...K},z)),!this.ending)this.answer(J,Y)}clip(J){let $;try{$=JSON.stringify(J)}catch{return String(J)}if($===void 0||$.length<=this.limits.toolOutputChars)return J;return`${$.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${$.length} characters in all)`}async waitForThread(J=new Set){let $=this.params.liveRuns;if(!$)return!1;let Q=await $.find({threadId:this.threadId}),Z=Q&&!J.has(Q.runId)?$.get(Q.runId):null;if(!Q||!Z)return!1;return J.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let $=await J.get(this.sessionId).catch(()=>null);if($)this.body=$.body;return this.body}async follow(J){let $=this.params.progress??h8();try{for await(let Q of J.run){let Z=$(Q);if(Z)this.note(Z)}}catch{}}complete(J,$){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,$),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify($)}`);this.respond()}answer(J,$){this.sideband.functionOutput(J,$),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let J=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=J,this.sideband.send({type:"response.create",event_id:J})}questions(){return this.pending.map((J)=>({kind:J.kind,tool:String(J.name),input:J.input}))}dropQueue(){let J=this.queue.splice(0);for(let $ of J)$.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let $=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if($<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),$)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let J=this.info();this.hook(()=>this.params.onTick?.(J))}hook(J){this.hooks=this.hooks.then(async()=>{try{await J()}catch($){if($ instanceof TJ)this.end("usage",$.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",$),this.end("error",this.lines.error)}})}tampered(J){let $=this.params.session;if(!$||!J)return!1;if($.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==$.instructions)return!0;if(Array.isArray(J.tools)){let Q=new Set([...KJ(this.params.delegate),...$.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if(Q.size!==Z.size||[...Q].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,$){for(let X of this.timers)clearTimeout(X);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),$&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine($);if(J!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,K={sessionId:this.sessionId,...this.callId?{callId:this.callId}:{},threadId:this.threadId,reason:J,startedAt:this.startedAt,endedAt:Z,durationMs:W,seconds:Math.ceil(W/1000),usage:this.usage,transcription:this.transcription,transcript:this.transcript,requests:this.requests,toolCalls:this.toolCalls,errors:this.errors};kJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(K)}catch(X){console.error("[gemi/ai] a voice session's onEnd threw.",X)}return this.resolveEnded(K),K}async hangUp(){try{await this.hangupCall()}catch(J){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",J),this.errors.push({code:"hangup_failed",message:J instanceof Error?J.message:String(J)});let $;await Promise.race([this.sideband.closed,new Promise((Q)=>$=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout($),this.sideband.close()}}async closingLine(J){await new Promise(($)=>{let Q=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",K,X=setTimeout(G,this.limits.closingLineMs);function G(){clearTimeout(X),$()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(Y)=>{let z=Y;if(z.type==="sideband.closed")return G();if(W==="cancelling"){if(z.type==="response.done"||z.type==="error"&&z.error?.event_id===Z)V();return}if(z.type==="error"&&z.error?.event_id===Q)return G();if(z.type==="response.created"&&!K){K=z.response?.id;return}let D=(N)=>!K||!N||N===K;if(z.type==="response.done"&&D(z.response?.id))W="playing";else if(z.type==="output_audio_buffer.stopped"&&W==="playing"&&D(z.response_id))G()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function uQ(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function y8(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function v8(J,$,Q){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:$};if(J.kind==="approval")return{...Z,approve:Q===!0,...$?{reason:$}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function h8(){let J=new Set;return($)=>{if($.type==="tool-call"){if($.part.partial||$.resent||J.has($.part.toolCallId))return;return J.add($.part.toolCallId),`running ${String($.part.name)}`}if($.type==="tool-progress"){let Q=$.data;if(typeof Q==="string")return Q;if(Q&&typeof Q==="object")for(let Z of["message","label","title"]){let W=Q[Z];if(typeof W==="string"&&W)return W}}return}}var cQ="http://gemi.internal/__gemi__/voice/mcp";async function V$(J,$){if(!$.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:Q}=J,Z=J.scopes??Q.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:$.user,via:"voice",id:`voice:${$.sessionId}`,scopes:Z}});return(await Q.available(W(mQ()),J.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(G,V)=>{let Y=mQ();return h.run(Y,async()=>{return await J.authorize?.({name:X.name,input:G,sessionId:V.sessionId}),Q.execute(W(Y),X.name,G,void 0,{signal:V.signal})},{user:$.user})}}))}function mQ(){return new j(new Request(cQ,{method:"POST"}),{},"api",new URL(cQ).pathname)}class z${records=new Map;retainEndedMs;constructor(J={}){this.retainEndedMs=J.retainEndedMs??600000}async create(J){this.sweep(),this.records.set(J.id,structuredClone(J))}async get(J){let $=this.records.get(J);return $?structuredClone($):null}async update(J,$){let Q=this.records.get(J);if(!Q)return;this.records.set(J,{...Q,...structuredClone($),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[$,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<J)this.records.delete($)}}var D$=new z$;var pQ=new WeakMap,lQ=100;class H${threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(J,$={}){this.threadsTable=iQ($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=iQ($.messagesTable??"gemi_agent_messages","messages"),this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.options=$}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A DatabaseAgentStore scope is a non-empty string.");let $=new H$({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return $.scope=J,$}async createTable(){let J=c8(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($);await this.addScopeColumns()}async addScopeColumns(){let J=m8(this.dialect,this.threadsTable,this.messagesTable);for(let[$,Q]of J){if(await this.hasColumn($,"scope"))continue;for(let Z of Q)await this.sql.unsafe(Z)}}async hasColumn(J,$){try{return await this.sql.unsafe(`SELECT ${$} FROM ${this.quote(J)} WHERE 1 = 0`),!0}catch{return!1}}async createThread(J){let $=crypto.randomUUID(),Q=J.userId===void 0||J.userId===null?null:String(J.userId);return await this.run(async(Z)=>{let W=this.clock(Z);if(this.scope===null)await Z`
147
182
  INSERT INTO ${this.threads(Z)} (id, user_id, created_at, updated_at)
148
183
  VALUES (${$}, ${Q}, ${W}, ${W})
149
184
  `;else await Z`
@@ -155,61 +190,61 @@ import{$c as _0,Ac as T8,Cc as x8,Dc as y8,Ec as q8,Fc as b8,Gc as f8,Hc as v8,I
155
190
  SELECT message FROM ${this.messages($)}
156
191
  WHERE thread_id = ${J} AND ${this.inScope($)}
157
192
  ORDER BY position
158
- `).map((W)=>JSON.parse(String(W.message)))})}async appendMessages(J,$){if($.length===0){if(await this.getThread(J)===null)throw i9(J);return}await this.atomically(async(Q)=>{await Q`
193
+ `).map((W)=>JSON.parse(String(W.message)))})}async appendMessages(J,$){if($.length===0){if(await this.getThread(J)===null)throw dQ(J);return}await this.atomically(async(Q)=>{await Q`
159
194
  UPDATE ${this.threads(Q)} SET updated_at = ${this.clock(Q)}
160
195
  WHERE id = ${J} AND ${this.inScope(Q)}
161
196
  `;let Z=await Q`
162
197
  SELECT title FROM ${this.threads(Q)} WHERE id = ${J} AND ${this.inScope(Q)}
163
- `;if(Z.length===0)throw i9(J);let W=[...new Set($.map((G)=>G.id))],K=await Q`
198
+ `;if(Z.length===0)throw dQ(J);let W=[...new Set($.map((Y)=>Y.id))],K=await Q`
164
199
  SELECT id FROM ${this.messages(Q)}
165
- WHERE thread_id = ${J} AND id IN (${n9(Q,W)})
166
- `,X=new Set(K.map((G)=>String(G.id))),[Y]=await Q`
200
+ WHERE thread_id = ${J} AND id IN (${nQ(Q,W)})
201
+ `,X=new Set(K.map((Y)=>String(Y.id))),[G]=await Q`
167
202
  SELECT MAX(position) AS position FROM ${this.messages(Q)} WHERE thread_id = ${J}
168
- `,V=Y?.position===null||Y?.position===void 0?0:Number(Y.position)+1;for(let G of $){let H=JSON.stringify(G);if(X.has(G.id))await Q`
169
- UPDATE ${this.messages(Q)} SET message = ${H}
170
- WHERE thread_id = ${J} AND id = ${G.id}
203
+ `,V=G?.position===null||G?.position===void 0?0:Number(G.position)+1;for(let Y of $){let z=JSON.stringify(Y);if(X.has(Y.id))await Q`
204
+ UPDATE ${this.messages(Q)} SET message = ${z}
205
+ WHERE thread_id = ${J} AND id = ${Y.id}
171
206
  `;else if(this.scope===null)await Q`
172
207
  INSERT INTO ${this.messages(Q)} (thread_id, id, position, message, created_at)
173
- VALUES (${J}, ${G.id}, ${V}, ${H}, ${this.clock(Q)})
174
- `,X.add(G.id),V+=1;else await Q`
208
+ VALUES (${J}, ${Y.id}, ${V}, ${z}, ${this.clock(Q)})
209
+ `,X.add(Y.id),V+=1;else await Q`
175
210
  INSERT INTO ${this.messages(Q)} (thread_id, scope, id, position, message, created_at)
176
- VALUES (${J}, ${this.scope}, ${G.id}, ${V}, ${H}, ${this.clock(Q)})
177
- `,X.add(G.id),V+=1}if(Z[0].title===null||Z[0].title===void 0){let G=B6($);if(G!==null)await Q`
178
- UPDATE ${this.threads(Q)} SET title = ${G}
211
+ VALUES (${J}, ${this.scope}, ${Y.id}, ${V}, ${z}, ${this.clock(Q)})
212
+ `,X.add(Y.id),V+=1}if(Z[0].title===null||Z[0].title===void 0){let Y=g8($);if(Y!==null)await Q`
213
+ UPDATE ${this.threads(Q)} SET title = ${Y}
179
214
  WHERE id = ${J} AND title IS NULL
180
215
  `}})}async removeMessages(J,$){if($.length===0)return;await this.run(async(Q)=>{await Q`
181
216
  DELETE FROM ${this.messages(Q)}
182
217
  WHERE thread_id = ${J} AND ${this.inScope(Q)}
183
- AND id IN (${n9(Q,[...new Set($)])})
218
+ AND id IN (${nQ(Q,[...new Set($)])})
184
219
  `})}async loadSummaries(J){return this.run(async($)=>{let[Q]=await $`
185
220
  SELECT summaries FROM ${this.threads($)} WHERE id = ${J} AND ${this.inScope($)}
186
- `;return Q?o9(Q.summaries):[]})}async saveSummary(J,$){await this.atomically(async(Q)=>{await Q`
221
+ `;return Q?oQ(Q.summaries):[]})}async saveSummary(J,$){await this.atomically(async(Q)=>{await Q`
187
222
  UPDATE ${this.threads(Q)} SET updated_at = updated_at
188
223
  WHERE id = ${J} AND ${this.inScope(Q)}
189
224
  `;let[Z]=await Q`
190
225
  SELECT summaries FROM ${this.threads(Q)} WHERE id = ${J} AND ${this.inScope(Q)}
191
- `;if(!Z)return;let W=BJ(o9(Z.summaries),$);await Q`
226
+ `;if(!Z)return;let W=GJ(oQ(Z.summaries),$);await Q`
192
227
  UPDATE ${this.threads(Q)} SET summaries = ${JSON.stringify(W)}
193
228
  WHERE id = ${J}
194
- `})}async lockSummary(J,$,Q){let Z=`${$}:${crypto.randomUUID()}`;if(!await this.run(async(K)=>{let X=this.clock(K),Y=await K`
229
+ `})}async lockSummary(J,$,Q){let Z=`${$}:${crypto.randomUUID()}`;if(!await this.run(async(K)=>{let X=this.clock(K),G=await K`
195
230
  UPDATE ${this.threads(K)}
196
231
  SET summary_lock = ${Z}, summary_lock_until = ${X} + ${this.ms(K,Q)}
197
232
  WHERE id = ${J} AND ${this.inScope(K)}
198
233
  AND (summary_lock_until IS NULL OR summary_lock_until <= ${X})
199
- `;return L6(Y)>0}))return null;return async()=>{await this.run(async(K)=>{await K`
234
+ `;return u8(G)>0}))return null;return async()=>{await this.run(async(K)=>{await K`
200
235
  UPDATE ${this.threads(K)} SET summary_lock = NULL, summary_lock_until = NULL
201
236
  WHERE id = ${J} AND ${this.inScope(K)} AND summary_lock = ${Z}
202
237
  `})}}async getThread(J){return this.run(async($)=>{let[Q]=await $`
203
238
  SELECT id, user_id, title, created_at, updated_at FROM ${this.threads($)}
204
239
  WHERE id = ${J} AND ${this.inScope($)}
205
- `;return Q?s9(Q):null})}async listThreads(J={}){let $=Math.max(0,Math.floor(J.limit??50)),Q=Math.max(0,Math.floor(J.offset??0));return this.run(async(Z)=>{let W=J.userId===void 0?Z`1 = 1`:J.userId===null?Z`user_id IS NULL`:Z`user_id = ${String(J.userId)}`;return(await Z`
240
+ `;return Q?sQ(Q):null})}async listThreads(J={}){let $=Math.max(0,Math.floor(J.limit??50)),Q=Math.max(0,Math.floor(J.offset??0));return this.run(async(Z)=>{let W=J.userId===void 0?Z`1 = 1`:J.userId===null?Z`user_id IS NULL`:Z`user_id = ${String(J.userId)}`;return(await Z`
206
241
  SELECT id, user_id, title, created_at, updated_at FROM ${this.threads(Z)}
207
242
  WHERE ${this.inScope(Z)} AND ${W}
208
243
  ORDER BY updated_at DESC, id DESC
209
244
  LIMIT ${$} OFFSET ${Q}
210
- `).map(s9)})}async deleteThread(J){await this.atomically(async($)=>{if((await $`
245
+ `).map(sQ)})}async deleteThread(J){await this.atomically(async($)=>{if((await $`
211
246
  SELECT id FROM ${this.threads($)} WHERE id = ${J} AND ${this.inScope($)}
212
- `).length===0)return;await $`DELETE FROM ${this.messages($)} WHERE thread_id = ${J}`,await $`DELETE FROM ${this.threads($)} WHERE id = ${J}`})}atomically(J){if(this.guard(),this.joinable())return TJ(this.sql,(X)=>J(X),{connection:this.connection});let $=this.scope,Q=this.options.beginScope,Z=()=>this.sql.begin(async(X)=>{if($!==null&&Q)await Q(X,$);return J(X)});if(this.dialect!=="sqlite")return Z();let K=(p9.get(this.sql)??Promise.resolve()).then(Z,Z);return p9.set(this.sql,K.then(()=>{},()=>{})),K}joinable(){if(this.connection===void 0)return;let J=t();if(J===void 0||r()!==this.connection)return;return J}run(J){this.guard();let $=this.joinable();if($)return J($);if(this.scope!==null&&this.options.beginScope)return this.atomically(J);return J(this.sql)}guard(){if(this.scope===null&&this.options.requireScope)throw Error("This DatabaseAgentStore requires a scope: call it through store.forScope(scope).")}inScope(J){return this.scope===null?J`1 = 1`:J`scope = ${this.scope}`}quote(J){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${J}\``:`"${J}"`}threads(J){return J.unsafe(this.quote(this.threadsTable))}messages(J){return J.unsafe(this.quote(this.messagesTable))}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function d9(J,$){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The agent ${$} table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);return J}function i9(J){return Error(`Thread ${J} does not exist here, or has been deleted.`)}function n9(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function B6(J){for(let $ of J){if($.role!=="user"||$.event)continue;let Q=$.content.map((Z)=>Z.type==="text"?Z.text:"").join(" ").replace(/\s+/g," ").trim();if(Q)return Q.length>l9?`${Q.slice(0,l9-1)}\u2026`:Q}return null}function o9(J){if(J===null||J===void 0||J==="")return[];let $=JSON.parse(String(J));return Array.isArray($)?$:[]}function s9(J){return{id:String(J.id),userId:J.user_id===null||J.user_id===void 0?null:String(J.user_id),title:J.title===null||J.title===void 0?null:String(J.title),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at)}}function L6(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function C6(J,$,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
247
+ `).length===0)return;await $`DELETE FROM ${this.messages($)} WHERE thread_id = ${J}`,await $`DELETE FROM ${this.threads($)} WHERE id = ${J}`})}atomically(J){if(this.guard(),this.joinable())return _J(this.sql,(X)=>J(X),{connection:this.connection});let $=this.scope,Q=this.options.beginScope,Z=()=>this.sql.begin(async(X)=>{if($!==null&&Q)await Q(X,$);return J(X)});if(this.dialect!=="sqlite")return Z();let K=(pQ.get(this.sql)??Promise.resolve()).then(Z,Z);return pQ.set(this.sql,K.then(()=>{},()=>{})),K}joinable(){if(this.connection===void 0)return;let J=d();if(J===void 0||n()!==this.connection)return;return J}run(J){this.guard();let $=this.joinable();if($)return J($);if(this.scope!==null&&this.options.beginScope)return this.atomically(J);return J(this.sql)}guard(){if(this.scope===null&&this.options.requireScope)throw Error("This DatabaseAgentStore requires a scope: call it through store.forScope(scope).")}inScope(J){return this.scope===null?J`1 = 1`:J`scope = ${this.scope}`}quote(J){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${J}\``:`"${J}"`}threads(J){return J.unsafe(this.quote(this.threadsTable))}messages(J){return J.unsafe(this.quote(this.messagesTable))}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function iQ(J,$){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The agent ${$} table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);return J}function dQ(J){return Error(`Thread ${J} does not exist here, or has been deleted.`)}function nQ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function g8(J){for(let $ of J){if($.role!=="user"||$.event)continue;let Q=$.content.map((Z)=>Z.type==="text"?Z.text:"").join(" ").replace(/\s+/g," ").trim();if(Q)return Q.length>lQ?`${Q.slice(0,lQ-1)}\u2026`:Q}return null}function oQ(J){if(J===null||J===void 0||J==="")return[];let $=JSON.parse(String(J));return Array.isArray($)?$:[]}function sQ(J){return{id:String(J.id),userId:J.user_id===null||J.user_id===void 0?null:String(J.user_id),title:J.title===null||J.title===void 0?null:String(J.title),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at)}}function u8(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function c8(J,$,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
213
248
  \`id\` VARCHAR(191) NOT NULL,
214
249
  \`scope\` VARCHAR(191) NULL,
215
250
  \`user_id\` VARCHAR(191) NULL,
@@ -254,14 +289,14 @@ import{$c as _0,Ac as T8,Cc as x8,Dc as y8,Ec as q8,Fc as b8,Gc as f8,Hc as v8,I
254
289
  "created_at" BIGINT NOT NULL,
255
290
 
256
291
  CONSTRAINT "${Q}_pkey" PRIMARY KEY ("thread_id", "id")
257
- )`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}function O6(J,$,Q){if(J==="mysql"||J==="mariadb")return[[$,[`ALTER TABLE \`${$}\` ADD COLUMN \`scope\` VARCHAR(191) NULL, ADD INDEX \`${$}_scope_user_id_updated_at_idx\`(\`scope\`, \`user_id\`, \`updated_at\`)`]],[Q,[`ALTER TABLE \`${Q}\` ADD COLUMN \`scope\` VARCHAR(191) NULL`]]];return[[$,[`ALTER TABLE "${$}" ADD COLUMN "scope" TEXT`,`CREATE INDEX IF NOT EXISTS "${$}_scope_user_id_updated_at_idx" ON "${$}"("scope", "user_id", "updated_at")`]],[Q,[`ALTER TABLE "${Q}" ADD COLUMN "scope" TEXT`]]]}class QJ extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,$,Q){super(`Frame ${$} of run ${J} has been evicted; the oldest frame still buffered is ${Q}. Reload the thread instead of resuming.`);this.runId=J;this.requested=$;this.oldest=Q}}class LJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class dJ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(J={}){this.ttlMs=J.ttlMs??60000,this.maxFrames=J.maxFrames??4096,this.maxAgeMs=J.maxAgeMs===void 0?3600000:J.maxAgeMs}register(J,$={}){let Q={run:J,threadId:$.threadId,owner:$.owner??null,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(J.runId,Q),$.threadId)this.byThread.set($.threadId,J.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,J.runId);return this.scheduleExpiry(Q,$.maxRunDurationMs),this.pump(Q,$)}findByClientRunId(J){let $=this.byClientRun.get(J);return $&&this.runs.has($)?$:null}async find(J){let $=this.byThread.get(J.threadId);if(!$)return null;let Q=this.runs.get($);if(!Q)return null;return{runId:$,seq:Q.lastSeq}}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,$){let Q=this.ownerOf(J);return Q===null||Q===$}isRunning(J){let $=this.runs.get(J);return!!$&&!$.ended&&!$.evicted}replay(J,$){let Q=this.runs.get(J);if(!Q)throw new LJ(J);if($!==void 0&&$<Q.lostBefore)throw new QJ(J,$,Q.lostBefore);let Z=Q.frames[0]?.seq;return this.drain(Q,J,$??Z??Q.lastSeq+1)}clear(){for(let J of this.runs.values()){if(J.evictAt)clearTimeout(J.evictAt);if(J.expireAt)clearTimeout(J.expireAt);J.ended=!0,this.notify(J)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(J,$){let Q=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let K=$.onEvent;if(K)Q=Q.then(()=>K(Z.event)).catch((X)=>d$($,X));continue}if(J.frames.push(Z),J.lastSeq=Z.seq,J.frames.length>this.maxFrames){let K=J.frames.shift();if(K)J.lostBefore=K.seq+1}this.notify(J);let W=$.onEvent;if(W)Q=Q.then(()=>W(Z.event)).catch((K)=>d$($,K))}}catch(Z){d$($,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await Q}}async*drain(J,$,Q){let Z=Q;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new QJ($,Z,J.lostBefore);let K=J.frames,X=K[0]?.seq;if(X===void 0)break;let Y=Math.max(0,Z-X);if(Y>=K.length)break;let V=K[Y];yield V,Z=V.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,$){if(J.version!==$)return Promise.resolve();return new Promise((Q)=>J.wake.add(Q))}notify(J){J.version++;let $=Array.from(J.wake);J.wake.clear();for(let Q of $)Q()}scheduleEviction(J){if(J.evictAt)return;let $=setTimeout(()=>{let Q=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get(Q)===J)this.runs.delete(Q);if(J.threadId&&this.byThread.get(J.threadId)===Q)this.byThread.delete(J.threadId);if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===Q)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);$.unref?.(),J.evictAt=$}scheduleExpiry(J,$){if(this.maxAgeMs===null||$===null)return;let Q=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Q)||Q>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round(Q/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},Q);Z.unref?.(),J.expireAt=Z}}var i$=new dJ;function d$(J,$){try{J.onInternalError?.($)}catch{}}class iJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,$){if(this.records.has(J))return;this.records.set(J,{...$});while(this.records.size>this.maxEntries){let Q=this.records.keys().next().value;if(Q===void 0)break;this.records.delete(Q)}}async get(J){let $=this.records.get(J);return $?{...$}:null}}var n$=new iJ;class a${now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,$){let Q=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Q);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>Q)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:$}),{status:"claimed"}}async complete(J,$,Q){this.receipts.set(J,{result:structuredClone($),expiresAt:Q})}async release(J){let $=this.receipts.get(J);if($&&!$.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[$,Q]of this.receipts)if(Q.expiresAt<=J)this.receipts.delete($);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var a9="pending",o$="done:",_6=`
292
+ )`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}function m8(J,$,Q){if(J==="mysql"||J==="mariadb")return[[$,[`ALTER TABLE \`${$}\` ADD COLUMN \`scope\` VARCHAR(191) NULL, ADD INDEX \`${$}_scope_user_id_updated_at_idx\`(\`scope\`, \`user_id\`, \`updated_at\`)`]],[Q,[`ALTER TABLE \`${Q}\` ADD COLUMN \`scope\` VARCHAR(191) NULL`]]];return[[$,[`ALTER TABLE "${$}" ADD COLUMN "scope" TEXT`,`CREATE INDEX IF NOT EXISTS "${$}_scope_user_id_updated_at_idx" ON "${$}"("scope", "user_id", "updated_at")`]],[Q,[`ALTER TABLE "${Q}" ADD COLUMN "scope" TEXT`]]]}class s extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,$,Q){super(`Frame ${$} of run ${J} has been evicted; the oldest frame still buffered is ${Q}. Reload the thread instead of resuming.`);this.runId=J;this.requested=$;this.oldest=Q}}class YJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class jJ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(J={}){this.ttlMs=J.ttlMs??60000,this.maxFrames=J.maxFrames??4096,this.maxAgeMs=J.maxAgeMs===void 0?3600000:J.maxAgeMs}register(J,$={}){let Q={run:J,threadId:$.threadId,owner:$.owner??null,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(J.runId,Q),$.threadId)this.byThread.set($.threadId,J.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,J.runId);return this.scheduleExpiry(Q,$.maxRunDurationMs),this.pump(Q,$)}findByClientRunId(J){let $=this.byClientRun.get(J);return $&&this.runs.has($)?$:null}async find(J){let $=this.byThread.get(J.threadId);if(!$)return null;let Q=this.runs.get($);if(!Q)return null;return{runId:$,seq:Q.lastSeq}}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,$){let Q=this.ownerOf(J);return Q===null||Q===$}isRunning(J){let $=this.runs.get(J);return!!$&&!$.ended&&!$.evicted}replay(J,$){let Q=this.runs.get(J);if(!Q)throw new YJ(J);if($!==void 0&&$<Q.lostBefore)throw new s(J,$,Q.lostBefore);let Z=Q.frames[0]?.seq;return this.drain(Q,J,$??Z??Q.lastSeq+1)}clear(){for(let J of this.runs.values()){if(J.evictAt)clearTimeout(J.evictAt);if(J.expireAt)clearTimeout(J.expireAt);J.ended=!0,this.notify(J)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(J,$){let Q=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let K=$.onEvent;if(K)Q=Q.then(()=>K(Z.event)).catch((X)=>P$($,X));continue}if(J.frames.push(Z),J.lastSeq=Z.seq,J.frames.length>this.maxFrames){let K=J.frames.shift();if(K)J.lostBefore=K.seq+1}this.notify(J);let W=$.onEvent;if(W)Q=Q.then(()=>W(Z.event)).catch((K)=>P$($,K))}}catch(Z){P$($,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await Q}}async*drain(J,$,Q){let Z=Q;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new s($,Z,J.lostBefore);let K=J.frames,X=K[0]?.seq;if(X===void 0)break;let G=Math.max(0,Z-X);if(G>=K.length)break;let V=K[G];yield V,Z=V.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,$){if(J.version!==$)return Promise.resolve();return new Promise((Q)=>J.wake.add(Q))}notify(J){J.version++;let $=Array.from(J.wake);J.wake.clear();for(let Q of $)Q()}scheduleEviction(J){if(J.evictAt)return;let $=setTimeout(()=>{let Q=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get(Q)===J)this.runs.delete(Q);if(J.threadId&&this.byThread.get(J.threadId)===Q)this.byThread.delete(J.threadId);if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===Q)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);$.unref?.(),J.evictAt=$}scheduleExpiry(J,$){if(this.maxAgeMs===null||$===null)return;let Q=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Q)||Q>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round(Q/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},Q);Z.unref?.(),J.expireAt=Z}}var F$=new jJ;function P$(J,$){try{J.onInternalError?.($)}catch{}}class xJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,$){if(this.records.has(J))return;this.records.set(J,{...$});while(this.records.size>this.maxEntries){let Q=this.records.keys().next().value;if(Q===void 0)break;this.records.delete(Q)}}async get(J){let $=this.records.get(J);return $?{...$}:null}}var N$=new xJ;class U${now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,$){let Q=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Q);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>Q)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:$}),{status:"claimed"}}async complete(J,$,Q){this.receipts.set(J,{result:structuredClone($),expiresAt:Q})}async release(J){let $=this.receipts.get(J);if($&&!$.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[$,Q]of this.receipts)if(Q.expiresAt<=J)this.receipts.delete($);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var aQ="pending",O$="done:",p8=`
258
293
  if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
259
294
  local held = redis.call('GET', KEYS[1])
260
295
  if not held then return ARGV[1] end
261
- return held`,M6=`
296
+ return held`,l8=`
262
297
  if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
263
- return 0`;class t${injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,$){let Q=await this.client.send("EVAL",[_6,"1",this.key(J),a9,t9($)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(o$))return{status:"replay",result:JSON.parse(Z.slice(o$.length))};return{status:"blocked"}}async complete(J,$,Q){await this.client.send("SET",[this.key(J),o$+JSON.stringify($),"PX",t9(Q)])}async release(J){await this.client.send("EVAL",[M6,"1",this.key(J),a9])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=r9(),$=J.bound(s$)?J.make(s$).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function t9(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var S6=86400000,A6=60000;class CJ{ttlMs;clientOwnedIds;scope=null;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??S6,this.clientOwnedIds=J.clientOwnedIds??!1}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A MemoryAgentStore scope is a non-empty string.");let $=new CJ({ttlMs:this.ttlMs,clientOwnedIds:this.clientOwnedIds});return $.threads=this.threads,$.scope=J,$}visible(J){let $=this.threads.get(J);if(!$||this.scope===null||$.scope===this.scope)return $;return}fresh(){return{messages:[],touchedAt:Date.now(),...this.scope!==null?{scope:this.scope}:{}}}async createThread(J){let $=crypto.randomUUID();return this.threads.set($,this.fresh()),this.sweep(),{threadId:$}}async loadThread(J){this.sweep();let $=this.visible(J);if(!$){if(this.threads.has(J))return null;return this.clientOwnedIds?[]:null}return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q){if(!this.clientOwnedIds||this.threads.has(J))throw Error(`Thread ${J} does not exist here, or has expired.`);Q=this.fresh(),this.threads.set(J,Q)}for(let Z of $){let W=JSON.parse(JSON.stringify(Z)),K=Q.messages.findIndex((X)=>X.id===W.id);if(K===-1)Q.messages.push(W);else Q.messages[K]=W}Q.touchedAt=Date.now()}async removeMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q)return;let Z=new Set($);Q.messages=Q.messages.filter((W)=>!Z.has(W.id)),Q.touchedAt=Date.now()}async loadSummaries(J){return this.visible(J)?.summaries?.slice()??[]}async saveSummary(J,$){let Q=this.visible(J);if(!Q)return;Q.summaries=BJ(Q.summaries??[],$)}delete(J){if(this.visible(J))this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<A6)return;this.lastSweep=J;for(let[$,Q]of this.threads)if(J-Q.touchedAt>this.ttlMs)this.threads.delete($)}}var r$=new CJ;function QQ(J={}){return{messages:J.messages?[...J.messages]:[],pending:J.pending?[...J.pending]:[],error:null,threadId:J.threadId,seq:J.seq??-1,cursorRunId:J.cursorRunId,runMessageIds:[],loadedTools:[]}}function ZQ(J,$,Q=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==J.cursorRunId)&&$.seq<=J.seq)return J;return{...WQ(J,$.event,Q),seq:$.seq}}function WQ(J,$,Q){switch($.type){case"run-start":return{...J,messages:R6(J.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return u(J,$.messageId,Q,(Z)=>({...Z,role:$.role}));case"text-delta":if(JQ(J,$.messageId))return J;return u(J,$.messageId,Q,(Z)=>({...Z,content:x6(Z.content,$.delta)}));case"reasoning-delta":if(JQ(J,$.messageId))return J;return u(J,$.messageId,Q,(Z)=>({...Z,content:I6(Z.content,$.delta,$.id)}));case"output-delta":return u(J,$.messageId,Q,(Z)=>({...Z,content:$Q(Z.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return u(J,$.messageId,Q,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===$.part.toolCallId),K=W===-1?void 0:Z.content[W],X=$.part.progress??K?.progress,Y=$.part.nested??K?.nested,V=$.part.attachments??K?.attachments,G={...$.part,...X?{progress:X}:{},...Y?{nested:Y}:{},...V?{attachments:V}:{}},H=Z.content.slice();if(W===-1)H.push(G);else H[W]=G;return{...Z,content:H}});case"tool-call-discard":return u(J,$.messageId,Q,(Z)=>{let W=Z.content.filter((K)=>!(K.type==="tool-call"&&K.partial&&$.toolCallIds.includes(K.toolCallId)));return W.length===Z.content.length?Z:{...Z,content:W}});case"tool-search":{let Z=$.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return e9(J,$.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],$.data]}));case"nested-event":{let Z=$;return e9(J,$.toolCallId,(W)=>{let K=W.nested??[],X=K.findIndex((H)=>H.runId===Z.runId),Y=K[X]??{runId:Z.runId,agent:Z.agent,messages:[]},V=k6(Y,Z,Q),G=X===-1?[...K,V]:K.map((H,D)=>D===X?V:H);return{...W,nested:G}})}case"tool-result":{let Z=u(J,$.messageId,Q,(W)=>({...W,content:$Q(W.content,$.part,(K)=>K.type==="tool-result"&&K.toolCallId===$.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((X)=>X.id===$.message.id),W=J.messages.slice();if(Z===-1)W.push($.message);else W[Z]=$.message;let K=J.runMessageIds.includes($.message.id)?J.runMessageIds:[...J.runMessageIds,$.message.id];return{...J,messages:W,runMessageIds:K}}case"message-id":{let Z=J.messages.findIndex((Y)=>Y.id===$.localId);if(Z===-1){if(!$.message||J.messages.some((Y)=>Y.id===$.messageId))return J;return{...J,messages:[...J.messages,$.message]}}let W=J.messages[Z],K={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},X=J.messages.some((Y)=>Y.id===$.messageId)?J.messages.filter((Y,V)=>V!==Z).map((Y)=>Y.id===$.messageId?{...Y,...K}:Y):J.messages.map((Y,V)=>V===Z?{...Y,...K,id:$.messageId}:Y);return{...J,messages:X}}case"awaiting-input":return{...J,runId:$.runId,pending:[...$.pending]};case"message-end":return u(J,$.messageId,Q,(Z)=>({...Z,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...J,usage:$.usage};case"retry":return J;case"error":return{...J,error:$.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:$.finishReason,messages:KQ(J,$.finishReason)};default:return J}}function R6(J,$){if(!J.some((Q)=>Q.runId===$&&Q.finishReason===void 0))return J;return J.map((Q)=>{if(Q.runId!==$||Q.finishReason!==void 0)return Q;let{runId:Z,...W}=Q;return{...W,content:[]}})}function KQ(J,$){return J.messages.map((Q)=>Q.role==="assistant"&&J.runMessageIds.includes(Q.id)?E6(Q,$):Q)}function E6(J,$){let Q=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((K)=>K.finishReason===void 0)?{...W,nested:W.nested.map((K)=>K.finishReason===void 0?j6(K,$):K)}:W);if(J.finishReason===void 0)return{...J,finishReason:$,content:Q};return Q.some((W,K)=>W!==J.content[K])?{...J,content:Q}:J}function j6(J,$){let Q={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:$,messages:KQ(Q,$)}}function e9(J,$,Q){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],K=W.content.findIndex((G)=>G.type==="tool-call"&&G.toolCallId===$);if(K===-1)continue;if(W.finishReason!==void 0&&!T6(J,W,$))return J;let X=W.content.slice();X[K]=Q(X[K]);let Y=J.messages.slice();Y[Z]={...W,content:X};let V=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:V,messages:Y}}return J}function k6(J,$,Q){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((K)=>K.id),loadedTools:[],finishReason:J.finishReason},W=WQ(Z,$.event,Q);return{...J,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function T6(J,$,Q){if($.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Q))}function JQ(J,$){let Q=J.messages.find((Z)=>Z.id===$);return Q!==void 0&&Q.finishReason!==void 0}function u(J,$,Q,Z){let W=J.messages.findIndex((Y)=>Y.id===$),K=J.runMessageIds.includes($)?J.runMessageIds:[...J.runMessageIds,$];if(W===-1){let Y={id:$,role:"assistant",content:[],createdAt:Q};return{...J,runMessageIds:K,messages:[...J.messages,Z(Y)]}}let X=J.messages.slice();return X[W]=Z(X[W]),{...J,runMessageIds:K,messages:X}}function x6(J,$){let Q=J[J.length-1];if(Q&&Q.type==="text")return[...J.slice(0,-1),{type:"text",text:Q.text+$}];return[...J,{type:"text",text:$}]}function I6(J,$,Q){let Z=J[J.length-1];if(Z&&Z.type==="reasoning"&&Z.id===Q)return[...J.slice(0,-1),{...Z,text:(Z.text??"")+$}];return[...J,Q?{type:"reasoning",id:Q,text:$}:{type:"reasoning",text:$}]}function $Q(J,$,Q){let Z=J.findIndex(Q);if(Z===-1)return[...J,$];let W=J.slice();return W[Z]=$,W}class J8{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,$,Q,Z){this.store=J;this.threadId=$;this.report=Z;this.state=QQ({messages:Q})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[e$(J)])}frame(J){if(this.closed)return;let $=J.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=ZQ(this.state,J),$.type){case"message":this.write(()=>[e$($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let $ of J)this.done.add($.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let $=this.state.messages.find((Z)=>Z.id===J);if(!$)return;let Q=this.runId;this.write(()=>{let Z=e$($);if(Z.finishReason===void 0&&Q)Z.runId=Q;return[Z]})}write(J){let $;try{$=J()}catch(Q){this.report(Q);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Q)=>this.report(Q))}}function e$(J){return structuredClone(J)}async function XQ(J,$){let Q=[],Z=null,W=J.slice();for(let K=0;K<W.length;K++){let X=W[K];if(X.role!=="assistant"||X.finishReason!==void 0)continue;if(X.runId&&await $(X.runId))continue;Z??=new Set(J.flatMap((G)=>G.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let Y=X.content.map((G)=>G.type==="tool-call"?GQ(G):G);for(let G of X.content){if(G.type!=="tool-call"||Z.has(G.toolCallId))continue;let H={type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"interrupted"};Y.push(H)}let V={...X,content:Y,finishReason:"interrupted"};W[K]=V,Q.push(V)}return{messages:W,settled:Q}}function GQ(J){let{partial:$,...Q}=J;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(w6)}}function w6(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Q)=>Q.type==="tool-call"?GQ(Q):Q)}:$)}}var q6=50,b6=["running","ok","error"];async function HQ(J,$){let{store:Q,threadId:Z}=$,W=Math.max(q6,$.scan??0),K=await Q.listForThread(Z,{limit:W}),X,Y=async(F)=>{if(F.state!=="running")return F;if(X??=await YQ(Q),F.deadlineAt>X)return F;return await VQ(Q,F),await Q.get(F.id)??F};for(let F=0;F<K.length;F++)K[F]=await Y(K[F]);let V=new Map(K.map((F)=>[F.id,F])),G=J.slice(),H=[],D=new Set;for(let F=0;F<G.length;F++){let B=G[F],N=null;for(let P=0;P<B.content.length;P++){let U=B.content[P];if(U.type==="tool-call")D.add(U.toolCallId);if(U.type!=="tool-result"||U.status!=="running")continue;let L=U.job?.id,_=L?V.get(L):void 0;if(L&&_===void 0){let R=await Q.get(L);if(_=R?await Y(R):void 0,_)V.set(L,_)}if(_?.state==="running")continue;N??=B.content.slice(),N[P]=f6(U,_,$.outputSchemaFor,$.modelOutputFor)}if(N){let P={...B,content:N};G[F]=P,H.push(P)}}let z=[];for(let F of K){if(F.orphaned||D.has(F.toolCallId))continue;if(await $.isRunLive(F.runId))continue;z.push(F)}return{messages:G,settled:H,orphans:z,jobs:K}}async function zQ(J,$,Q){for(let Z of $)try{await J.transition(Z.id,b6,{orphaned:!0})}catch(W){Q(W)}}function f6(J,$,Q,Z){let W={type:"tool-result",toolCallId:J.toolCallId,name:J.name},K=(V,G)=>{let H=Z?.(String(J.name),V);return{...W,status:"ok",job:G,output:V,...H!==void 0?{modelOutput:H}:{}}};if(!$)return{...W,status:"error",job:J.job,error:{code:"tool_error",message:`The background job for "${String(J.name)}" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,toolCallId:J.toolCallId,retryable:!0}};let X={id:$.id,...$.summary!==void 0?{summary:$.summary}:{},...$.usage?{usage:$.usage}:{}};if($.state==="error")return{...W,status:"error",job:X,error:$.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let Y=Q?.(String(J.name));if(Y){let V=Y.safeParse($.output);if(V.ok===!1)return{...W,status:"error",job:X,error:{code:"invalid_tool_result",message:`The background job for "${String(J.name)}" finished with an output that does not match the tool's output schema: ${V.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return K(V.value,X)}return K($.output,X)}var y6=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;class eJ extends Error{status;code;kind;constructor(J,$){super(J);this.name="AgentTurnError",this.status=$.status,this.code=$.code,this.kind=$.kind}static async from(J){let $={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")$=Z.error}catch{}let Q=(Z)=>typeof $[Z]==="string"?$[Z]:void 0;return new eJ(Q("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:Q("code"),kind:Q("kind")})}}function v6(J){for(let $=J.length-1;$>=0;$--){let Q=J[$];if(Q.role!=="assistant")continue;return Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var h6=jQ,OJ=new Map,$8=new WeakMap,ZJ=new WeakMap,DQ=new WeakMap,FQ=new WeakMap,Q8=new WeakMap,iQ="thread_busy",PQ="http://gemi.internal/__gemi/agent-turn",nJ=new Map,g6=4194304,u6=1000,c6=5,_J=65536,KJ=()=>{};class nQ{byKey=new Map;take(J,$,Q){let Z=this.byKey.get(J);if(!Z?.has($)&&(Z?.size??0)>=Q)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set($,(Z.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let K=this.byKey.get(J),X=(K?.get($)??1)-1;if(!K)return;if(X>0)K.set($,X);else if(K.delete($),K.size===0)this.byKey.delete(J)}}}var UQ=new WeakMap,W8=new WeakMap;function m6(J){let $=W8.get(J);if(!$)$=new Map,W8.set(J,$);return $}function p6(J,$,Q){let Z=W8.get(J)?.get($);if(!Z)return;for(let W of[...Z])try{W(Q)}catch{}}function l6(J){let $=UQ.get(J);if(!$)$=new nQ,UQ.set(J,$);return $}function d6(J){return J}class F8 extends h6{static kind="agent-controller";hooks;store=r$;storeScope(J,$){return null}boundScope=void 0;async threadInScope(J,$){if(await this.scopeStore(J,{}),this.boundScope===null)return!0;return await this.store.loadThread($)!==null}async scopeStore(J,$){let Z=DQ.get(J)??await this.storeScope(J,{body:$})??null;if(this.boundScope!==void 0){if(this.boundScope!==Z)throw Error("This AgentController instance already served a request in another store scope. Build a controller per request (the router and startTurn do).");return}if(Z!==null)this.store=RQ(this.store,Z);this.boundScope=Z}liveRuns=i$;voice;voiceStore=p$;attachments=rJ;attachmentStorage=xQ;fileOwners=n$;nonces=H8;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,$){return this.hooks?.instructions?.(J,$)}reasoning(J,$){return this.hooks?.reasoning?.(J,$)}skills(J,$){return this.hooks?.skills?.(J,$)}runTools(J,$){return this.hooks?.runTools?.(J,$)}usageLimits(J,$){return this.hooks?.usageLimits?.(J,$)}context(J,$){let Q=this.hooks?.context;if(Q)return Q(J,$);return{}}memoryScopes(J,$){let Q=this.hooks?.memoryScopes;if(Q)return Q(J,$);return{}}memoryMaxTokens=void 0;requireThread=!1;maxBodyBytes=g6;maxHistoryMessages=u6;contextWindow=void 0;prepareStep(J,$){return this.hooks?.prepareStep?.(J,$)}maxConcurrentRuns=c6;runLimitKey(J,$){let Q=this.hooks?.runLimitKey;if(Q)return Q(J,$);return $.owner}authorizeRequest(J,$){let Q=this.hooks?.authorizeRequest;if(Q)return Q(J,$);return this.resource?.authorize(J,$)}resource;runOwner(J){let $=this.hooks?.runOwner;if($)return $(J);let Q=J.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(J){let{threadId:$}=J;if(typeof $!=="string"||$==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let Q=J.ifBusy??"supersede";if(Q!=="supersede"&&Q!=="queue"&&Q!=="skip")throw TypeError(`AgentController.startTurn's \`ifBusy\` is "supersede", "queue" or "skip"; got ${JSON.stringify(J.ifBusy)}.`);let Z=J.event===void 0?void 0:Z0(J),W={...J.turn,...J.text!==void 0?{text:J.text}:{}},K={...J.body,threadId:$,turn:W},X=new b(new Request(PQ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K)}),{},"api",new URL(PQ).pathname),Y=new this;if(ZJ.set(X,null),J.scope!==void 0)DQ.set(X,J.scope);if(FQ.set(X,Q),Z)Q8.set(X,Z);let V=await p.run(X,()=>Y.stream(X),{user:J.user??null}),G=ZJ.get(X);if(!G){let N=await eJ.from(V);if(Q==="skip"&&N.code===iQ)return{skipped:!0,threadId:$};throw N}ZJ.delete(X),V.body?.cancel().catch(KJ);let{run:H,hooks:D}=G,z=[],F=(async()=>{for await(let N of H)if(N.type==="awaiting-input")z=N.pending})().catch(KJ),B;return{runId:H.runId,threadId:$,run:H,stop:(N)=>H.stop(N),result:()=>B??=(async()=>{let N=await H.result();await Promise.all([D,F]);let P=N.messages;return{...N,threadId:$,text:v6(P),pending:N.finishReason==="awaiting-input"?z:[]}})()}}async stream(J=new b){let $=await WJ(J,this.maxBodyBytes);if($.error)return s($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=e6(Q);if(W.error)return s({body:{},error:W.error});let K=W.turn,X=Z!==void 0&&Q.regenerate===!0,Y=typeof Q.clientRunId==="string"?Q.clientRunId:void 0,V=oJ(Q);if(this.requireThread&&!Z)return S(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(await this.scopeStore(J,V),X&&!this.store.removeMessages)return S(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!Z&&Array.isArray(Q.messages)&&Q.messages.length>this.maxHistoryMessages)return Y8(413,"history_too_long",`The conversation has ${Q.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let G=await this.runOwner(J),H=Y?{cancelled:!1,owner:G}:null;if(H)nJ.set(Y,H);let D=null,z=[],F=async()=>{try{return await B()}finally{if(Z&&z.length>0&&D===null)await this.store.appendMessages(Z,z).catch((N)=>this.reportHookFailure(N))}},B=async()=>{let N,P=null;if(Z){let E=await this.store.loadThread(Z);if(!E)return S(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let a=await this.settleThread(Z,E,{write:!0});if(N=a.messages,P=this.jobsBlock(a.jobs),X){let XJ=Q0(N);if(!XJ)return S(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});z=N.slice(XJ.index),await this.store.removeMessages(Z,z.map((aQ)=>aQ.id)),N=N.slice(0,XJ.index),K=K?.localId?{...XJ.turn,localId:K.localId}:XJ.turn}}else N=Array.isArray(Q.messages)?Q.messages:[],z0(this.nonces);let U=[await this.instructions(J,{body:V})||void 0,P??void 0].filter(Boolean).join(`
298
+ return 0`;class L${injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,$){let Q=await this.client.send("EVAL",[p8,"1",this.key(J),aQ,tQ($)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(O$))return{status:"replay",result:JSON.parse(Z.slice(O$.length))};return{status:"blocked"}}async complete(J,$,Q){await this.client.send("SET",[this.key(J),O$+JSON.stringify($),"PX",tQ(Q)])}async release(J){await this.client.send("EVAL",[l8,"1",this.key(J),aQ])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=rQ(),$=J.bound(C$)?J.make(C$).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function tQ(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var i8=86400000,d8=60000;class VJ{ttlMs;clientOwnedIds;scope=null;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??i8,this.clientOwnedIds=J.clientOwnedIds??!1}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A MemoryAgentStore scope is a non-empty string.");let $=new VJ({ttlMs:this.ttlMs,clientOwnedIds:this.clientOwnedIds});return $.threads=this.threads,$.scope=J,$}visible(J){let $=this.threads.get(J);if(!$||this.scope===null||$.scope===this.scope)return $;return}fresh(){return{messages:[],touchedAt:Date.now(),...this.scope!==null?{scope:this.scope}:{}}}async createThread(J){let $=crypto.randomUUID();return this.threads.set($,this.fresh()),this.sweep(),{threadId:$}}async loadThread(J){this.sweep();let $=this.visible(J);if(!$){if(this.threads.has(J))return null;return this.clientOwnedIds?[]:null}return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q){if(!this.clientOwnedIds||this.threads.has(J))throw Error(`Thread ${J} does not exist here, or has expired.`);Q=this.fresh(),this.threads.set(J,Q)}for(let Z of $){let W=JSON.parse(JSON.stringify(Z)),K=Q.messages.findIndex((X)=>X.id===W.id);if(K===-1)Q.messages.push(W);else Q.messages[K]=W}Q.touchedAt=Date.now()}async removeMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q)return;let Z=new Set($);Q.messages=Q.messages.filter((W)=>!Z.has(W.id)),Q.touchedAt=Date.now()}async loadSummaries(J){return this.visible(J)?.summaries?.slice()??[]}async saveSummary(J,$){let Q=this.visible(J);if(!Q)return;Q.summaries=GJ(Q.summaries??[],$)}delete(J){if(this.visible(J))this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<d8)return;this.lastSweep=J;for(let[$,Q]of this.threads)if(J-Q.touchedAt>this.ttlMs)this.threads.delete($)}}var _$=new VJ;function QZ(J={}){return{messages:J.messages?[...J.messages]:[],pending:J.pending?[...J.pending]:[],error:null,threadId:J.threadId,seq:J.seq??-1,cursorRunId:J.cursorRunId,runMessageIds:[],loadedTools:[]}}function ZZ(J,$,Q=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==J.cursorRunId)&&$.seq<=J.seq)return J;return{...WZ(J,$.event,Q),seq:$.seq}}function WZ(J,$,Q){switch($.type){case"run-start":return{...J,messages:n8(J.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return b(J,$.messageId,Q,(Z)=>({...Z,role:$.role}));case"text-delta":if(JZ(J,$.messageId))return J;return b(J,$.messageId,Q,(Z)=>({...Z,content:r8(Z.content,$.delta)}));case"reasoning-delta":if(JZ(J,$.messageId))return J;return b(J,$.messageId,Q,(Z)=>({...Z,content:e8(Z.content,$.delta,$.id)}));case"output-delta":return b(J,$.messageId,Q,(Z)=>({...Z,content:$Z(Z.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return b(J,$.messageId,Q,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===$.part.toolCallId),K=W===-1?void 0:Z.content[W],X=$.part.progress??K?.progress,G=$.part.nested??K?.nested,V=$.part.attachments??K?.attachments,Y={...$.part,...X?{progress:X}:{},...G?{nested:G}:{},...V?{attachments:V}:{}},z=Z.content.slice();if(W===-1)z.push(Y);else z[W]=Y;return{...Z,content:z}});case"tool-call-discard":return b(J,$.messageId,Q,(Z)=>{let W=Z.content.filter((K)=>!(K.type==="tool-call"&&K.partial&&$.toolCallIds.includes(K.toolCallId)));return W.length===Z.content.length?Z:{...Z,content:W}});case"tool-search":{let Z=$.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return eQ(J,$.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],$.data]}));case"nested-event":{let Z=$;return eQ(J,$.toolCallId,(W)=>{let K=W.nested??[],X=K.findIndex((z)=>z.runId===Z.runId),G=K[X]??{runId:Z.runId,agent:Z.agent,messages:[]},V=a8(G,Z,Q),Y=X===-1?[...K,V]:K.map((z,D)=>D===X?V:z);return{...W,nested:Y}})}case"tool-result":{let Z=b(J,$.messageId,Q,(W)=>({...W,content:$Z(W.content,$.part,(K)=>K.type==="tool-result"&&K.toolCallId===$.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((X)=>X.id===$.message.id),W=J.messages.slice();if(Z===-1)W.push($.message);else W[Z]=$.message;let K=J.runMessageIds.includes($.message.id)?J.runMessageIds:[...J.runMessageIds,$.message.id];return{...J,messages:W,runMessageIds:K}}case"message-id":{let Z=J.messages.findIndex((G)=>G.id===$.localId);if(Z===-1){if(!$.message||J.messages.some((G)=>G.id===$.messageId))return J;return{...J,messages:[...J.messages,$.message]}}let W=J.messages[Z],K={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},X=J.messages.some((G)=>G.id===$.messageId)?J.messages.filter((G,V)=>V!==Z).map((G)=>G.id===$.messageId?{...G,...K}:G):J.messages.map((G,V)=>V===Z?{...G,...K,id:$.messageId}:G);return{...J,messages:X}}case"awaiting-input":return{...J,runId:$.runId,pending:[...$.pending]};case"message-end":return b(J,$.messageId,Q,(Z)=>({...Z,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...J,usage:$.usage};case"retry":return J;case"error":return{...J,error:$.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:$.finishReason,messages:KZ(J,$.finishReason)};default:return J}}function n8(J,$){if(!J.some((Q)=>Q.runId===$&&Q.finishReason===void 0))return J;return J.map((Q)=>{if(Q.runId!==$||Q.finishReason!==void 0)return Q;let{runId:Z,...W}=Q;return{...W,content:[]}})}function KZ(J,$){return J.messages.map((Q)=>Q.role==="assistant"&&J.runMessageIds.includes(Q.id)?o8(Q,$):Q)}function o8(J,$){let Q=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((K)=>K.finishReason===void 0)?{...W,nested:W.nested.map((K)=>K.finishReason===void 0?s8(K,$):K)}:W);if(J.finishReason===void 0)return{...J,finishReason:$,content:Q};return Q.some((W,K)=>W!==J.content[K])?{...J,content:Q}:J}function s8(J,$){let Q={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:$,messages:KZ(Q,$)}}function eQ(J,$,Q){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],K=W.content.findIndex((Y)=>Y.type==="tool-call"&&Y.toolCallId===$);if(K===-1)continue;if(W.finishReason!==void 0&&!t8(J,W,$))return J;let X=W.content.slice();X[K]=Q(X[K]);let G=J.messages.slice();G[Z]={...W,content:X};let V=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:V,messages:G}}return J}function a8(J,$,Q){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((K)=>K.id),loadedTools:[],finishReason:J.finishReason},W=WZ(Z,$.event,Q);return{...J,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function t8(J,$,Q){if($.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Q))}function JZ(J,$){let Q=J.messages.find((Z)=>Z.id===$);return Q!==void 0&&Q.finishReason!==void 0}function b(J,$,Q,Z){let W=J.messages.findIndex((G)=>G.id===$),K=J.runMessageIds.includes($)?J.runMessageIds:[...J.runMessageIds,$];if(W===-1){let G={id:$,role:"assistant",content:[],createdAt:Q};return{...J,runMessageIds:K,messages:[...J.messages,Z(G)]}}let X=J.messages.slice();return X[W]=Z(X[W]),{...J,runMessageIds:K,messages:X}}function r8(J,$){let Q=J[J.length-1];if(Q&&Q.type==="text")return[...J.slice(0,-1),{type:"text",text:Q.text+$}];return[...J,{type:"text",text:$}]}function e8(J,$,Q){let Z=J[J.length-1];if(Z&&Z.type==="reasoning"&&Z.id===Q)return[...J.slice(0,-1),{...Z,text:(Z.text??"")+$}];return[...J,Q?{type:"reasoning",id:Q,text:$}:{type:"reasoning",text:$}]}function $Z(J,$,Q){let Z=J.findIndex(Q);if(Z===-1)return[...J,$];let W=J.slice();return W[Z]=$,W}class M${store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,$,Q,Z){this.store=J;this.threadId=$;this.report=Z;this.state=QZ({messages:Q})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[B$(J)])}frame(J){if(this.closed)return;let $=J.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=ZZ(this.state,J),$.type){case"message":this.write(()=>[B$($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let $ of J)this.done.add($.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let $=this.state.messages.find((Z)=>Z.id===J);if(!$)return;let Q=this.runId;this.write(()=>{let Z=B$($);if(Z.finishReason===void 0&&Q)Z.runId=Q;return[Z]})}write(J){let $;try{$=J()}catch(Q){this.report(Q);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Q)=>this.report(Q))}}function B$(J){return structuredClone(J)}async function XZ(J,$){let Q=[],Z=null,W=J.slice();for(let K=0;K<W.length;K++){let X=W[K];if(X.role!=="assistant"||X.finishReason!==void 0)continue;if(X.runId&&await $(X.runId))continue;Z??=new Set(J.flatMap((Y)=>Y.content.flatMap((z)=>z.type==="tool-result"?[z.toolCallId]:[])));let G=X.content.map((Y)=>Y.type==="tool-call"?GZ(Y):Y);for(let Y of X.content){if(Y.type!=="tool-call"||Z.has(Y.toolCallId))continue;let z={type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"denied",cause:"interrupted"};G.push(z)}let V={...X,content:G,finishReason:"interrupted"};W[K]=V,Q.push(V)}return{messages:W,settled:Q}}function GZ(J){let{partial:$,...Q}=J;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(J9)}}function J9(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Q)=>Q.type==="tool-call"?GZ(Q):Q)}:$)}}var $9=50,Q9=["waiting","running","ok","error"];async function zZ(J,$){let{store:Q,threadId:Z}=$,W=Math.max($9,$.scan??0),K=await Q.listForThread(Z,{limit:W}),X,G=async(P)=>{if(P.state!=="running")return P;if(X??=await YZ(Q),P.deadlineAt>X)return P;return await VZ(Q,P),await Q.get(P.id)??P};for(let P=0;P<K.length;P++)K[P]=await G(K[P]);let V=new Map(K.map((P)=>[P.id,P])),Y=J.slice(),z=[],D=new Set;for(let P=0;P<Y.length;P++){let U=Y[P],O=null;for(let F=0;F<U.content.length;F++){let H=U.content[F];if(H.type==="tool-call")D.add(H.toolCallId);if(H.type!=="tool-result"||H.status!=="running")continue;let C=H.job?.id,L=C?V.get(C):void 0;if(C&&L===void 0){let T=await Q.get(C);if(L=T?await G(T):void 0,L)V.set(C,L)}if(L&&!f(L.state))continue;O??=U.content.slice(),O[F]=Z9(H,L,$.outputSchemaFor,$.modelOutputFor)}if(O){let F={...U,content:O};Y[P]=F,z.push(F)}}let N=[];for(let P of K){if(P.orphaned||P.toolCallId===""||D.has(P.toolCallId))continue;if(await $.isRunLive(P.runId))continue;N.push(P)}return{messages:Y,settled:z,orphans:N,jobs:K}}async function DZ(J,$,Q){for(let Z of $)try{await J.transition(Z.id,Q9,{orphaned:!0})}catch(W){Q(W)}}function Z9(J,$,Q,Z){let W={type:"tool-result",toolCallId:J.toolCallId,name:J.name},K=(V,Y)=>{let z=Z?.(String(J.name),V);return{...W,status:"ok",job:Y,output:V,...z!==void 0?{modelOutput:z}:{}}};if(!$)return{...W,status:"error",job:J.job,error:{code:"tool_error",message:`The background job for "${String(J.name)}" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,toolCallId:J.toolCallId,retryable:!0}};let X={id:$.id,...$.summary!==void 0?{summary:$.summary}:{},...$.usage?{usage:$.usage}:{}};if($.state==="error")return{...W,status:"error",job:X,error:$.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let G=Q?.(String(J.name));if(G){let V=G.safeParse($.output);if(V.ok===!1)return{...W,status:"error",job:X,error:{code:"invalid_tool_result",message:`The background job for "${String(J.name)}" finished with an output that does not match the tool's output schema: ${V.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return K(V.value,X)}return K($.output,X)}var W9=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;class hJ extends Error{status;code;kind;constructor(J,$){super(J);this.name="AgentTurnError",this.status=$.status,this.code=$.code,this.kind=$.kind}static async from(J){let $={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")$=Z.error}catch{}let Q=(Z)=>typeof $[Z]==="string"?$[Z]:void 0;return new hJ(Q("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:Q("code"),kind:Q("kind")})}}function K9(J){for(let $=J.length-1;$>=0;$--){let Q=J[$];if(Q.role!=="assistant")continue;return Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var X9=kZ,zJ=new Map,S$=new WeakMap,a=new WeakMap,HZ=new WeakMap,PZ=new WeakMap,A$=new WeakMap,nZ="thread_busy",FZ="http://gemi.internal/__gemi/agent-turn",IJ=new Map,G9=4194304,Y9=1000,V9=5,DJ=65536,r=()=>{};class oZ{byKey=new Map;take(J,$,Q){let Z=this.byKey.get(J);if(!Z?.has($)&&(Z?.size??0)>=Q)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set($,(Z.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let K=this.byKey.get(J),X=(K?.get($)??1)-1;if(!K)return;if(X>0)K.set($,X);else if(K.delete($),K.size===0)this.byKey.delete(J)}}}var NZ=new WeakMap,E$=new WeakMap;function z9(J){let $=E$.get(J);if(!$)$=new Map,E$.set(J,$);return $}function D9(J,$,Q){let Z=E$.get(J)?.get($);if(!Z)return;for(let W of[...Z])try{W(Q)}catch{}}function H9(J){let $=NZ.get(J);if(!$)$=new oZ,NZ.set(J,$);return $}function P9(J){return J}class y$ extends X9{static kind="agent-controller";hooks;store=_$;storeScope(J,$){return null}boundScope=void 0;async threadInScope(J,$){if(await this.scopeStore(J,{}),this.boundScope===null)return!0;return await this.store.loadThread($)!==null}async scopeStore(J,$){let Z=HZ.get(J)??await this.storeScope(J,{body:$})??null;if(this.boundScope!==void 0){if(this.boundScope!==Z)throw Error("This AgentController instance already served a request in another store scope. Build a controller per request (the router and startTurn do).");return}if(Z!==null)this.store=RZ(this.store,Z);this.boundScope=Z}liveRuns=F$;voice;voiceStore=D$;attachments=vJ;attachmentStorage=xZ;fileOwners=N$;nonces=w$;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,$){return this.hooks?.instructions?.(J,$)}reasoning(J,$){return this.hooks?.reasoning?.(J,$)}skills(J,$){return this.hooks?.skills?.(J,$)}runTools(J,$){return this.hooks?.runTools?.(J,$)}usageLimits(J,$){return this.hooks?.usageLimits?.(J,$)}context(J,$){let Q=this.hooks?.context;if(Q)return Q(J,$);return{}}memoryScopes(J,$){let Q=this.hooks?.memoryScopes;if(Q)return Q(J,$);return{}}memoryMaxTokens=void 0;requireThread=!1;maxBodyBytes=G9;maxHistoryMessages=Y9;contextWindow=void 0;prepareStep(J,$){return this.hooks?.prepareStep?.(J,$)}maxConcurrentRuns=V9;runLimitKey(J,$){let Q=this.hooks?.runLimitKey;if(Q)return Q(J,$);return $.owner}authorizeRequest(J,$){let Q=this.hooks?.authorizeRequest;if(Q)return Q(J,$);return this.resource?.authorize(J,$)}resource;runOwner(J){let $=this.hooks?.runOwner;if($)return $(J);let Q=J.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(J){let{threadId:$}=J;if(typeof $!=="string"||$==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let Q=J.ifBusy??"supersede";if(Q!=="supersede"&&Q!=="queue"&&Q!=="skip")throw TypeError(`AgentController.startTurn's \`ifBusy\` is "supersede", "queue" or "skip"; got ${JSON.stringify(J.ifBusy)}.`);let Z=J.event===void 0?void 0:R9(J),W={...J.turn,...J.text!==void 0?{text:J.text}:{}},K={...J.body,threadId:$,turn:W},X=new j(new Request(FZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K)}),{},"api",new URL(FZ).pathname),G=new this;if(a.set(X,null),J.scope!==void 0)HZ.set(X,J.scope);if(PZ.set(X,Q),Z)A$.set(X,Z);let V=await h.run(X,()=>G.stream(X),{user:J.user??null}),Y=a.get(X);if(!Y){let O=await hJ.from(V);if(Q==="skip"&&O.code===nZ)return{skipped:!0,threadId:$};throw O}a.delete(X),V.body?.cancel().catch(r);let{run:z,hooks:D}=Y,N=[],P=(async()=>{for await(let O of z)if(O.type==="awaiting-input")N=O.pending})().catch(r),U;return{runId:z.runId,threadId:$,run:z,stop:(O)=>z.stop(O),result:()=>U??=(async()=>{let O=await z.result();await Promise.all([D,P]);let F=O.messages;return{...O,threadId:$,text:K9(F),pending:O.finishReason==="awaiting-input"?N:[]}})()}}async stream(J=new j){let $=await t(J,this.maxBodyBytes);if($.error)return c($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=B9(Q);if(W.error)return c({body:{},error:W.error});let K=W.turn,X=Z!==void 0&&Q.regenerate===!0,G=typeof Q.clientRunId==="string"?Q.clientRunId:void 0,V=fJ(Q);if(this.requireThread&&!Z)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(await this.scopeStore(J,V),X&&!this.store.removeMessages)return M(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!Z&&Array.isArray(Q.messages)&&Q.messages.length>this.maxHistoryMessages)return x$(413,"history_too_long",`The conversation has ${Q.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(J),z=G?{cancelled:!1,owner:Y}:null;if(z)IJ.set(G,z);let D=null,N=[],P=async()=>{try{return await U()}finally{if(Z&&N.length>0&&D===null)await this.store.appendMessages(Z,N).catch((O)=>this.reportHookFailure(O))}},U=async()=>{let O,F=null;if(Z){let S=await this.store.loadThread(Z);if(!S)return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let l=await this.settleThread(Z,S,{write:!0});if(O=l.messages,F=this.jobsBlock(l.jobs),X){let e=A9(O);if(!e)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});N=O.slice(e.index),await this.store.removeMessages(Z,N.map((eZ)=>eZ.id)),O=O.slice(0,e.index),K=K?.localId?{...e.turn,localId:K.localId}:e.turn}}else O=Array.isArray(Q.messages)?Q.messages:[],f9(this.nonces);let H=[await this.instructions(J,{body:V})||void 0,F??void 0].filter(Boolean).join(`
264
299
 
265
- `)||void 0,L=await this.context(J,{body:V}),_=await this.reasoning(J,{body:V})||void 0,R=await this.skills(J,{body:V})||void 0,A=await this.runTools(J,{body:V,context:L})||void 0,x=await this.usageLimits(J,{body:V,context:L})||void 0,f=await this.attachmentsFor(J,Z,{body:V}),q=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(H?.cancelled)return _Q();let O=Z?new J8(this.store,Z,N,(E)=>this.reportHookFailure(E)):null,C=`run_${crypto.randomUUID()}`,M={req:J,runId:C,threadId:Z},w={id:null,notified:Promise.resolve()},I=this.agent.stream({runId:C,messages:N,turn:K,threadId:Z,...O?{onMessage:(E)=>O.finish(E)}:{},onTurn:(E)=>{if(w.id!==null)return;w.id=E.id;let a=O?O.settled():Promise.resolve();w.notified=a.then(()=>this.safely(()=>this.onMessage(E,M)))},instructions:U,...Q8.has(J)?{event:Q8.get(J)}:{},...ZJ.has(J)?{echoTurn:!0}:{},..._?{reasoning:_}:{},...R&&R.length>0?{skills:R}:{},...A?.tools&&A.tools.length>0?{tools:A.tools}:{},...A?.activeTools?{activeTools:A.activeTools}:{},...x?{usageLimits:x}:{},context:L,attachments:f,body:V,redactError:(E,a)=>this.redactError(E,a,M),onProviderRetry:(E)=>this.onProviderRetry(E,M),nonces:this.nonces,receipts:this.receipts,subject:G,...q?{memory:{scopes:q,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:G}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&pQ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==F8.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(E)=>this.prepareStep(E,M)}:{}}),J$=this.liveRuns.register(I,{threadId:Z,owner:G,clientRunId:Y,onEvent:(E)=>this.dispatchEvent(E,M),onInternalError:(E)=>this.reportHookFailure(E),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=I,O)this.follow(I,O);if(Z)p6(this.liveRuns,Z,I.runId);let{stored:$$,hooks:P8}=this.persistRun(I,M,J$,O,w);if($8.set(I,$$),ZJ.has(J))ZJ.set(J,{run:I,hooks:P8});return J.ctx?.()?.waitUntil(P8),I.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let N=await this.foreignFile([...K?.files??[],...Z?[]:K0(Q.messages)],G);if(N)return N;if(H?.cancelled)return _Q();let P=await this.runLimitKey(J,{owner:G,threadId:Z}),U=P===null?KJ:l6(this.liveRuns).take(P,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!U)return Y8(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return Z?await this.withThread(Z,G,F,FQ.get(J)??"supersede"):await F()}finally{let L=D;if(L)L.result().then(U,U);else U()}}finally{if(H&&nJ.get(Y)===H)nJ.delete(Y)}}async withThread(J,$,Q,Z="supersede"){if(Z==="skip"&&OJ.has(J))return MQ(J);for(;;){let W=await this.underThreadLock(J,$,Q,Z);if(!("waitFor"in W))return W.response;await W.waitFor}}async underThreadLock(J,$,Q,Z){let W=OJ.get(J)??Promise.resolve(),K,X=new Promise((V)=>{K=V}),Y=W.then(()=>X);OJ.set(J,Y),await W;try{let V=await this.liveRuns.find({threadId:J});if(V&&Z!=="supersede"&&this.liveRuns.isRunning(V.runId)){if(Z==="skip")return{response:MQ(J)};let H=this.liveRuns.get(V.runId),D=H?$8.get(H)??H.result():null;if(D)return{waitFor:D.then(KJ,KJ)}}if(V&&this.liveRuns.isRunning(V.runId)&&!this.liveRuns.mayAccess(V.runId,$))return{response:MJ()};let G=V?this.liveRuns.get(V.runId):null;if(G)G.stop({reason:"superseded by a later turn on this thread"}),await $8.get(G);return{response:await Q()}}finally{if(K(),OJ.get(J)===Y)OJ.delete(J)}}async attach(J=new b){let $=await WJ(J,_J);if($.error)return s($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:OQ(J,"threadId");if(!Z)return S(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=Q.emptyMiss===!0;if(!await this.threadInScope(J,Z))return EQ(Z,W);let K=await this.liveRuns.find({threadId:Z});if(K&&!this.liveRuns.mayAccess(K.runId,await this.runOwner(J)))return MJ();if(!K)return EQ(Z,W);let X=typeof Q.runId==="string"?Q.runId:void 0,Y=X&&X!==K.runId?void 0:$0(J,Q);try{return bQ(this.liveRuns.replay(K.runId,Y))}catch(V){if(V instanceof QJ)return S(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof LJ)return S(404,{code:V.code,message:V.message});throw V}}async watch(J=new b){let $=await WJ(J,_J);if($.error)return s($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:OQ(J,"threadId");if(!Z)return S(400,{code:"invalid_request",message:"watch needs a threadId: it is the thread whose runs are announced."});if(await this.authorizeRequest(J,{route:"attach",threadId:Z}),!await this.threadInScope(J,Z))return S(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let W=await this.runOwner(J),K=this.liveRuns,X=m6(K),Y=await K.find({threadId:Z}),V=null,G=null,H=0,D=()=>{if(G?.stop(),!V)return;let F=X.get(Z);if(F?.delete(V),F&&F.size===0)X.delete(Z);V=null},z=new ReadableStream({start(F){G=wQ(F);let B=(P)=>{if(!K.mayAccess(P,W))return;try{F.enqueue(new TextEncoder().encode(IQ({seq:++H,event:{type:"run-start",runId:P,threadId:Z}}))),G?.touch()}catch{D()}};V=B;let N=X.get(Z);if(!N)N=new Set,X.set(Z,N);if(N.add(B),Y&&K.isRunning(Y.runId))B(Y.runId)},cancel(){D()}});return J.rawRequest?.signal?.addEventListener("abort",D,{once:!0}),new Response(z,{status:200,headers:qQ()})}async stop(J=new b){let $=await WJ(J,_J);if($.error)return s($);let Q=$.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner(J),W=typeof Q.runId==="string"?Q.runId:void 0;if(!W&&typeof Q.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Q.clientRunId)??void 0,!W){let X=nJ.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return MJ();return X.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Q.threadId==="string")W=(await this.liveRuns.find({threadId:Q.threadId}))?.runId;let K=W?this.liveRuns.get(W):null;if(!K)return{stopped:!1};if(!this.liveRuns.mayAccess(K.runId,Z))return MJ();return K.stop({reason:typeof Q.reason==="string"?Q.reason:void 0}),{stopped:!0}}attachmentScope(J,$,Q){let Z=this.hooks?.attachmentScope;if(Z)return Z(J,$,Q);let W=J.ctx()?.user,K=W?.id??W?.publicId;if(K!==void 0&&K!==null&&String(K)!=="")return{key:`user:${String(K)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(J){let $=this.hooks?.attachmentLimits;if($)return $(J);return null}checkUpload(J,$,Q){return this.hooks?.checkUpload?.(J,$,Q)}attachmentDestination(J,$,Q){let Z=this.hooks?.attachmentDestination;if(Z)return Z(J,$,Q);return"both"}async attachmentsFor(J,$,Q={body:{}}){let Z=await this.attachmentScope(J,$,Q);if(!Z)return null;return new tJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new b){let $=this.voice;if(!$)return Z8();let Q=await WJ(J,_J);if(Q.error)return s(Q);let{sdp:Z,threadId:W,pushToTalk:K}=Q.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return S(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let X=oJ(Q.body,X0),Y=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:Y,body:X});let V=J.ctx?.()?.user??null,G=await $.start({req:J,body:X,threadId:Y,user:V,pushToTalk:K===!0}),H=Date.now(),D,z=async(L)=>{if(L!==void 0)console.error("[gemi/ai] a voice session could not start.",L);if(D)await $.realtime.hangup(D).catch((_)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",_)});try{await G.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:G.threadId??Y??"",reason:"start_failed",startedAt:H,endedAt:Date.now(),durationMs:0,seconds:0,usage:j(),transcription:{usage:j(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(_){console.error("[gemi/ai] a voice session's onEnd threw.",_)}},F=G.threadId??Y;if(!F)return await z(void 0),S(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(F!==Y)await this.authorizeRequest(J,{route:"stream",threadId:F,body:X})}catch(L){throw await z(void 0),L}let B=crypto.randomUUID(),N=G.tools??[];try{if(G.mcp)N=[...N,...await c$(G.mcp,{user:V,sessionId:B})]}catch(L){return await z(L),S(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...G.session,tools:[...UJ($.delegate),...G.session?.tools??[],...N.map((L)=>L.tool)],...K===!0?{turnDetection:null}:{}},U;try{U=await $.realtime.createCall({sdp:Z,session:P,safetyIdentifier:G.safetyIdentifier})}catch(L){await z(L);let _=L instanceof g&&L.code==="rate_limited";return S(_?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=U.callId;try{await this.voiceStore.create({id:B,callId:U.callId,threadId:F,owner:await this.runOwner(J),body:X,startedAt:H});let{threadId:L,session:_,safetyIdentifier:R,mcp:A,tools:x,...f}=G;return{sessionId:o.start({...f,tools:N,controller:this.constructor,threadId:F,user:V,body:X,call:{realtime:$.realtime,callId:U.callId},sessionId:B,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:P}).sessionId,sdp:U.sdpAnswer,threadId:F,delegate:$.delegate?.name??NJ,endsAt:H+(G.limits?.maxDurationMs??900000)}}catch(L){return await z(L),S(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new b){if(!this.voice)return Z8();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await WJ(J,_J);if(Q.error)return s(Q);let Z=oJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return S(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),o.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new b){let $=this.voice;if(!$)return Z8();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Q.body}),Q.endedAt!==void 0)return{ended:!1};let Z=o.get(Q.id);if(Z)await Z.end("hangup");else await $.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let $=J.params?.sessionId,Q=typeof $==="string"&&$?await this.voiceStore.get($):null;if(!Q)return S(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return MJ();return Q}async upload(J=new b){let $=await J.rawRequest.formData(),Q=$.get("file");if(!(Q instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=Q instanceof File&&Q.name?Q.name:"upload",W=Q.type||"application/octet-stream",K=n6($.get("body")),X=$.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:K});let Y=s6(await this.attachmentLimits(J),Q,Z,W);if(Y)throw new G8(Y.code,Y.message);await this.scopeStore(J,K);let V=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,G=await this.runOwner(J),H=(A)=>this.fileOwners.record(A,{owner:G,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString()}),D={body:K,threadId:V},z=await this.checkUpload({name:Z,size:Q.size,mimeType:W},J,D);if(z)throw new G8(z.code||"upload_refused",z.message);let F=await this.attachmentDestination(Q,J,D),B=G0(F,$.get("destination")),N=await this.attachmentScope(J,V,{body:K}),P=B!=="provider"&&!N;if(P){if(B==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');Y0()}if(B==="provider"||!N){let A=await NQ(this.agent.provider,Q);await H(A);let x={fileId:A,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(P)x.downgraded="no_scope";return x}let U=uQ(),L=await this.attachmentStorage.put({name:cQ(U,Z),body:Q,contentType:W}),_=B==="both"?await NQ(this.agent.provider,Q):void 0;if(_)await H(_);let R={id:U,scopeKey:N.key,fileId:_,objectName:L,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:B};return await this.attachments.put(N,R),{fileId:_,attachmentId:U,name:Z,mimeType:W,size:Q.size,destination:B}}async foreignFile(J,$){let Q=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of Q){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return W0()}return null}onMessage(J,$){return this.hooks?.onMessage?.(J,$)}onToolCall(J,$){return this.hooks?.onToolCall?.(J,$)}onToolResult(J,$,Q){return this.hooks?.onToolResult?.(J,$,Q)}onAwaitingInput(J,$){return this.hooks?.onAwaitingInput?.(J,$)}redactError(J,$,Q){let Z=this.hooks?.redactError;if(Z)return Z(J,$,Q);return z8(J,$)}onError(J,$){return this.hooks?.onError?.(J,$)}onProviderRetry(J,$){return this.hooks?.onProviderRetry?.(J,$)}onStreamComplete(J,$){return this.hooks?.onStreamComplete?.(J,$)}reportHookFailure(J){let $=this.hooks?.reportHookFailure;if($)try{return $(J)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,$){switch(J.type){case"tool-call":if(!J.part.partial&&!J.resent)await this.onToolCall({toolCallId:J.part.toolCallId,name:String(J.part.name),input:J.part.input},$);return;case"tool-result":{let Q=J.part;await this.onToolResult(Q,$,{toolCallId:Q.toolCallId,name:String(Q.name),input:dQ(Q)});return}case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(vQ(J.error),$);return;default:return}}async readThread(J,$={}){let Z=await($.scope===null||$.scope===void 0?this.store:RQ(this.store,$.scope)).loadThread(J);if(!Z)return null;let{messages:W}=await this.settleThread(J,Z,{write:!1});return W}isRunLive(J,$){return this.liveRuns.get(J)!==null}async settleThread(J,$,{write:Q}){let Z=(V)=>this.isRunLive(V,J),W=await XQ($,Z),K=W.messages,X=[],Y=new Map(W.settled.map((V)=>[V.id,V]));if(D0(K)||Q)try{let V=await HQ(K,{threadId:J,store:c.store,isRunLive:Z,outputSchemaFor:(G)=>this.toolNamed(G)?.outputSchema,modelOutputFor:(G,H)=>lQ(this.toolNamed(G),H,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});K=V.messages,X=V.jobs;for(let G of V.settled)Y.set(G.id,G);if(Q&&V.orphans.length>0){await zQ(c.store,V.orphans,(H)=>this.reportHookFailure(H));let G=new Set(V.orphans.map((H)=>H.id));X=X.map((H)=>G.has(H.id)?{...H,orphaned:!0}:H)}}catch(V){this.reportHookFailure(V)}if(Q&&Y.size>0)try{await this.store.appendMessages(J,[...Y.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:X}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??EJ}jobsBlock(J){return S8(J,this.jobsBlockMax())}toolNamed(J){let $=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let K=$(W.tools);if(K)return K}else if(W.name===J)return W}return};return $(this.agent.tools??[])}follow(J,$){(async()=>{try{for await(let Q of J.frames())$.frame(Q)}catch(Q){this.reportHookFailure(Q)}})()}persistRun(J,$,Q,Z=null,W={id:null,notified:Promise.resolve()}){let K=Promise.resolve(),X=(async()=>{let V;try{V=await J.result()}catch(H){Z?.close(),await Z?.settled(),K=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},$)));return}let G=V.messages;if(Z?.close(G),await Z?.settled(),$.threadId&&G.length>0)try{await this.store.appendMessages($.threadId,G)}catch(H){this.reportHookFailure(H)}K=this.notifyRun(V,G,$,W)})(),Y=X.then(()=>H0(Promise.all([K,Q]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:Y}}async notifyRun(J,$,Q,Z){await Z.notified;for(let W of $){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete(J,Q))}async safely(J){try{await J()}catch($){this.reportHookFailure($)}}}var K8=["turn","clientRunId","threadId","messages","regenerate"],i6=["text","files","toolResults"];function oJ(J,$=sQ(J)?K8:[...K8,...i6]){let Q={};for(let[Z,W]of Object.entries(J)){if($.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function n6(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new X8("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new X8("The upload's `body` field must be a JSON object.");return oJ($,K8)}class X8 extends sJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function NQ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof y&&o6.has(Q.status))throw new oQ(T(Q).message);throw Q}}var o6=new Set([400,413,415,422]);class G8 extends sJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function s6(J,$,Q,Z){if(!J)return null;let{maxBytes:W,accept:K}=J;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${BQ($.size)}; the limit is ${BQ(W)}.`};if(K&&K.length>0&&!K.some((X)=>a6(X,Q,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify(Q)} is not a type this chat accepts. Accepted: ${K.join(", ")}.`};return null}function a6(J,$,Q){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return $.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function BQ(J){if(J<1024)return`${J} B`;let $=["KB","MB","GB"],Q=J/1024,Z=0;while(Q>=1024&&Z<$.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${$[Z]}`}class oQ extends sJ{constructor(J){super(J);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(J)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:J}}},view:{}}}}async function WJ(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!t6(Q.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number(Q.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>$)return LQ($);let W;try{let X=await r6(Q,$);if(X===null)return LQ($);W=X}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let K;try{K=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(K===null||typeof K!=="object"||Array.isArray(K))return{body:{},error:"The request body must be a JSON object."};return{body:K}}function t6(J){return TQ(J)==="application/json"}async function r6(J,$){if(!Number.isFinite($)||!J.body)return await J.text();let Q=J.body.getReader(),Z=[],W=0;for(;;){let{done:Y,value:V}=await Q.read();if(Y)break;if(W+=V.byteLength,W>$)return await Q.cancel().catch(KJ),null;Z.push(V)}let K=new Uint8Array(W),X=0;for(let Y of Z)K.set(Y,X),X+=Y.byteLength;return new TextDecoder().decode(K)}function LQ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function Y8(J,$,Q){return S(J,{...aJ(kQ(J),Q,J),code:$})}function s(J){if(J.status===413)return Y8(413,J.code??"body_too_large",J.error??"");return S(J.status??400,{code:J.code??"invalid_request",message:J.error})}function sQ(J){return Boolean(J.turn)&&typeof J.turn==="object"}function e6(J){let $=sQ(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=J0($.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray($.toolResults))Q.toolResults=$.toolResults;if(Object.keys(Q).length===0)return{};if($===J.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:Z}=$;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>CQ)return{error:`turn.localId is longer than ${CQ} characters.`};Q.localId=Z}return{turn:Q}}var CQ=200;function J0(J){let $=[];for(let[Q,Z]of J.entries()){let W=`turn.files[${Q}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let K={};for(let H of["fileId","attachmentId","name","mimeType"]){let D=Z[H];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${H} must be a string.`;K[H]=D}let{fileId:X,attachmentId:Y,name:V,mimeType:G}=K;if(X?.startsWith(n))return`${W}.fileId holds a gemi attachment id (${X}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(Y!==void 0&&!Y.startsWith(n))return`${W}.attachmentId is not a gemi attachment id: it must start with "${n}".`;if(!X&&!Y)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...X?{fileId:X}:{},...Y?{attachmentId:Y}:{},...V!==void 0?{name:V}:{},...G!==void 0?{mimeType:G}:{}})}return $}function $0(J,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let Z=Math.floor($.cursor);if(Z>=0)return Z+1;return}let Q=J?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function OQ(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function Q0(J){let $=D8(J);for(let Q=J.length-1;Q>=0;Q--){let Z=J[Q];if(Z.role!=="user"||$.has(Z.id))continue;let W="",K=[];for(let X of Z.content){if(X.type==="text")W+=X.text;if(X.type==="file")K.push({...X.fileId?{fileId:X.fileId}:{},...X.attachmentId?{attachmentId:X.attachmentId}:{},...X.name?{name:X.name}:{},...X.mimeType?{mimeType:X.mimeType}:{}})}if(!W&&K.length===0)continue;return{index:Q,turn:{...W?{text:W}:{},...K.length>0?{files:K}:{}}}}return null}function _Q(){return S(409,{code:"stopped",message:"The turn was stopped before it started."})}function Z0(J){let $=J.event;if(J.text!==void 0||J.turn!==void 0)throw TypeError("AgentController.startTurn takes an `event` or a `text`/`turn`, not both: an event is not a person's message.");if(typeof $!=="object"||$===null||typeof $.name!=="string"||!y6.test($.name))throw TypeError('AgentController.startTurn\'s `event.name` must be letters, digits and `.`, `_`, `:`, `-` (at most 64), like "job-settled".');if($.text!==void 0&&typeof $.text!=="string")throw TypeError("AgentController.startTurn's `event.text` must be a string.");let Q;if($.data!==void 0)try{Q=JSON.parse(JSON.stringify($.data))}catch(Z){throw TypeError(`AgentController.startTurn's \`event.data\` is not JSON: ${String(Z)}`)}return{name:$.name,...$.text?{text:$.text}:{},...Q!==void 0?{data:Q}:{}}}function MQ(J){return S(409,{code:iQ,message:`Thread ${J} has a run going, and this turn was not to interrupt it.`})}function MJ(){return S(403,aJ("permission","This run belongs to someone else.",403))}function W0(){return S(403,aJ("permission","A file in this turn was uploaded by someone else.",403))}function K0(J){if(!Array.isArray(J))return[];let $=[];for(let Q of J){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}var X0=["sdp","threadId","pushToTalk"];function Z8(){return S(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function S(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function G0(J,$){if(typeof $!=="string"||$.length===0)return J;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===J||J==="both"&&$==="storage")return $;if(J==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${J}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var SQ=!1;function Y0(){if(SQ)return;SQ=!0,console.warn("[gemi/ai] An upload had no attachment scope, so its bytes were sent to the model provider only and no attachment id was minted \u2014 a tool cannot forward this file. Guard the route with auth, send a `threadId` with the upload, or override `attachmentScope()`.")}var V0=2147483647;function H0(J,$){let Q=J.then(()=>{},()=>{});if(!($<=V0))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var AQ=!1;function z0(J){if(AQ||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof V8))return;AQ=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}function D0(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}function RQ(J,$){if(typeof $!=="string"||$==="")throw TypeError("A store scope is a non-empty string.");if(!J.forScope)throw Error("This controller's store cannot be scoped: storeScope() or a turn's `scope` needs a store that implements `forScope` (DatabaseAgentStore or MemoryAgentStore).");return J.forScope($)}function EQ(J,$=!1){if($)return new Response(null,{status:204});return S(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`})}export{M0 as windowMessages,UJ as voiceTools,B0 as turnStarts,hJ as toRealtimeUsage,BZ as toAgentTools,U0 as supportsStrict,L0 as splitTurns,T0 as settleSummaries,P0 as s,z8 as redactError,h0 as parsePartialJson,C0 as messageSize,HJ as measureUsage,c$ as mcpVoiceTools,i$ as liveRuns,BJ as keepSummary,y9 as isCallNotFound,D8 as injectedMessageIds,N$ as generate,z6 as evalChain,d6 as defineAgentHooks,p$ as defaultVoiceStore,I0 as defaultUsageLimitStore,k0 as defaultSummaryStore,H8 as defaultNonceStore,n$ as defaultFileOwners,rJ as defaultAttachmentStore,r$ as defaultAgentStore,lJ as VoiceHangup,o as VoiceBridge,N0 as Usage,L$ as ToolNamespace,l as ToolError,q0 as Skill,tJ as ScopedAttachments,b0 as SKILLS_NAMESPACE,t$ as RedisReceiptStore,fQ as RedisNonceStore,gJ as RealtimeSideband,g as RealtimeRequestError,FJ as RealtimeClient,O8 as Prompt,yQ as PrismaNonceStore,w0 as PendingEscalation,v$ as OpenAIProvider,S$ as OpenAIImageProvider,m$ as MemoryVoiceSessionStore,x0 as MemoryUsageLimitStore,j0 as MemorySummaryStore,a$ as MemoryReceiptStore,V8 as MemoryNonceStore,dJ as MemoryLiveRuns,iJ as MemoryFileOwners,mJ as MemoryCircuitStore,mQ as MemoryAttachmentStore,CJ as MemoryAgentStore,E8 as MemoryAgentJobStore,p8 as MEMORY_NAMESPACE,LJ as LiveRunNotFoundError,k8 as JobsRequireThreadError,j8 as JobHandle,F0 as JSONSchemaError,gQ as InvalidAttachmentScopeError,v8 as InMemoryAgentMemoryStore,fJ as ImageRequestError,yJ as ImageProvider,C$ as ImageModel,QJ as FrameCursorEvictedError,PJ as FallbackProvider,c8 as FakeAgentMemoryStore,IJ as Eval,l$ as DatabaseAgentStore,H$ as DatabaseAgentMemoryStore,Y$ as DatabaseAgentJobStore,b9 as DEFAULT_TRANSCRIPTION_MODEL,y8 as DEFAULT_MEMORY_MAX_TOKENS,m8 as DEFAULT_MEMORY_LIMITS,S0 as DEFAULT_MAX_SUMMARY_TOKENS,f0 as DEFAULT_MAX_RUN_DURATION_MS,T8 as DEFAULT_JOB_DEADLINE_MS,EJ as DEFAULT_JOBS_CONTEXT_MAX,NJ as DEFAULT_DELEGATE_NAME,O0 as DEFAULT_CONTEXT_WINDOW_STEP,_0 as DEFAULT_CONTEXT_WINDOW_NOTE,A0 as DEFAULT_COMPACT_TRIGGER_TOKENS,R0 as DEFAULT_COMPACT_INSTRUCTIONS,E0 as COMPACT_SUMMARY_HEADER,h$ as AzureOpenAIProvider,A$ as AzureOpenAIImageProvider,hQ as AttachmentNotFoundError,eJ as AgentTurnError,wJ as AgentTool,y0 as AgentRunError,$J as AgentProvider,h8 as AgentMemoryRefusedError,g8 as AgentMemoryConflictError,u8 as AgentMemories,c as AgentJobs,K$ as AgentJobDeadlineSweep,x8 as AgentJob,F8 as AgentController,v0 as Agent};
300
+ `)||void 0,C=await this.context(J,{body:V}),L=await this.reasoning(J,{body:V})||void 0,T=await this.skills(J,{body:V})||void 0,R=await this.runTools(J,{body:V,context:C})||void 0,x=await this.usageLimits(J,{body:V,context:C})||void 0,m=await this.attachmentsFor(J,Z,{body:V}),p=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(z?.cancelled)return BZ();let B=Z?new M$(this.store,Z,O,(S)=>this.reportHookFailure(S)):null,E=`run_${crypto.randomUUID()}`,_={req:J,runId:E,threadId:Z},PJ={id:null,notified:Promise.resolve()},w=this.agent.stream({runId:E,messages:O,turn:K,threadId:Z,...B?{onMessage:(S)=>B.finish(S)}:{},onTurn:(S)=>{if(PJ.id!==null)return;PJ.id=S.id;let l=B?B.settled():Promise.resolve();PJ.notified=l.then(()=>this.safely(()=>this.onMessage(S,_)))},instructions:H,...A$.has(J)?{event:A$.get(J)}:{},...a.has(J)?{echoTurn:!0}:{},...L?{reasoning:L}:{},...T&&T.length>0?{skills:T}:{},...R?.tools&&R.tools.length>0?{tools:R.tools}:{},...R?.activeTools?{activeTools:R.activeTools}:{},...x?{usageLimits:x}:{},context:C,attachments:m,body:V,redactError:(S,l)=>this.redactError(S,l,_),onProviderRetry:(S)=>this.onProviderRetry(S,_),nonces:this.nonces,receipts:this.receipts,subject:Y,...p?{memory:{scopes:p,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&lZ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==y$.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(S)=>this.prepareStep(S,_)}:{}}),tZ=this.liveRuns.register(w,{threadId:Z,owner:Y,clientRunId:G,onEvent:(S)=>this.dispatchEvent(S,_),onInternalError:(S)=>this.reportHookFailure(S),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=w,B)this.follow(w,B);if(Z)D9(this.liveRuns,Z,w.runId);let{stored:rZ,hooks:v$}=this.persistRun(w,_,tZ,B,PJ);if(S$.set(w,rZ),a.has(J))a.set(J,{run:w,hooks:v$});return J.ctx?.()?.waitUntil(v$),w.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let O=await this.foreignFile([...K?.files??[],...Z?[]:k9(Q.messages)],Y);if(O)return O;if(z?.cancelled)return BZ();let F=await this.runLimitKey(J,{owner:Y,threadId:Z}),H=F===null?r:H9(this.liveRuns).take(F,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!H)return x$(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return Z?await this.withThread(Z,Y,P,PZ.get(J)??"supersede"):await P()}finally{let C=D;if(C)C.result().then(H,H);else H()}}finally{if(z&&IJ.get(G)===z)IJ.delete(G)}}async withThread(J,$,Q,Z="supersede"){if(Z==="skip"&&zJ.has(J))return MZ(J);for(;;){let W=await this.underThreadLock(J,$,Q,Z);if(!("waitFor"in W))return W.response;await W.waitFor}}async underThreadLock(J,$,Q,Z){let W=zJ.get(J)??Promise.resolve(),K,X=new Promise((V)=>{K=V}),G=W.then(()=>X);zJ.set(J,G),await W;try{let V=await this.liveRuns.find({threadId:J});if(V&&Z!=="supersede"&&this.liveRuns.isRunning(V.runId)){if(Z==="skip")return{response:MZ(J)};let z=this.liveRuns.get(V.runId),D=z?S$.get(z)??z.result():null;if(D)return{waitFor:D.then(r,r)}}if(V&&this.liveRuns.isRunning(V.runId)&&!this.liveRuns.mayAccess(V.runId,$))return{response:HJ()};let Y=V?this.liveRuns.get(V.runId):null;if(Y)Y.stop({reason:"superseded by a later turn on this thread"}),await S$.get(Y);return{response:await Q()}}finally{if(K(),zJ.get(J)===G)zJ.delete(J)}}async attach(J=new j){let $=await t(J,DJ);if($.error)return c($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:_Z(J,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=Q.emptyMiss===!0;if(!await this.threadInScope(J,Z))return EZ(Z,W);let K=await this.liveRuns.find({threadId:Z});if(K&&!this.liveRuns.mayAccess(K.runId,await this.runOwner(J)))return HJ();if(!K)return EZ(Z,W);let X=typeof Q.runId==="string"?Q.runId:void 0,G=X&&X!==K.runId?void 0:S9(J,Q);try{return qZ(this.liveRuns.replay(K.runId,G))}catch(V){if(V instanceof s)return M(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof YJ)return M(404,{code:V.code,message:V.message});throw V}}async watch(J=new j){let $=await t(J,DJ);if($.error)return c($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:_Z(J,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"watch needs a threadId: it is the thread whose runs are announced."});if(await this.authorizeRequest(J,{route:"attach",threadId:Z}),!await this.threadInScope(J,Z))return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let W=await this.runOwner(J),K=this.liveRuns,X=z9(K),G=await K.find({threadId:Z}),V=null,Y=null,z=0,D=()=>{if(Y?.stop(),!V)return;let P=X.get(Z);if(P?.delete(V),P&&P.size===0)X.delete(Z);V=null},N=new ReadableStream({start(P){Y=wZ(P);let U=(F)=>{if(!K.mayAccess(F,W))return;try{P.enqueue(new TextEncoder().encode(IZ({seq:++z,event:{type:"run-start",runId:F,threadId:Z}}))),Y?.touch()}catch{D()}};V=U;let O=X.get(Z);if(!O)O=new Set,X.set(Z,O);if(O.add(U),G&&K.isRunning(G.runId))U(G.runId)},cancel(){D()}});return J.rawRequest?.signal?.addEventListener("abort",D,{once:!0}),new Response(N,{status:200,headers:fZ()})}async stop(J=new j){let $=await t(J,DJ);if($.error)return c($);let Q=$.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner(J),W=typeof Q.runId==="string"?Q.runId:void 0;if(!W&&typeof Q.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Q.clientRunId)??void 0,!W){let X=IJ.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return HJ();return X.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Q.threadId==="string")W=(await this.liveRuns.find({threadId:Q.threadId}))?.runId;let K=W?this.liveRuns.get(W):null;if(!K)return{stopped:!1};if(!this.liveRuns.mayAccess(K.runId,Z))return HJ();return K.stop({reason:typeof Q.reason==="string"?Q.reason:void 0}),{stopped:!0}}attachmentScope(J,$,Q){let Z=this.hooks?.attachmentScope;if(Z)return Z(J,$,Q);let W=J.ctx()?.user,K=W?.id??W?.publicId;if(K!==void 0&&K!==null&&String(K)!=="")return{key:`user:${String(K)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(J){let $=this.hooks?.attachmentLimits;if($)return $(J);return null}checkUpload(J,$,Q){return this.hooks?.checkUpload?.(J,$,Q)}attachmentDestination(J,$,Q){let Z=this.hooks?.attachmentDestination;if(Z)return Z(J,$,Q);return"both"}async attachmentsFor(J,$,Q={body:{}}){let Z=await this.attachmentScope(J,$,Q);if(!Z)return null;return new yJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new j){let $=this.voice;if(!$)return R$();let Q=await t(J,DJ);if(Q.error)return c(Q);let{sdp:Z,threadId:W,pushToTalk:K}=Q.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return M(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let X=fJ(Q.body,T9),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:G,body:X});let V=J.ctx?.()?.user??null,Y=await $.start({req:J,body:X,threadId:G,user:V,pushToTalk:K===!0}),z=Date.now(),D,N=async(C)=>{if(C!==void 0)console.error("[gemi/ai] a voice session could not start.",C);if(D)await $.realtime.hangup(D).catch((L)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",L)});try{await Y.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:Y.threadId??G??"",reason:"start_failed",startedAt:z,endedAt:Date.now(),durationMs:0,seconds:0,usage:A(),transcription:{usage:A(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(L){console.error("[gemi/ai] a voice session's onEnd threw.",L)}},P=Y.threadId??G;if(!P)return await N(void 0),M(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(P!==G)await this.authorizeRequest(J,{route:"stream",threadId:P,body:X})}catch(C){throw await N(void 0),C}let U=crypto.randomUUID(),O=Y.tools??[];try{if(Y.mcp)O=[...O,...await V$(Y.mcp,{user:V,sessionId:U})]}catch(C){return await N(C),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let F={...Y.session,tools:[...KJ($.delegate),...Y.session?.tools??[],...O.map((C)=>C.tool)],...K===!0?{turnDetection:null}:{}},H;try{H=await $.realtime.createCall({sdp:Z,session:F,safetyIdentifier:Y.safetyIdentifier})}catch(C){await N(C);let L=C instanceof b$&&C.code==="rate_limited";return M(L?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=H.callId;try{await this.voiceStore.create({id:U,callId:H.callId,threadId:P,owner:await this.runOwner(J),body:X,startedAt:z});let{threadId:C,session:L,safetyIdentifier:T,mcp:R,tools:x,...m}=Y;return{sessionId:u.start({...m,tools:O,controller:this.constructor,threadId:P,user:V,body:X,call:{realtime:$.realtime,callId:H.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:F}).sessionId,sdp:H.sdpAnswer,threadId:P,delegate:$.delegate?.name??XJ,endsAt:z+(Y.limits?.maxDurationMs??900000)}}catch(C){return await N(C),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new j){if(!this.voice)return R$();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await t(J,DJ);if(Q.error)return c(Q);let Z=fJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),u.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new j){let $=this.voice;if(!$)return R$();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Q.body}),Q.endedAt!==void 0)return{ended:!1};let Z=u.get(Q.id);if(Z)await Z.end("hangup");else await $.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let $=J.params?.sessionId,Q=typeof $==="string"&&$?await this.voiceStore.get($):null;if(!Q)return M(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return HJ();return Q}async upload(J=new j){let $=await J.rawRequest.formData(),Q=$.get("file");if(!(Q instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=Q instanceof File&&Q.name?Q.name:"upload",W=Q.type||"application/octet-stream",K=N9($.get("body")),X=$.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:K});let G=C9(await this.attachmentLimits(J),Q,Z,W);if(G)throw new j$(G.code,G.message);await this.scopeStore(J,K);let V=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,Y=await this.runOwner(J),z=(R)=>this.fileOwners.record(R,{owner:Y,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString()}),D={body:K,threadId:V},N=await this.checkUpload({name:Z,size:Q.size,mimeType:W},J,D);if(N)throw new j$(N.code||"upload_refused",N.message);let P=await this.attachmentDestination(Q,J,D),U=j9(P,$.get("destination")),O=await this.attachmentScope(J,V,{body:K}),F=U!=="provider"&&!O;if(F){if(U==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');x9()}if(U==="provider"||!O){let R=await OZ(this.agent.provider,Q);await z(R);let x={fileId:R,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(F)x.downgraded="no_scope";return x}let H=uZ(),C=await this.attachmentStorage.put({name:cZ(H,Z),body:Q,contentType:W}),L=U==="both"?await OZ(this.agent.provider,Q):void 0;if(L)await z(L);let T={id:H,scopeKey:O.key,fileId:L,objectName:C,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:U};return await this.attachments.put(O,T),{fileId:L,attachmentId:H,name:Z,mimeType:W,size:Q.size,destination:U}}async foreignFile(J,$){let Q=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of Q){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return E9()}return null}onMessage(J,$){return this.hooks?.onMessage?.(J,$)}onToolCall(J,$){return this.hooks?.onToolCall?.(J,$)}onToolResult(J,$,Q){return this.hooks?.onToolResult?.(J,$,Q)}onAwaitingInput(J,$){return this.hooks?.onAwaitingInput?.(J,$)}redactError(J,$,Q){let Z=this.hooks?.redactError;if(Z)return Z(J,$,Q);return f$(J,$)}onError(J,$){return this.hooks?.onError?.(J,$)}onProviderRetry(J,$){return this.hooks?.onProviderRetry?.(J,$)}onStreamComplete(J,$){return this.hooks?.onStreamComplete?.(J,$)}reportHookFailure(J){let $=this.hooks?.reportHookFailure;if($)try{return $(J)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,$){switch(J.type){case"tool-call":if(!J.part.partial&&!J.resent)await this.onToolCall({toolCallId:J.part.toolCallId,name:String(J.part.name),input:J.part.input},$);return;case"tool-result":{let Q=J.part;await this.onToolResult(Q,$,{toolCallId:Q.toolCallId,name:String(Q.name),input:dZ(Q)});return}case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(vZ(J.error),$);return;default:return}}async readThread(J,$={}){let Z=await($.scope===null||$.scope===void 0?this.store:RZ(this.store,$.scope)).loadThread(J);if(!Z)return null;let{messages:W}=await this.settleThread(J,Z,{write:!1});return W}isRunLive(J,$){return this.liveRuns.get(J)!==null}async settleThread(J,$,{write:Q}){let Z=(V)=>this.isRunLive(V,J),W=await XZ($,Z),K=W.messages,X=[],G=new Map(W.settled.map((V)=>[V.id,V]));if(q9(K)||Q)try{let V=await zZ(K,{threadId:J,store:y.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolNamed(Y)?.outputSchema,modelOutputFor:(Y,z)=>iZ(this.toolNamed(Y),z,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});K=V.messages,X=V.jobs;for(let Y of V.settled)G.set(Y.id,Y);if(Q&&V.orphans.length>0){await DZ(y.store,V.orphans,(z)=>this.reportHookFailure(z));let Y=new Set(V.orphans.map((z)=>z.id));X=X.map((z)=>Y.has(z.id)?{...z,orphaned:!0}:z)}}catch(V){this.reportHookFailure(V)}if(Q&&G.size>0)try{await this.store.appendMessages(J,[...G.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:X}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??UJ}jobsBlock(J){return d$(J,this.jobsBlockMax())}toolNamed(J){let $=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let K=$(W.tools);if(K)return K}else if(W.name===J)return W}return};return $(this.agent.tools??[])}follow(J,$){(async()=>{try{for await(let Q of J.frames())$.frame(Q)}catch(Q){this.reportHookFailure(Q)}})()}persistRun(J,$,Q,Z=null,W={id:null,notified:Promise.resolve()}){let K=Promise.resolve(),X=(async()=>{let V;try{V=await J.result()}catch(z){Z?.close(),await Z?.settled(),K=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:z instanceof Error?z.message:String(z),retryable:!1},$)));return}let Y=V.messages;if(Z?.close(Y),await Z?.settled(),$.threadId&&Y.length>0)try{await this.store.appendMessages($.threadId,Y)}catch(z){this.reportHookFailure(z)}K=this.notifyRun(V,Y,$,W)})(),G=X.then(()=>w9(Promise.all([K,Q]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:G}}async notifyRun(J,$,Q,Z){await Z.notified;for(let W of $){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete(J,Q))}async safely(J){try{await J()}catch($){this.reportHookFailure($)}}}var k$=["turn","clientRunId","threadId","messages","regenerate"],F9=["text","files","toolResults"];function fJ(J,$=aZ(J)?k$:[...k$,...F9]){let Q={};for(let[Z,W]of Object.entries(J)){if($.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function N9(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new T$("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new T$("The upload's `body` field must be a JSON object.");return fJ($,k$)}class T$ extends qJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function OZ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof pZ&&O9.has(Q.status))throw new sZ(o(Q).message);throw Q}}var O9=new Set([400,413,415,422]);class j$ extends qJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function C9(J,$,Q,Z){if(!J)return null;let{maxBytes:W,accept:K}=J;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${CZ($.size)}; the limit is ${CZ(W)}.`};if(K&&K.length>0&&!K.some((X)=>U9(X,Q,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify(Q)} is not a type this chat accepts. Accepted: ${K.join(", ")}.`};return null}function U9(J,$,Q){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return $.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function CZ(J){if(J<1024)return`${J} B`;let $=["KB","MB","GB"],Q=J/1024,Z=0;while(Q>=1024&&Z<$.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${$[Z]}`}class sZ extends qJ{constructor(J){super(J);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(J)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:J}}},view:{}}}}async function t(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!L9(Q.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number(Q.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>$)return UZ($);let W;try{let X=await _9(Q,$);if(X===null)return UZ($);W=X}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let K;try{K=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(K===null||typeof K!=="object"||Array.isArray(K))return{body:{},error:"The request body must be a JSON object."};return{body:K}}function L9(J){return jZ(J)==="application/json"}async function _9(J,$){if(!Number.isFinite($)||!J.body)return await J.text();let Q=J.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:V}=await Q.read();if(G)break;if(W+=V.byteLength,W>$)return await Q.cancel().catch(r),null;Z.push(V)}let K=new Uint8Array(W),X=0;for(let G of Z)K.set(G,X),X+=G.byteLength;return new TextDecoder().decode(K)}function UZ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function x$(J,$,Q){return M(J,{...bJ(TZ(J),Q,J),code:$})}function c(J){if(J.status===413)return x$(413,J.code??"body_too_large",J.error??"");return M(J.status??400,{code:J.code??"invalid_request",message:J.error})}function aZ(J){return Boolean(J.turn)&&typeof J.turn==="object"}function B9(J){let $=aZ(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=M9($.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray($.toolResults))Q.toolResults=$.toolResults;if(Object.keys(Q).length===0)return{};if($===J.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:Z}=$;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>LZ)return{error:`turn.localId is longer than ${LZ} characters.`};Q.localId=Z}return{turn:Q}}var LZ=200;function M9(J){let $=[];for(let[Q,Z]of J.entries()){let W=`turn.files[${Q}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let K={};for(let z of["fileId","attachmentId","name","mimeType"]){let D=Z[z];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${z} must be a string.`;K[z]=D}let{fileId:X,attachmentId:G,name:V,mimeType:Y}=K;if(X?.startsWith(wJ))return`${W}.fileId holds a gemi attachment id (${X}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(G!==void 0&&!G.startsWith(wJ))return`${W}.attachmentId is not a gemi attachment id: it must start with "${wJ}".`;if(!X&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...X?{fileId:X}:{},...G?{attachmentId:G}:{},...V!==void 0?{name:V}:{},...Y!==void 0?{mimeType:Y}:{}})}return $}function S9(J,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let Z=Math.floor($.cursor);if(Z>=0)return Z+1;return}let Q=J?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function _Z(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function A9(J){let $=q$(J);for(let Q=J.length-1;Q>=0;Q--){let Z=J[Q];if(Z.role!=="user"||$.has(Z.id))continue;let W="",K=[];for(let X of Z.content){if(X.type==="text")W+=X.text;if(X.type==="file")K.push({...X.fileId?{fileId:X.fileId}:{},...X.attachmentId?{attachmentId:X.attachmentId}:{},...X.name?{name:X.name}:{},...X.mimeType?{mimeType:X.mimeType}:{}})}if(!W&&K.length===0)continue;return{index:Q,turn:{...W?{text:W}:{},...K.length>0?{files:K}:{}}}}return null}function BZ(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function R9(J){let $=J.event;if(J.text!==void 0||J.turn!==void 0)throw TypeError("AgentController.startTurn takes an `event` or a `text`/`turn`, not both: an event is not a person's message.");if(typeof $!=="object"||$===null||typeof $.name!=="string"||!W9.test($.name))throw TypeError('AgentController.startTurn\'s `event.name` must be letters, digits and `.`, `_`, `:`, `-` (at most 64), like "job-settled".');if($.text!==void 0&&typeof $.text!=="string")throw TypeError("AgentController.startTurn's `event.text` must be a string.");let Q;if($.data!==void 0)try{Q=JSON.parse(JSON.stringify($.data))}catch(Z){throw TypeError(`AgentController.startTurn's \`event.data\` is not JSON: ${String(Z)}`)}return{name:$.name,...$.text?{text:$.text}:{},...Q!==void 0?{data:Q}:{}}}function MZ(J){return M(409,{code:nZ,message:`Thread ${J} has a run going, and this turn was not to interrupt it.`})}function HJ(){return M(403,bJ("permission","This run belongs to someone else.",403))}function E9(){return M(403,bJ("permission","A file in this turn was uploaded by someone else.",403))}function k9(J){if(!Array.isArray(J))return[];let $=[];for(let Q of J){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}var T9=["sdp","threadId","pushToTalk"];function R$(){return M(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function M(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function j9(J,$){if(typeof $!=="string"||$.length===0)return J;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===J||J==="both"&&$==="storage")return $;if(J==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${J}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var SZ=!1;function x9(){if(SZ)return;SZ=!0,console.warn("[gemi/ai] An upload had no attachment scope, so its bytes were sent to the model provider only and no attachment id was minted \u2014 a tool cannot forward this file. Guard the route with auth, send a `threadId` with the upload, or override `attachmentScope()`.")}var I9=2147483647;function w9(J,$){let Q=J.then(()=>{},()=>{});if(!($<=I9))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var AZ=!1;function f9(J){if(AZ||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof I$))return;AZ=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}function q9(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}function RZ(J,$){if(typeof $!=="string"||$==="")throw TypeError("A store scope is a non-empty string.");if(!J.forScope)throw Error("This controller's store cannot be scoped: storeScope() or a turn's `scope` needs a store that implements `forScope` (DatabaseAgentStore or MemoryAgentStore).");return J.forScope($)}function EZ(J,$=!1){if($)return new Response(null,{status:204});return M(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`})}export{l9 as windowMessages,KJ as voiceTools,g9 as turnStarts,z6 as toRealtimeUsage,M8 as toAgentTools,v9 as supportsStrict,u9 as splitTurns,t9 as settleSummaries,y9 as s,f$ as redactError,G6 as parsePartialJson,c9 as messageSize,ZJ as measureUsage,V$ as mcpVoiceTools,F$ as liveRuns,GJ as keepSummary,H6 as isCallNotFound,q$ as injectedMessageIds,tJ as generate,f8 as evalChain,P9 as defineAgentHooks,D$ as defaultVoiceStore,e9 as defaultUsageLimitStore,a9 as defaultSummaryStore,X6 as defaultPromptCacheKey,w$ as defaultNonceStore,N$ as defaultFileOwners,vJ as defaultAttachmentStore,_$ as defaultAgentStore,TJ as VoiceHangup,u as VoiceBridge,h9 as Usage,eJ as ToolNamespace,g as ToolError,$6 as Skill,yJ as ScopedAttachments,Q6 as SKILLS_NAMESPACE,L$ as RedisReceiptStore,bZ as RedisNonceStore,Y6 as RealtimeSideband,b$ as RealtimeRequestError,D6 as RealtimeClient,p$ as Prompt,yZ as PrismaNonceStore,J6 as PendingEscalation,P6 as OpenAIProvider,Z$ as OpenAIImageProvider,z$ as MemoryVoiceSessionStore,r9 as MemoryUsageLimitStore,s9 as MemorySummaryStore,U$ as MemoryReceiptStore,I$ as MemoryNonceStore,jJ as MemoryLiveRuns,xJ as MemoryFileOwners,EJ as MemoryCircuitStore,mZ as MemoryAttachmentStore,VJ as MemoryAgentStore,a$ as MemoryAgentJobStore,PQ as MEMORY_NAMESPACE,YJ as LiveRunNotFoundError,r$ as JobsRequireThreadError,t$ as JobHandle,b9 as JSONSchemaError,gZ as InvalidAttachmentScopeError,GQ as InMemoryAgentMemoryStore,AJ as ImageRequestError,RJ as ImageProvider,J$ as ImageModel,s as FrameCursorEvictedError,WJ as FallbackProvider,DQ as FakeAgentMemoryStore,MJ as Eval,H$ as DatabaseAgentStore,iJ as DatabaseAgentMemoryStore,pJ as DatabaseAgentJobStore,V6 as DEFAULT_TRANSCRIPTION_MODEL,XQ as DEFAULT_MEMORY_MAX_TOKENS,HQ as DEFAULT_MEMORY_LIMITS,i9 as DEFAULT_MAX_SUMMARY_TOKENS,Z6 as DEFAULT_MAX_RUN_DURATION_MS,e$ as DEFAULT_JOB_DEADLINE_MS,UJ as DEFAULT_JOBS_CONTEXT_MAX,XJ as DEFAULT_DELEGATE_NAME,m9 as DEFAULT_CONTEXT_WINDOW_STEP,p9 as DEFAULT_CONTEXT_WINDOW_NOTE,d9 as DEFAULT_COMPACT_TRIGGER_TOKENS,n9 as DEFAULT_COMPACT_INSTRUCTIONS,o9 as COMPACT_SUMMARY_HEADER,F6 as AzureOpenAIProvider,W$ as AzureOpenAIImageProvider,hZ as AttachmentNotFoundError,hJ as AgentTurnError,SJ as AgentTool,W6 as AgentRunError,Y$ as AgentProvider,YQ as AgentMemoryRefusedError,VQ as AgentMemoryConflictError,zQ as AgentMemories,y as AgentJobs,mJ as AgentJobDeadlineSweep,JQ as AgentJob,y$ as AgentController,K6 as Agent};
266
301
 
267
- //# debugId=9AB6D2253A61E79A64756E2164756E21
302
+ //# debugId=CE18E28A9A1E5E5E64756E2164756E21