gemi 0.215.0 → 0.217.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 (258) hide show
  1. package/dist/ai/Agent.d.ts +9 -7
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +91 -7
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/AgentProvider.d.ts +32 -15
  6. package/dist/ai/AgentProvider.d.ts.map +1 -1
  7. package/dist/ai/FallbackProvider.d.ts +8 -6
  8. package/dist/ai/FallbackProvider.d.ts.map +1 -1
  9. package/dist/ai/generate.d.ts.map +1 -1
  10. package/dist/ai/index.d.ts +3 -2
  11. package/dist/ai/index.d.ts.map +1 -1
  12. package/dist/ai/index.js +42 -42
  13. package/dist/ai/index.js.map +5 -5
  14. package/dist/ai/live/harness.d.ts +1 -0
  15. package/dist/ai/live/harness.d.ts.map +1 -1
  16. package/dist/ai/providers/anthropicStream.d.ts.map +1 -1
  17. package/dist/ai/providers/call.d.ts +10 -0
  18. package/dist/ai/providers/call.d.ts.map +1 -1
  19. package/dist/ai/providers/errors.d.ts +15 -7
  20. package/dist/ai/providers/errors.d.ts.map +1 -1
  21. package/dist/ai/providers/fakeProvider.d.ts +3 -0
  22. package/dist/ai/providers/fakeProvider.d.ts.map +1 -1
  23. package/dist/ai/providers/stream.d.ts.map +1 -1
  24. package/dist/ai/redact.d.ts +4 -6
  25. package/dist/ai/redact.d.ts.map +1 -1
  26. package/dist/ai/store/Attachments.d.ts +98 -2
  27. package/dist/ai/store/Attachments.d.ts.map +1 -1
  28. package/dist/ai/store/FileOwners.d.ts +18 -0
  29. package/dist/ai/store/FileOwners.d.ts.map +1 -1
  30. package/dist/ai/store/index.d.ts +1 -1
  31. package/dist/ai/store/index.d.ts.map +1 -1
  32. package/dist/ai/testing/RecordingProvider.d.ts +2 -0
  33. package/dist/ai/testing/RecordingProvider.d.ts.map +1 -1
  34. package/dist/ai/testing/index.js +3 -3
  35. package/dist/ai/testing/index.js.map +3 -3
  36. package/dist/ai/types.d.ts +23 -0
  37. package/dist/ai/types.d.ts.map +1 -1
  38. package/dist/app/index.js +1 -1
  39. package/dist/bin/ai-client/extract.d.ts +6 -4
  40. package/dist/bin/ai-client/extract.d.ts.map +1 -1
  41. package/dist/bin/ai-client/kotlin.d.ts +13 -1
  42. package/dist/bin/ai-client/kotlin.d.ts.map +1 -1
  43. package/dist/bin/ai-client/model.d.ts +4 -3
  44. package/dist/bin/ai-client/model.d.ts.map +1 -1
  45. package/dist/bin/ai-client/swift.d.ts +10 -1
  46. package/dist/bin/ai-client/swift.d.ts.map +1 -1
  47. package/dist/bin/gemi.js +51 -29
  48. package/dist/bin/gemi.js.map +6 -6
  49. package/dist/bin/http-client/extract.d.ts.map +1 -1
  50. package/dist/bin/http-client/model.d.ts +1 -1
  51. package/dist/bin/http-client/model.d.ts.map +1 -1
  52. package/dist/bin/http-client/render.d.ts +5 -0
  53. package/dist/bin/http-client/render.d.ts.map +1 -0
  54. package/dist/bun/plugin.js +1 -1
  55. package/dist/bun/preload.js +1 -1
  56. package/dist/{chunk-y0b22kf8.js → chunk-17agj0r3.js} +2 -2
  57. package/dist/{chunk-y0b22kf8.js.map → chunk-17agj0r3.js.map} +1 -1
  58. package/dist/{chunk-k6532519.js → chunk-1nw9jhpt.js} +2 -2
  59. package/dist/{chunk-k6532519.js.map → chunk-1nw9jhpt.js.map} +1 -1
  60. package/dist/{chunk-153m8mfe.js → chunk-3r7z4kc0.js} +2 -2
  61. package/dist/{chunk-153m8mfe.js.map → chunk-3r7z4kc0.js.map} +1 -1
  62. package/dist/{chunk-2e278yhf.js → chunk-4k3r37be.js} +2 -2
  63. package/dist/{chunk-2e278yhf.js.map → chunk-4k3r37be.js.map} +1 -1
  64. package/dist/{chunk-gk2k76tn.js → chunk-4s72m6zx.js} +3 -3
  65. package/dist/{chunk-gk2k76tn.js.map → chunk-4s72m6zx.js.map} +1 -1
  66. package/dist/{chunk-m4nn6ne9.js → chunk-5gp49wph.js} +2 -2
  67. package/dist/{chunk-c80xrwep.js.map → chunk-5gp49wph.js.map} +1 -1
  68. package/dist/{chunk-qt80d3fw.js → chunk-5vdkqv17.js} +2 -2
  69. package/dist/{chunk-qt80d3fw.js.map → chunk-5vdkqv17.js.map} +1 -1
  70. package/dist/{chunk-2ek8wpe8.js → chunk-5wh3cw2x.js} +3 -3
  71. package/dist/{chunk-2ek8wpe8.js.map → chunk-5wh3cw2x.js.map} +1 -1
  72. package/dist/{chunk-wsp30cr6.js → chunk-6b7z5h54.js} +2 -2
  73. package/dist/{chunk-wsp30cr6.js.map → chunk-6b7z5h54.js.map} +1 -1
  74. package/dist/{chunk-78gy3agg.js → chunk-6ncn8rdn.js} +2 -2
  75. package/dist/{chunk-78gy3agg.js.map → chunk-6ncn8rdn.js.map} +1 -1
  76. package/dist/chunk-7081awrd.js +11 -0
  77. package/dist/{chunk-3ejv7fs4.js.map → chunk-7081awrd.js.map} +6 -6
  78. package/dist/{chunk-ktxf56dm.js → chunk-7t13vyzg.js} +3 -3
  79. package/dist/{chunk-ktxf56dm.js.map → chunk-7t13vyzg.js.map} +1 -1
  80. package/dist/{chunk-hcysexst.js → chunk-7xe5vd4w.js} +2 -2
  81. package/dist/{chunk-hcysexst.js.map → chunk-7xe5vd4w.js.map} +1 -1
  82. package/dist/{chunk-61sevt6g.js → chunk-8524ejgk.js} +2 -2
  83. package/dist/{chunk-61sevt6g.js.map → chunk-8524ejgk.js.map} +1 -1
  84. package/dist/{chunk-10safpz9.js → chunk-94fdjkzf.js} +2 -2
  85. package/dist/{chunk-10safpz9.js.map → chunk-94fdjkzf.js.map} +1 -1
  86. package/dist/{chunk-sw8012bt.js → chunk-9c8e4nkz.js} +2 -2
  87. package/dist/{chunk-sw8012bt.js.map → chunk-9c8e4nkz.js.map} +1 -1
  88. package/dist/{chunk-s7p6w1p2.js → chunk-9pvxexh1.js} +2 -2
  89. package/dist/{chunk-s7p6w1p2.js.map → chunk-9pvxexh1.js.map} +1 -1
  90. package/dist/{chunk-mj857ksa.js → chunk-aes0ecnp.js} +3 -3
  91. package/dist/{chunk-mj857ksa.js.map → chunk-aes0ecnp.js.map} +1 -1
  92. package/dist/{chunk-nc5p41g9.js → chunk-at6zjajz.js} +2 -2
  93. package/dist/{chunk-nc5p41g9.js.map → chunk-at6zjajz.js.map} +1 -1
  94. package/dist/{chunk-2w8j265x.js → chunk-b1btq22a.js} +3 -3
  95. package/dist/{chunk-2w8j265x.js.map → chunk-b1btq22a.js.map} +1 -1
  96. package/dist/{chunk-sqzm1k9q.js → chunk-b1pps9bj.js} +2 -2
  97. package/dist/{chunk-sqzm1k9q.js.map → chunk-b1pps9bj.js.map} +1 -1
  98. package/dist/{chunk-c8sq880v.js → chunk-b8tmmpcf.js} +2 -2
  99. package/dist/{chunk-c8sq880v.js.map → chunk-b8tmmpcf.js.map} +1 -1
  100. package/dist/chunk-bcfwa370.js +5 -0
  101. package/dist/chunk-bcfwa370.js.map +13 -0
  102. package/dist/{chunk-1bsr7vzn.js → chunk-c71g46aw.js} +2 -2
  103. package/dist/{chunk-1bsr7vzn.js.map → chunk-c71g46aw.js.map} +1 -1
  104. package/dist/{chunk-nx86gzt1.js → chunk-cwm5x7rf.js} +2 -2
  105. package/dist/{chunk-nx86gzt1.js.map → chunk-cwm5x7rf.js.map} +1 -1
  106. package/dist/{chunk-ha3d6zhv.js → chunk-d6056zme.js} +2 -2
  107. package/dist/{chunk-ha3d6zhv.js.map → chunk-d6056zme.js.map} +1 -1
  108. package/dist/chunk-d6bgh2nr.js +5 -0
  109. package/dist/{chunk-g4esp7z5.js.map → chunk-d6bgh2nr.js.map} +1 -1
  110. package/dist/{chunk-tejgrqh7.js → chunk-dgna0e7g.js} +2 -2
  111. package/dist/{chunk-tejgrqh7.js.map → chunk-dgna0e7g.js.map} +1 -1
  112. package/dist/{chunk-ge201pk4.js → chunk-ee7xb9qr.js} +1 -1
  113. package/dist/{chunk-d8nxkc90.js → chunk-eh3ktv8k.js} +2 -2
  114. package/dist/{chunk-d8nxkc90.js.map → chunk-eh3ktv8k.js.map} +1 -1
  115. package/dist/{chunk-chy85f3v.js → chunk-fhb00fjx.js} +2 -2
  116. package/dist/{chunk-chy85f3v.js.map → chunk-fhb00fjx.js.map} +1 -1
  117. package/dist/{chunk-dghymwgp.js → chunk-fq7wkefg.js} +2 -2
  118. package/dist/{chunk-dghymwgp.js.map → chunk-fq7wkefg.js.map} +1 -1
  119. package/dist/{chunk-rdzdbd52.js → chunk-g178aect.js} +4 -4
  120. package/dist/{chunk-rdzdbd52.js.map → chunk-g178aect.js.map} +1 -1
  121. package/dist/{chunk-hka2sgqz.js → chunk-gt6eq1p2.js} +3 -3
  122. package/dist/{chunk-hka2sgqz.js.map → chunk-gt6eq1p2.js.map} +1 -1
  123. package/dist/{chunk-3xrmx5c7.js → chunk-gxd1388t.js} +2 -2
  124. package/dist/{chunk-3xrmx5c7.js.map → chunk-gxd1388t.js.map} +1 -1
  125. package/dist/{chunk-3fraz0p0.js → chunk-gxfyd8wr.js} +3 -3
  126. package/dist/{chunk-3fraz0p0.js.map → chunk-gxfyd8wr.js.map} +1 -1
  127. package/dist/{chunk-3vnb6xhz.js → chunk-h6knw9f0.js} +1 -1
  128. package/dist/{chunk-5yfdrbwv.js → chunk-hmtn7996.js} +2 -2
  129. package/dist/{chunk-5yfdrbwv.js.map → chunk-hmtn7996.js.map} +1 -1
  130. package/dist/{chunk-3egn4pfk.js → chunk-jzqywxpj.js} +2 -2
  131. package/dist/{chunk-3egn4pfk.js.map → chunk-jzqywxpj.js.map} +1 -1
  132. package/dist/{chunk-9a3wbbr6.js → chunk-k8nsefzb.js} +2 -2
  133. package/dist/{chunk-9a3wbbr6.js.map → chunk-k8nsefzb.js.map} +1 -1
  134. package/dist/{chunk-wee3yrdn.js → chunk-kggwk7hz.js} +1 -1
  135. package/dist/{chunk-y54kz6h6.js → chunk-m0pfdc1n.js} +3 -3
  136. package/dist/{chunk-y54kz6h6.js.map → chunk-m0pfdc1n.js.map} +1 -1
  137. package/dist/{chunk-ntwmz16f.js → chunk-m68cxnbv.js} +2 -2
  138. package/dist/{chunk-ntwmz16f.js.map → chunk-m68cxnbv.js.map} +1 -1
  139. package/dist/{chunk-768yza4f.js → chunk-ncw3zjxm.js} +2 -2
  140. package/dist/{chunk-768yza4f.js.map → chunk-ncw3zjxm.js.map} +1 -1
  141. package/dist/{chunk-fw7sxgse.js → chunk-nhebjh6n.js} +1 -1
  142. package/dist/{chunk-rqab9hcz.js → chunk-p18nfs9t.js} +2 -2
  143. package/dist/{chunk-rqab9hcz.js.map → chunk-p18nfs9t.js.map} +1 -1
  144. package/dist/{chunk-1a0ehbkm.js → chunk-ppdfwnqw.js} +1 -1
  145. package/dist/{chunk-tvd39jya.js → chunk-prc4bcgp.js} +2 -2
  146. package/dist/{chunk-tvd39jya.js.map → chunk-prc4bcgp.js.map} +1 -1
  147. package/dist/{chunk-zzrmsvqc.js → chunk-q0d45r2j.js} +2 -2
  148. package/dist/{chunk-zzrmsvqc.js.map → chunk-q0d45r2j.js.map} +1 -1
  149. package/dist/{chunk-xh2ejnar.js → chunk-q30f4r5x.js} +2 -2
  150. package/dist/{chunk-xh2ejnar.js.map → chunk-q30f4r5x.js.map} +1 -1
  151. package/dist/{chunk-bvm2w6ha.js → chunk-qa528feb.js} +2 -2
  152. package/dist/{chunk-bvm2w6ha.js.map → chunk-qa528feb.js.map} +1 -1
  153. package/dist/{chunk-5w0kzk4m.js → chunk-qstjm3cb.js} +2 -2
  154. package/dist/{chunk-5w0kzk4m.js.map → chunk-qstjm3cb.js.map} +1 -1
  155. package/dist/{chunk-c46y8hs0.js → chunk-r90djdx6.js} +2 -2
  156. package/dist/{chunk-c46y8hs0.js.map → chunk-r90djdx6.js.map} +1 -1
  157. package/dist/{chunk-jgb3je66.js → chunk-rp2f9mq1.js} +2 -2
  158. package/dist/{chunk-jgb3je66.js.map → chunk-rp2f9mq1.js.map} +1 -1
  159. package/dist/{chunk-t8ghxzva.js → chunk-s7jwsbfd.js} +3 -3
  160. package/dist/{chunk-t8ghxzva.js.map → chunk-s7jwsbfd.js.map} +1 -1
  161. package/dist/{chunk-gg97wgy0.js → chunk-sba3s380.js} +2 -2
  162. package/dist/{chunk-gg97wgy0.js.map → chunk-sba3s380.js.map} +1 -1
  163. package/dist/{chunk-m4wagwhr.js → chunk-snt0523y.js} +2 -2
  164. package/dist/{chunk-m4wagwhr.js.map → chunk-snt0523y.js.map} +1 -1
  165. package/dist/{chunk-5399t8zm.js → chunk-sqqh78tf.js} +2 -2
  166. package/dist/{chunk-5399t8zm.js.map → chunk-sqqh78tf.js.map} +1 -1
  167. package/dist/{chunk-sej6n20p.js → chunk-sxxkkx75.js} +4 -4
  168. package/dist/{chunk-sej6n20p.js.map → chunk-sxxkkx75.js.map} +2 -2
  169. package/dist/{chunk-at5ce580.js → chunk-tsjg2k2h.js} +3 -3
  170. package/dist/chunk-tsjg2k2h.js.map +27 -0
  171. package/dist/{chunk-vz2dt9f3.js → chunk-v0sgcy87.js} +1 -1
  172. package/dist/{chunk-zsk4wvrs.js → chunk-vawqmdh4.js} +2 -2
  173. package/dist/{chunk-zsk4wvrs.js.map → chunk-vawqmdh4.js.map} +1 -1
  174. package/dist/{chunk-7czjphwg.js → chunk-vck02shp.js} +2 -2
  175. package/dist/{chunk-7czjphwg.js.map → chunk-vck02shp.js.map} +1 -1
  176. package/dist/{chunk-4q0pxgv6.js → chunk-vewxnk3g.js} +2 -2
  177. package/dist/{chunk-4q0pxgv6.js.map → chunk-vewxnk3g.js.map} +1 -1
  178. package/dist/{chunk-9xa5kzaq.js → chunk-w3ks9nz7.js} +2 -2
  179. package/dist/{chunk-9xa5kzaq.js.map → chunk-w3ks9nz7.js.map} +1 -1
  180. package/dist/{chunk-11wy7gm1.js → chunk-w85wrer7.js} +2 -2
  181. package/dist/{chunk-11wy7gm1.js.map → chunk-w85wrer7.js.map} +1 -1
  182. package/dist/{chunk-xbxdhmh4.js → chunk-w9sw2kn7.js} +3 -3
  183. package/dist/{chunk-xbxdhmh4.js.map → chunk-w9sw2kn7.js.map} +1 -1
  184. package/dist/{chunk-9yh4sfac.js → chunk-wkmd81k4.js} +3 -3
  185. package/dist/{chunk-9yh4sfac.js.map → chunk-wkmd81k4.js.map} +1 -1
  186. package/dist/{chunk-xdrnzs3t.js → chunk-ww62b10k.js} +2 -2
  187. package/dist/{chunk-xdrnzs3t.js.map → chunk-ww62b10k.js.map} +1 -1
  188. package/dist/{chunk-mcqzgyvf.js → chunk-xb0evp2m.js} +2 -2
  189. package/dist/{chunk-mcqzgyvf.js.map → chunk-xb0evp2m.js.map} +1 -1
  190. package/dist/{chunk-2hcwvkfx.js → chunk-xese0rng.js} +3 -3
  191. package/dist/{chunk-2hcwvkfx.js.map → chunk-xese0rng.js.map} +1 -1
  192. package/dist/{chunk-bjh3ms04.js → chunk-xf3wke41.js} +2 -2
  193. package/dist/{chunk-bjh3ms04.js.map → chunk-xf3wke41.js.map} +1 -1
  194. package/dist/{chunk-0njs5zqz.js → chunk-xn7azkgd.js} +3 -3
  195. package/dist/{chunk-0njs5zqz.js.map → chunk-xn7azkgd.js.map} +1 -1
  196. package/dist/{chunk-2x4x2qnk.js → chunk-xp5mmgfp.js} +2 -2
  197. package/dist/{chunk-2x4x2qnk.js.map → chunk-xp5mmgfp.js.map} +1 -1
  198. package/dist/{chunk-er6rhs42.js → chunk-xyv3y476.js} +3 -3
  199. package/dist/{chunk-er6rhs42.js.map → chunk-xyv3y476.js.map} +1 -1
  200. package/dist/{chunk-c80xrwep.js → chunk-yedb5vvg.js} +2 -2
  201. package/dist/{chunk-m4nn6ne9.js.map → chunk-yedb5vvg.js.map} +1 -1
  202. package/dist/{chunk-2v7stsgt.js → chunk-ykshxc5k.js} +2 -2
  203. package/dist/{chunk-2v7stsgt.js.map → chunk-ykshxc5k.js.map} +1 -1
  204. package/dist/{chunk-cgjdxxwy.js → chunk-yxtfg4wy.js} +2 -2
  205. package/dist/{chunk-cgjdxxwy.js.map → chunk-yxtfg4wy.js.map} +1 -1
  206. package/dist/{chunk-18aw52vs.js → chunk-zy6hj5cc.js} +2 -2
  207. package/dist/{chunk-18aw52vs.js.map → chunk-zy6hj5cc.js.map} +1 -1
  208. package/dist/{chunk-fdbh87nv.js → chunk-zyvmbqcx.js} +3 -3
  209. package/dist/{chunk-fdbh87nv.js.map → chunk-zyvmbqcx.js.map} +1 -1
  210. package/dist/config/index.js +1 -1
  211. package/dist/console/run.js +2 -2
  212. package/dist/console/run.js.map +1 -1
  213. package/dist/container/index.js +2 -2
  214. package/dist/container/index.js.map +1 -1
  215. package/dist/database/index.js +2 -2
  216. package/dist/database/index.js.map +1 -1
  217. package/dist/email/index.js +2 -2
  218. package/dist/email/index.js.map +1 -1
  219. package/dist/facades/index.js +2 -2
  220. package/dist/facades/index.js.map +1 -1
  221. package/dist/foundation/index.js +2 -2
  222. package/dist/foundation/index.js.map +1 -1
  223. package/dist/http/ApiRouter.d.ts +1 -1
  224. package/dist/http/ApiRouter.d.ts.map +1 -1
  225. package/dist/http/index.js +2 -2
  226. package/dist/http/index.js.map +1 -1
  227. package/dist/i18n/dictionaryRuntime.js +2 -2
  228. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  229. package/dist/i18n/index.js +2 -2
  230. package/dist/i18n/index.js.map +1 -1
  231. package/dist/kernel/index.js +2 -2
  232. package/dist/kernel/index.js.map +1 -1
  233. package/dist/orm/index.js +2 -2
  234. package/dist/orm/index.js.map +1 -1
  235. package/dist/probe/index.js +2 -2
  236. package/dist/probe/index.js.map +1 -1
  237. package/dist/server/index.js +2 -2
  238. package/dist/server/index.js.map +1 -1
  239. package/dist/services/index.js +2 -2
  240. package/dist/services/index.js.map +1 -1
  241. package/dist/services/queue/work.js +2 -2
  242. package/dist/services/queue/work.js.map +1 -1
  243. package/dist/stats/route-table.js +1 -1
  244. package/dist/support/index.js +2 -2
  245. package/dist/support/index.js.map +1 -1
  246. package/dist/vitest/index.js +1 -1
  247. package/package.json +1 -1
  248. package/dist/chunk-3ejv7fs4.js +0 -11
  249. package/dist/chunk-at5ce580.js.map +0 -27
  250. package/dist/chunk-g4esp7z5.js +0 -5
  251. package/dist/chunk-y10tys3s.js +0 -5
  252. package/dist/chunk-y10tys3s.js.map +0 -13
  253. /package/dist/{chunk-ge201pk4.js.map → chunk-ee7xb9qr.js.map} +0 -0
  254. /package/dist/{chunk-3vnb6xhz.js.map → chunk-h6knw9f0.js.map} +0 -0
  255. /package/dist/{chunk-wee3yrdn.js.map → chunk-kggwk7hz.js.map} +0 -0
  256. /package/dist/{chunk-fw7sxgse.js.map → chunk-nhebjh6n.js.map} +0 -0
  257. /package/dist/{chunk-1a0ehbkm.js.map → chunk-ppdfwnqw.js.map} +0 -0
  258. /package/dist/{chunk-vz2dt9f3.js.map → chunk-v0sgcy87.js.map} +0 -0
package/dist/ai/index.js CHANGED
@@ -1,24 +1,24 @@
1
1
  // @bun
2
- import{ca as wQ,da as yQ,ea as vQ,fa as z6,ga as D6,ha as H6,ia as y$,ja as P6,ka as F6,la as V$,ma as N6,na as O6,oa as C6,pa as U6}from"../chunk-3ejv7fs4.js";import{$c as a9,Ac as zZ,Bc as JQ,Dc as $Q,Ec as GQ,Fc as WQ,Gc as KQ,Hc as XQ,Ic as YQ,Jc as VQ,Kc as zQ,Lc as DQ,Mc as HQ,Nc as PQ,Oc as FQ,Qc as b$,Rc as u9,Sc as c9,Tc as m9,Uc as p9,Vc as l9,Wc as i9,Xc as d9,Yc as n9,Zc as o9,_c as s9,ad as YJ,bd as t9,cd as iZ,dd as r9,ed as dZ,fd as e9,gd as J6,hd as $6,ic as w$,id as AJ,jc as yZ,jd as J$,kc as vZ,kd as Q6,lc as f$,ld as Z6,md as nZ,nd as W6,od as K6,pc as IQ,pd as X6,qc as RQ,qd as G6,rc as WJ,rd as Y6,sc as g9,sd as V6,tc as f,td as rJ,uc as t$,vc as r$,xc as e$,yc as y,zc as VZ}from"../chunk-at5ce580.js";import{Gd as g,Hd as q$,Kd as hZ,Ld as gZ,Md as uZ,Nd as fJ,Od as cZ,Pd as vJ,Qd as mZ,Rd as pZ,Sd as hJ,Td as lZ,Yd as Y$,Zd as s,xd as gQ,yd as A,zd as k}from"../chunk-y10tys3s.js";import{oe as i$}from"../chunk-hcysexst.js";import"../chunk-9yh4sfac.js";import{Cj as U$,Dj as wZ,Fj as fZ,Gj as qZ,Hj as bZ,Qi as j,oi as TZ,ri as xZ,xj as IZ}from"../chunk-2hcwvkfx.js";import{Ij as jZ,Kj as bJ,Lj as yJ}from"../chunk-d8nxkc90.js";import{Uj as h}from"../chunk-m4wagwhr.js";import{Wj as y9,Xj as v9,Yj as h9}from"../chunk-xdrnzs3t.js";import"../chunk-768yza4f.js";import"../chunk-mcqzgyvf.js";import"../chunk-cgjdxxwy.js";import{$k as n,al as o,pl as BJ}from"../chunk-er6rhs42.js";import"../chunk-bvm2w6ha.js";import"../chunk-5w0kzk4m.js";import{gm as eQ}from"../chunk-mj857ksa.js";import"../chunk-gg97wgy0.js";import"../chunk-zzrmsvqc.js";import{Dm as mJ}from"../chunk-5yfdrbwv.js";import"../chunk-c80xrwep.js";import{existsSync as $8,readdirSync as _6,readFileSync as m$}from"fs";import{isAbsolute as Q8,join as NJ,relative as Z8,sep as W8}from"path";var p$="prompts.json",K8=/\{\{>\s*([\w./-]+)\s*\}\}/g,g$=/\{\{(\w+)\}\}/g,X8=/^[\w-]+(\/[\w-]+)*$/,u$={dir:"app/agents",shared:"prompts"},CJ={},uJ=new Map,OJ;function G8(){if(OJ===void 0){let J=NJ(mJ(),"dist","server",p$);OJ=$8(J)?JSON.parse(m$(J,"utf8")):null}return OJ??null}function Y8(J){return J.replace(/\r?\n$/,"")}function c$(){return CJ.cache??Bun.env.NODE_ENV==="production"}function V8(J,$){if(!X8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??CJ.dir??u$.dir,Z=Q8(Q)?Q:NJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:NJ($.shared??CJ.shared??u$.shared,`${J}.md`);return NJ(Z,W)}function z8(J,$){let Q=V8(J,$),Z=c$()?uJ.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let X=G8()?.[Z8(mJ(),Q).split(W8).join("/")];if(X!==void 0)return X}let K;try{K=Y8(m$(Q,"utf8"))}catch(X){if(X.code==="ENOENT"){let G=W?` or in dist/server/${p$}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw X}if(c$())uJ.set(Q,K);return K}function cJ(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return z8(J,Q).replace(K8,(Z,W)=>cJ(W,[...$,J],Q))}class l${static configure(J){CJ={...J},uJ.clear(),OJ=void 0}static render(J,$={},Q={}){return cJ(J,[],Q).replace(g$,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...cJ(J,[],$).matchAll(g$)].map((Z)=>Z[1]);return[...new Set(Q)]}}class pJ extends i${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await y.sweep({limit:100})===100);}}var LJ=20,D8=300,H8=200;function n$(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 ${UJ(K.createdAt)}`);else if(K.state==="running")X.push(`running since ${UJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${UJ(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${d$(K.error.message,H8)}`:"failed";X.push(`failed at ${UJ(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${d$(JSON.stringify(K.summary),D8)}`);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 UJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function d$(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}var o$=["after_jobs","batch_key","queued","inbox","job_checkpoint"],s$=20;class lJ{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 P8(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return BJ(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`
2
+ import{ca as hQ,da as pQ,ea as mQ,fa as U6,ga as C6,ha as _6,ia as u$,ja as L6,ka as B6,la as H$,ma as M6,na as S6,oa as A6,pa as R6}from"../chunk-7081awrd.js";import{$c as Z6,Ac as OZ,Bc as XQ,Dc as GQ,Ec as PQ,Fc as zQ,Gc as DQ,Hc as HQ,Ic as NQ,Jc as FQ,Kc as OQ,Lc as UQ,Mc as CQ,Nc as _Q,Oc as LQ,Qc as g$,Rc as n9,Sc as o9,Tc as s9,Uc as a9,Vc as t9,Wc as r9,Xc as e9,Yc as J6,Zc as $6,_c as Q6,ad as zJ,bd as W6,cd as tZ,dd as K6,ed as rZ,fd as X6,gd as G6,hd as Y6,ic as y$,id as EJ,jc as pZ,jd as W$,kc as mZ,kd as V6,lc as v$,ld as z6,md as eZ,nd as D6,od as H6,pc as vQ,pd as P6,qc as IQ,qd as N6,rc as XJ,rd as F6,sc as d9,sd as O6,tc as b,td as Q$,uc as ZQ,vc as WQ,xc as KQ,yc as g,zc as FZ}from"../chunk-tsjg2k2h.js";import{Gd as p,Hd as h$,Kd as lZ,Ld as iZ,Md as dZ,Nd as bJ,Od as nZ,Pd as cJ,Qd as yJ,Rd as x$,Sd as oZ,Td as sZ,Ud as pJ,Vd as aZ,_d as t,ae as a,xd as iQ,yd as A,zd as T}from"../chunk-bcfwa370.js";import{re as t$}from"../chunk-7xe5vd4w.js";import"../chunk-wkmd81k4.js";import{Aj as vZ,Fj as B$,Gj as hZ,Ij as gZ,Jj as uZ,Kj as cZ,Ti as I,ri as fZ,ui as yZ}from"../chunk-xese0rng.js";import{Lj as bZ,Nj as gJ,Oj as uJ}from"../chunk-eh3ktv8k.js";import{Xj as c}from"../chunk-snt0523y.js";import{$j as i9,Zj as m9,_j as l9}from"../chunk-ww62b10k.js";import"../chunk-ncw3zjxm.js";import"../chunk-xb0evp2m.js";import"../chunk-yxtfg4wy.js";import{cl as o,dl as s,sl as SJ}from"../chunk-xyv3y476.js";import"../chunk-qa528feb.js";import"../chunk-qstjm3cb.js";import{jm as KZ}from"../chunk-aes0ecnp.js";import"../chunk-sba3s380.js";import"../chunk-q0d45r2j.js";import{Gm as dJ}from"../chunk-hmtn7996.js";import"../chunk-yedb5vvg.js";import{existsSync as Y8,readdirSync as k6,readFileSync as o$}from"fs";import{isAbsolute as V8,join as UJ,relative as z8,sep as D8}from"path";var s$="prompts.json",H8=/\{\{>\s*([\w./-]+)\s*\}\}/g,i$=/\{\{(\w+)\}\}/g,P8=/^[\w-]+(\/[\w-]+)*$/,d$={dir:"app/agents",shared:"prompts"},_J={},lJ=new Map,CJ;function N8(){if(CJ===void 0){let J=UJ(dJ(),"dist","server",s$);CJ=Y8(J)?JSON.parse(o$(J,"utf8")):null}return CJ??null}function F8(J){return J.replace(/\r?\n$/,"")}function n$(){return _J.cache??Bun.env.NODE_ENV==="production"}function O8(J,$){if(!P8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??_J.dir??d$.dir,Z=V8(Q)?Q:UJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:UJ($.shared??_J.shared??d$.shared,`${J}.md`);return UJ(Z,W)}function U8(J,$){let Q=O8(J,$),Z=n$()?lJ.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let X=N8()?.[z8(dJ(),Q).split(D8).join("/")];if(X!==void 0)return X}let K;try{K=F8(o$(Q,"utf8"))}catch(X){if(X.code==="ENOENT"){let G=W?` or in dist/server/${s$}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw X}if(n$())lJ.set(Q,K);return K}function iJ(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return U8(J,Q).replace(H8,(Z,W)=>iJ(W,[...$,J],Q))}class a${static configure(J){_J={...J},lJ.clear(),CJ=void 0}static render(J,$={},Q={}){return iJ(J,[],Q).replace(i$,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...iJ(J,[],$).matchAll(i$)].map((Z)=>Z[1]);return[...new Set(Q)]}}class nJ extends t${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await g.sweep({limit:100})===100);}}var BJ=20,C8=300,_8=200;function e$(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)=>!b(K.state)).sort(Q),...J.filter((K)=>b(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 ${LJ(K.createdAt)}`);else if(K.state==="running")X.push(`running since ${LJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${LJ(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${r$(K.error.message,_8)}`:"failed";X.push(`failed at ${LJ(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${r$(JSON.stringify(K.summary),C8)}`);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 LJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function r$(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}var JQ=["after_jobs","batch_key","queued","inbox","job_checkpoint"],$Q=20;class oJ{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 L8(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return SJ(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
4
  INSERT INTO ${this.name(Q)}
5
5
  (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
6
6
  orphaned, attachment_scope, created_at, updated_at, deadline_at,
7
7
  after_jobs, batch_key, queued)
8
8
  VALUES
9
9
  (${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
10
- ${J.owner}, ${J.job}, ${q(J.summary)}, ${W}, 0, ${J.attachmentScope},
10
+ ${J.owner}, ${J.job}, ${y(J.summary)}, ${W}, 0, ${J.attachmentScope},
11
11
  ${Z}, ${Z}, ${Z} + ${this.ms(Q,J.deadlineMs)},
12
- ${q(J.after)}, ${J.batch??null}, ${q(J.queued)})
12
+ ${y(J.after)}, ${J.batch??null}, ${y(J.queued)})
13
13
  `;else await Q`
14
14
  INSERT INTO ${this.name(Q)}
15
15
  (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
16
16
  orphaned, attachment_scope, created_at, updated_at, deadline_at)
17
17
  VALUES
18
18
  (${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
19
- ${J.owner}, ${J.job}, ${q(J.summary)}, ${W}, 0, ${J.attachmentScope},
19
+ ${J.owner}, ${J.job}, ${y(J.summary)}, ${W}, 0, ${J.attachmentScope},
20
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]?d(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 (${a$(Q,$.states)})`;return($.limit===void 0?await Q`
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]?n(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 (${QQ(Q,$.states)})`;return($.limit===void 0?await Q`
22
22
  SELECT * FROM ${this.name(Q)}
23
23
  WHERE thread_id = ${J} AND ${Z}
24
24
  ORDER BY created_at DESC, id DESC
@@ -27,36 +27,36 @@ import{ca as wQ,da as yQ,ea as vQ,fa as z6,ga as D6,ha as H6,ia as y$,ja as P6,k
27
27
  WHERE thread_id = ${J} AND ${Z}
28
28
  ORDER BY created_at DESC, id DESC
29
29
  LIMIT ${Math.max(0,Math.floor($.limit))}
30
- `).map(d)}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`
30
+ `).map(n)}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 = ${y(Q.checkpoint)}`);if(Q.state!==void 0)K.push(Z`state = ${Q.state}`);if("output"in Q)K.push(Z`output = ${y(Q.output)}`);if("error"in Q)K.push(Z`error = ${y(Q.error)}`);if("usage"in Q)K.push(Z`${this.column(Z,"usage")} = ${y(Q.usage)}`);if("orphaned"in Q)K.push(Z`orphaned = ${Q.orphaned?1:0}`);if(Q.state!==void 0&&b(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`
31
31
  UPDATE ${this.name(Z)} SET ${X}
32
- WHERE id = ${J} AND state IN (${a$(Z,$)})
33
- `;return _J(G)>0}async overdue(J,$){let Q=this.q();return(await Q`
32
+ WHERE id = ${J} AND state IN (${QQ(Z,$)})
33
+ `;return MJ(G)>0}async overdue(J,$){let Q=this.q();return(await Q`
34
34
  SELECT * FROM ${this.name(Q)}
35
35
  WHERE state = 'running' AND deadline_at <= ${this.ms(Q,J)}
36
36
  ORDER BY deadline_at, id
37
37
  LIMIT ${Math.max(0,Math.floor($))}
38
- `).map(d)}async waitingOn(J){if(!await this.columns())return[];let $=this.q();return(await $`
38
+ `).map(n)}async waitingOn(J){if(!await this.columns())return[];let $=this.q();return(await $`
39
39
  SELECT * FROM ${this.name($)}
40
40
  WHERE state = 'waiting' AND after_jobs LIKE ${`%${JSON.stringify(J)}%`}
41
41
  ORDER BY created_at, id
42
- `).map(d).filter((Z)=>Z.after?.includes(J))}async waiting(J){let $=this.q();return(await $`
42
+ `).map(n).filter((Z)=>Z.after?.includes(J))}async waiting(J){let $=this.q();return(await $`
43
43
  SELECT * FROM ${this.name($)}
44
44
  WHERE state = 'waiting'
45
45
  ORDER BY created_at, id
46
46
  LIMIT ${Math.max(0,Math.floor(J))}
47
- `).map(d)}async listBatch(J){if(!await this.columns())return[];let $=this.q();return(await $`
47
+ `).map(n)}async listBatch(J){if(!await this.columns())return[];let $=this.q();return(await $`
48
48
  SELECT * FROM ${this.name($)} WHERE batch_key = ${J} ORDER BY created_at, id
49
- `).map(d)}async appendInbox(J,$){await this.requireLaterColumns("`AgentJobs.message`");for(let Q=0;Q<s$;Q++){let Z=this.q(),[W]=await Z`
49
+ `).map(n)}async appendInbox(J,$){await this.requireLaterColumns("`AgentJobs.message`");for(let Q=0;Q<$Q;Q++){let Z=this.q(),[W]=await Z`
50
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`
51
+ `;if(!W||b(String(W.state)))return!1;let K=W.inbox===null||W.inbox===void 0?null:String(W.inbox),X=JSON.stringify([...w(K)??[],$]),G=await Z`
52
52
  UPDATE ${this.name(Z)} SET inbox = ${X}, updated_at = ${this.clock(Z)}
53
53
  WHERE id = ${J} AND state IN ('waiting', 'running') AND ${this.sameInbox(Z,K)}
54
- `;if(_J(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;$<s$;$++){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`
54
+ `;if(MJ(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;$<$Q;$++){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
55
  UPDATE ${this.name(Q)} SET inbox = NULL WHERE id = ${J} AND ${this.sameInbox(Q,W)}
56
- `;if(_J(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 $`
56
+ `;if(MJ(K)>0)return w(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 $`
57
57
  DELETE FROM ${this.name($)}
58
58
  WHERE state IN ('ok', 'error') AND settled_at <= ${this.clock($)} - ${this.ms($,J)}
59
- `;return _J(Q)}columns(){return this.later??=(async()=>{try{return await this.sql.unsafe(`SELECT ${o$.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 ${o$.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=n();if(J===void 0||o()!==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 a$(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 d(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 _J(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 \`${$}\` (
59
+ `;return MJ(Q)}columns(){return this.later??=(async()=>{try{return await this.sql.unsafe(`SELECT ${JQ.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 ${JQ.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=o();if(J===void 0||s()!==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 QQ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function y(J){return J===void 0?null:JSON.stringify(J)}function w(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function n(J){let $=w(J.summary),Q=w(J.output),Z=w(J.error),W=w(J.usage),K=w(J.after_jobs),X=w(J.queued),G=w(J.inbox),V=w(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 MJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function L8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
60
60
  \`id\` VARCHAR(191) NOT NULL,
61
61
  \`thread_id\` VARCHAR(191) NOT NULL,
62
62
  \`run_id\` VARCHAR(191) NOT NULL,
@@ -110,9 +110,9 @@ import{ca as wQ,da as yQ,ea as vQ,fa as z6,ga as D6,ha as H6,ia as y$,ja as P6,k
110
110
  "queued" TEXT,
111
111
  "inbox" TEXT,
112
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 QQ=4;class dJ{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 F8(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 (${$J(Q,J)})`];if($.kinds!==void 0)Z.push(Q`kind IN (${$J(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`
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 YQ=4;class aJ{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 B8(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 (${ZJ(Q,J)})`];if($.kinds!==void 0)Z.push(Q`kind IN (${ZJ(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`
114
114
  SELECT created_at, id FROM ${this.name(Q)}
115
- WHERE id = ${$.after} AND scope IN (${$J(Q,J)})
115
+ WHERE id = ${$.after} AND scope IN (${ZJ(Q,J)})
116
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`
117
117
  SELECT * FROM ${this.name(Q)} WHERE ${W}
118
118
  ORDER BY created_at, id
@@ -120,16 +120,16 @@ import{ca as wQ,da as yQ,ea as vQ,fa as z6,ga as D6,ha as H6,ia as y$,ja as P6,k
120
120
  SELECT * FROM ${this.name(Q)} WHERE ${W}
121
121
  ORDER BY created_at, id
122
122
  LIMIT ${K}
123
- `).map(iJ);if($.tags!==void 0){if(G=G.filter((V)=>KQ(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]?iJ(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(XQ(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>=QQ||!await this.atKey(J.scope,$))throw W}if(Q>=QQ)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`
123
+ `).map(sJ);if($.tags!==void 0){if(G=G.filter((V)=>DQ(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]?sJ(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(HQ(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>=YQ||!await this.atKey(J.scope,$))throw W}if(Q>=YQ)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`
124
124
  UPDATE ${this.name(Z)} SET ${K}
125
125
  WHERE id = ${J} AND version = ${Math.floor(Q)}
126
- `;if(MJ(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 (${$J($,[...new Set(J)])})`;return MJ(Q)}async deleteScope(J){let $=this.q();return MJ(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 WQ(Z,$,Q.limit)}async count(J){let $=this.q(),[Q]=await $`
126
+ `;if(AJ(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 (${ZJ($,[...new Set(J)])})`;return AJ(Q)}async deleteScope(J){let $=this.q();return AJ(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 $`
127
127
  SELECT COUNT(*) AS total FROM ${this.name($)}
128
128
  WHERE scope = ${J} AND (expires_at IS NULL OR expires_at > ${this.clock($)})
129
129
  `;return Number(Q?.total??0)}async touch(J,$){if(J.length===0)return;let Q=this.q();await Q`
130
130
  UPDATE ${this.name(Q)} SET last_used_at = ${this.ms(Q,$)}
131
- WHERE id IN (${$J(Q,[...new Set(J)])})
132
- `}async prune(J){let $=this.q();return MJ(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 (${ZJ(Q,[...new Set(J)])})
132
+ `}async prune(J){let $=this.q();return AJ(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`
133
133
  INSERT INTO ${this.name(Q)}
134
134
  (id, scope, kind, ${this.column(Q,"key")}, content, tags, pinned, source, version,
135
135
  created_at, updated_at, expires_at)
@@ -140,7 +140,7 @@ import{ca as wQ,da as yQ,ea as vQ,fa as z6,ga as D6,ha as H6,ia as y$,ja as P6,k
140
140
  ${W===null?null:this.ms(Q,W)})
141
141
  `}async atKey(J,$){let Q=this.q(),Z=await Q`
142
142
  SELECT * FROM ${this.name(Q)} WHERE scope = ${J} AND ${this.column(Q,"key")} = ${$}
143
- `;return Z[0]?iJ(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=n();if(J===void 0||o()!==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 $J(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function ZQ(J,$){if(J===null||J===void 0||J==="")return $;try{return JSON.parse(String(J))}catch{return $}}function iJ(J){let $=ZQ(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:ZQ(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 MJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function F8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
143
+ `;return Z[0]?sJ(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=o();if(J===void 0||s()!==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 ZJ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function VQ(J,$){if(J===null||J===void 0||J==="")return $;try{return JSON.parse(String(J))}catch{return $}}function sJ(J){let $=VQ(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:VQ(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 AJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function B8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
144
144
  \`id\` VARCHAR(191) NOT NULL,
145
145
  \`scope\` VARCHAR(191) NOT NULL,
146
146
  \`kind\` VARCHAR(191) NOT NULL,
@@ -177,8 +177,8 @@ import{ca as wQ,da as yQ,ea as vQ,fa as z6,ga as D6,ha as H6,ia as y$,ja as P6,k
177
177
  "updated_at" BIGINT NOT NULL,
178
178
  "last_used_at" BIGINT,
179
179
  "expires_at" BIGINT${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 OQ={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 NQ(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 N8(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*NQ($,Q,J)/$:1-Z*NQ(Q,$,1-J)/Q}function nJ(J,$){return N8($/($+J*J),$/2,0.5)}function O8(J){if(!(J>0))return Number.POSITIVE_INFINITY;let $=1.959964,Q=2;while(nJ(Q,J)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=($+Q)/2;if(nJ(W,J)>0.05)$=W;else Q=W}return($+Q)/2}function C8(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 CQ(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 oJ(J){let $=J.length;if($===0)return OQ;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:CQ(Q,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function sJ(J){let $=J.length;if($===0)return OQ;let Q=J.reduce((K,X)=>K+X,0)/$,Z=CQ(J,Q);if($<2||Z===0)return{n:$,mean:Q,stddev:Z,low:null,high:null};let W=O8($-1)*Z/Math.sqrt($);return{n:$,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function QJ(J,$,Q){return{before:J.mean,after:$.mean,delta:$.mean-J.mean,p:Q,pAdjusted:Q,significant:!1}}function UQ(J,$){if(J.n===0||$.n===0)return QJ(J,$,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return QJ(J,$,C8(Q(J),J.n,Q($),$.n))}function LQ(J,$){if(J.n<2||$.n<2)return QJ(J,$,null);let Q=J.stddev**2/J.n,Z=$.stddev**2/$.n,W=Math.sqrt(Q+Z);if(W===0)return QJ(J,$,null);let K=(Q+Z)**2/(Q**2/(J.n-1)+Z**2/($.n-1));return QJ(J,$,nJ(($.mean-J.mean)/W,K))}function _Q(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 SJ{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:($)=>SJ.judge($)}):J.graders,this.pricing=J.pricing}static create(J){let $=`The eval "${J.name}"`;ZJ(J.runs,$,"runs"),ZJ(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 SJ(J);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")ZJ(K.samples,`${$}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,$,Q={}){return EQ(J,$,Q)}static format(J,$={}){return B8(J,$)}async run(J={}){let $=`${this.name}.run`;ZJ(J.runs,$,"runs"),ZJ(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 WJ(async()=>{try{K=await this.task(J.input,{case:J,run:$,signal:Q})}catch(U){X=TQ(U)}}),V={},Y=!1,z=await WJ(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 BQ(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?aJ(this.pricing,G.byModel).cost+aJ(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:kQ(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:G.usage,byModel:L8(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 WJ(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 BQ(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]={...MQ(P),graders:SQ(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?aJ(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:SQ(J,X),calibration:$,totals:{...MQ(J),usage:V,judgeUsage:Y,byModel:z,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(z)}}}}async function BQ(J,$,Q,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return tJ(await J($,Q),W);if(J.kind!=="judge")return tJ(await J.check($,Q),W);return await U8(J,$,Q,W,Z)}catch(K){return{pass:!1,score:0,error:TQ(K)}}}async function U8(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 rJ({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=tJ(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:kQ(G.map((D)=>D.score)),...Y.length>0?{note:Y.join(" | ")}:{},...z.length===G.length?{error:z.join(" | ")}:{}}}function tJ(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=AQ(J);return{pass:Q>=$,score:Q}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:AQ(J.score),...J.note!==void 0?{note:J.note}:{}}}function MQ(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:oJ($.map((Q)=>Q.pass)),score:sJ($.map((Q)=>Q.score))}}function SQ(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:oJ(X.map((G)=>G.pass)),score:sJ(X.map((G)=>G.score))}]}))}function aJ(J,$){let Q=0,Z=[];for(let[W,K]of Object.entries($)){let X=RQ(J,W,K);if(X===void 0){Z.push(W);continue}Q+=X}return{cost:Q,unpriced:Z}}function L8(...J){let $={};for(let Q of J)for(let[Z,W]of Object.entries(Q))$[Z]=k($[Z]??A(),W);return $}function EQ(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:UQ(H.passRate,C.passRate),score:LQ(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]);_Q(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 = ${_8(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 _8(J){return J<0.001?"<0.001":J.toFixed(3)}function B8(J,$){let Q=$.baseline&&!$.baseline.aborted&&!J.aborted?EQ($.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 kQ(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function AQ(J){return Math.min(1,Math.max(0,J))}function TQ(J){return J instanceof Error?J.message:String(J)}function ZJ(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 M8=/^[A-Za-z0-9_-]{1,64}$/;function S8(J,$){let Q=A8($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((z)=>eJ(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(!M8.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(eJ(J,z,Z));else G.get(D).push(eJ(J,z,!1))}let Y=[];for(let[z,D]of K){let N=G.get(z);if(N.length===0)continue;Y.push(J$.create({name:z,description:D.description,tools:N,deferred:D.deferred??Z}))}return[...Y,...V]}function A8(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function eJ(J,$,Q){if($.kind==="tool")return R8(J,$,Q);return AJ.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 R8(J,$,Q){let Z=J.nativeTool($.name);return AJ.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 E8(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 jQ(J,$){if(J.size!==void 0)try{E8(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 xQ(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 $${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;jQ(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new $$(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)=>xQ(Q,`image-${Z}`)),...J.mask?{mask:xQ(J.mask,"mask")}:{},signal:J.signal}))}present(J){return IQ(this.provider.model,J.usage),k8(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 jQ($,`ImageModel "${this.name}"`),$}}function k8(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}var Q$=300000;function Z$(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 RJ 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 T8={png:"image/png",jpeg:"image/jpeg"};function j8(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 x8(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function I8(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new RJ({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:x8(Q),mimeType:T8[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:j8(J.usage)}}async function fQ(J,$,Q,Z){let W;try{W=await wQ(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 RJ(s(K),{cause:K})}return I8(await W.json())}async function qQ(J,$,Q={}){return await fQ(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function bQ(J,$,Q={}){return await fQ(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class EJ{static models(){return[]}modelName(){return this.model}async generate(J){return await qQ(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 bQ(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 s(J)}}var hQ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class W$ extends EJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new W$(J,$)}static models(){return hQ}endpoint(){return Z$(yQ(this.config,{timeoutMs:Q$}))}}class K$ extends EJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new K$(J,$)}static models(){return hQ}modelName(){return this.config.deployment??this.model}endpoint(){return Z$(vQ(this.config,{timeoutMs:Q$}))}}class kJ{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 uQ=Symbol("timed-out");class KJ extends V${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=X$(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 kJ;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=w8(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new KJ(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 KJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new KJ([$],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(_)=>{if(V)return;V=!0,await this.record(W,K,_)},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=(_)=>{let E=$?k(k(A(),$),_.usage):_.usage;return $=void 0,{..._,usage:E}};try{L=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:z.signal})[Symbol.asyncIterator]();let _=K.timeoutMs!==void 0?Date.now()+K.timeoutMs:void 0;for(;;){let E=!P&&_!==void 0?await f8(L.next(),Math.max(0,_-Date.now())):await L.next();if(E===uQ){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 B=E.value;if(B.type==="finish"&&B.model)F=B.model;if(B.type==="retry"){yield B;continue}if(P){if(B.type==="finish")O=k(O??A(),B.usage),U=!0,yield R(B);else{if(B.type==="error")H={error:B.error};yield B}continue}if(gQ(B)){P=!0,await Y("success"),yield*N.splice(0),yield B;continue}if(B.type==="error")H={error:B.error,...B.status!==void 0?{status:B.status}:{},...B.requestId!==void 0?{requestId:B.requestId}:{}};else if(B.type==="finish"){if(O=k(O??A(),B.usage),B.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(B)}}catch(_){let E=K.provider.normalizeError(_);if(P){if(E.code!=="aborted")yield{type:"error",error:E,...Y$(_)};this.report({index:W,model:G,responseModel:F,attempt:Z,usage:O,outcome:G$(E),error:E}),yield R({type:"finish",reason:E.code==="aborted"?"aborted":"error",usage:A(),...F?{model:F}:{}});return}H={error:E,...Y$(_)}}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?G$(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 _ of N)yield _.type==="finish"?R(_):_;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":G$(H.error),error:H.error}),x){if(O)$=k($??A(),O);continue}let m=!1,p;for(let _ of N){if(_.type==="finish"){p=_;continue}if(_.type==="error")m=!0;yield _}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(X$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=X$($),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 X$(J){return J.circuitKey??J.provider.model}function G$(J){return J.code==="aborted"?"aborted":"failed"}function w8(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch),supportsForcedToolChoice:J.every(($)=>$.supportsForcedToolChoice!==!1)}}function f8(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(uQ),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function q8(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 jJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var GJ="ask_agent",b8={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},y8={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 XJ(J={}){return[{name:J.name??GJ,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 TJ=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 TJ.get(J)}static async endAll(J){await Promise.all([...TJ.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={...b8,...cQ(J.limits)},this.lines={...y8,...cQ(J.lines)},this.delegateName=J.delegate?.name??GJ;let $=new Set(XJ(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),TJ.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=v8(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)=>h8(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 jJ){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??g8();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 jJ)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([...XJ(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};TJ.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 cQ(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function v8(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function h8(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 g8(){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 mQ="http://gemi.internal/__gemi__/voice/mcp";async function z$(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(pQ()),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=pQ();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 pQ(){return new j(new Request(mQ,{method:"POST"}),{},"api",new URL(mQ).pathname)}class D${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 H$=new D$;var lQ=new WeakMap,iQ=100;class P${threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(J,$={}){this.threadsTable=dQ($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=dQ($.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 P$({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return $.scope=J,$}async createTable(){let J=m8(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($);await this.addScopeColumns()}async addScopeColumns(){let J=p8(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 MQ={n:0,mean:0,stddev:0,low:null,high:null};function u(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))-u(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 BQ(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 M8(J,$,Q){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(u($+Q)-u($)-u(Q)+$*Math.log(J)+Q*Math.log(1-J));return J<($+1)/($+Q+2)?Z*BQ($,Q,J)/$:1-Z*BQ(Q,$,1-J)/Q}function tJ(J,$){return M8($/($+J*J),$/2,0.5)}function S8(J){if(!(J>0))return Number.POSITIVE_INFINITY;let $=1.959964,Q=2;while(tJ(Q,J)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=($+Q)/2;if(tJ(W,J)>0.05)$=W;else Q=W}return($+Q)/2}function A8(J,$,Q,Z){let W=J+Q,K=$+Z,X=(z,D)=>u(z+1)-u(D+1)-u(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 SQ(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 rJ(J){let $=J.length;if($===0)return MQ;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:SQ(Q,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function eJ(J){let $=J.length;if($===0)return MQ;let Q=J.reduce((K,X)=>K+X,0)/$,Z=SQ(J,Q);if($<2||Z===0)return{n:$,mean:Q,stddev:Z,low:null,high:null};let W=S8($-1)*Z/Math.sqrt($);return{n:$,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function WJ(J,$,Q){return{before:J.mean,after:$.mean,delta:$.mean-J.mean,p:Q,pAdjusted:Q,significant:!1}}function AQ(J,$){if(J.n===0||$.n===0)return WJ(J,$,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return WJ(J,$,A8(Q(J),J.n,Q($),$.n))}function RQ(J,$){if(J.n<2||$.n<2)return WJ(J,$,null);let Q=J.stddev**2/J.n,Z=$.stddev**2/$.n,W=Math.sqrt(Q+Z);if(W===0)return WJ(J,$,null);let K=(Q+Z)**2/(Q**2/(J.n-1)+Z**2/($.n-1));return WJ(J,$,tJ(($.mean-J.mean)/W,K))}function EQ(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 RJ{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:($)=>RJ.judge($)}):J.graders,this.pricing=J.pricing}static create(J){let $=`The eval "${J.name}"`;KJ(J.runs,$,"runs"),KJ(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 RJ(J);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")KJ(K.samples,`${$}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,$,Q={}){return wQ(J,$,Q)}static format(J,$={}){return T8(J,$)}async run(J={}){let $=`${this.name}.run`;KJ(J.runs,$,"runs"),KJ(J.concurrency,$,"concurrency");let Q=J.only?new Set(J.only):null;if(Q){let P=[...Q].filter((F)=>!this.cases.some((U)=>U.id===F));if(P.length>0)throw Error(`The eval "${this.name}" has no case ${P.map((F)=>`"${F}"`).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((P)=>!Q||Q.has(P.id)),V={};for(let[P,F]of Object.entries(this.graders)){if(X.aborted)break;if(typeof F==="function"||F.kind!=="judge"||!F.calibration)continue;V[P]=await this.calibrate(F,X)}let Y=G.flatMap((P)=>Array.from({length:Z},(F,U)=>({test:P,run:U+1}))),z=Array.from({length:Y.length}),D=0,N,H=async()=>{while(D<Y.length&&!X.aborted){let P=D++,F=Y[P],U=await this.sample(F.test,F.run,X,J.keepOutputs??!1);z[P]=U;try{J.onSample?.(U)}catch(_){N??={error:_},K.abort(_)}}},C=Math.min(J.concurrency??this.concurrency,Y.length);if(await Promise.all(Array.from({length:C},H)),N)throw N.error;let O=z.filter((P)=>P!==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((P)=>P.id)})}async sample(J,$,Q,Z){let W=Date.now(),K,X,G=await XJ(async()=>{try{K=await this.task(J.input,{case:J,run:$,signal:Q})}catch(C){X=fQ(C)}}),V={},Y=!1,z=await XJ(async()=>{if(X!==void 0)return;let C={case:J,input:J.input,run:$};for(let[O,P]of Object.entries(this.graders)){if(J.skip?.includes(O))continue;let F=await kQ(P,K,C,Q);if(!F)continue;if(V[O]=F,!F.pass&&typeof P!=="function"&&P.gate)Y=!0}}),D=Object.values(V).map((C)=>C.score),N=X===void 0&&D.length===0,H=this.pricing?J$(this.pricing,G.byModel).cost+J$(this.pricing,z.byModel).cost:void 0;return{case:J.id,run:$,pass:X===void 0&&!N&&Object.values(V).every((C)=>C.pass),excluded:Y||N,...N?{ungraded:!0}:{},score:X!==void 0||N?0:qQ(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:G.usage,byModel:E8(G.byModel,z.byModel),judgeUsage:z.usage,...H!==void 0?{cost:H}:{},durationMs:Date.now()-W}}async calibrate(J,$){let Q=J.calibration,Z=[],W=0,K=await XJ(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 kQ(J,Y.output,D,$),H=N?.pass??!1;if(H===Y.expected)W++;else Z.push({id:z,expected:Y.expected,got:H,...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 H=J.filter((C)=>C.case===N.id);if(H.length===0)continue;G[N.id]={...TQ(H),graders:jQ(H,X)}}let V=A(),Y=A(),z={};for(let N of J){V=T(V,N.usage),Y=T(Y,N.judgeUsage);for(let[H,C]of Object.entries(N.byModel))z[H]=T(z[H]??A(),C)}let D=this.pricing?J$(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:jQ(J,X),calibration:$,totals:{...TQ(J),usage:V,judgeUsage:Y,byModel:z,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(z)}}}}async function kQ(J,$,Q,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return $$(await J($,Q),W);if(J.kind!=="judge")return $$(await J.check($,Q),W);return await R8(J,$,Q,W,Z)}catch(K){return{pass:!1,score:0,error:fQ(K)}}}async function R8(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 Q$({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 H=$$(J.verdict(N.output,Q),Z);if(H)G.push(H)}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:qQ(G.map((D)=>D.score)),...Y.length>0?{note:Y.join(" | ")}:{},...z.length===G.length?{error:z.join(" | ")}:{}}}function $$(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=xQ(J);return{pass:Q>=$,score:Q}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:xQ(J.score),...J.note!==void 0?{note:J.note}:{}}}function TQ(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:rJ($.map((Q)=>Q.pass)),score:eJ($.map((Q)=>Q.score))}}function jQ(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:rJ(X.map((G)=>G.pass)),score:eJ(X.map((G)=>G.score))}]}))}function J$(J,$){let Q=0,Z=[];for(let[W,K]of Object.entries($)){let X=IQ(J,W,K);if(X===void 0){Z.push(W);continue}Q+=X}return{cost:Q,unpriced:Z}}function E8(...J){let $={};for(let Q of J)for(let[Z,W]of Object.entries(Q))$[Z]=T($[Z]??A(),W);return $}function wQ(J,$,Q){for(let[P,F]of[["baseline",J],["current report",$]])if(F.aborted)throw Error(`Eval.compare: the ${P} for "${F.name}" was aborted (${F.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,F,U)=>{let _={label:P,passRate:AQ(F.passRate,U.passRate),score:RQ(F.score,U.score)};return K.push(_),{passRate:_.passRate,score:_.score}},G=(P,F,U)=>Object.fromEntries(Object.keys(U).filter((_)=>(_ in F)).map((_)=>[_,X(`${P} ${_}`,F[_],U[_])])),V=(P,F)=>({fromCurrent:P.filter((U)=>!F.includes(U)),fromBaseline:F.filter((U)=>!P.includes(U))}),Y=X("total",J.totals,$.totals),z=G("case",J.cases,$.cases),D=G("grader",J.graders,$.graders),N=K.flatMap((P)=>[P.passRate,P.score]);EQ(N,Z,W);let H={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))},C=[...H.cases.fromCurrent.map((P)=>`case ${P}: in the baseline, missing from this report`),...H.graders.fromCurrent.map((P)=>`grader ${P}: in the baseline, missing from this report`)],O=[];for(let P of K)for(let[F,U]of[["pass rate",P.passRate],["score",P.score]]){if(!U.significant)continue;let _=`${P.label}: ${F} ${U.before.toFixed(2)} \u2192 ${U.after.toFixed(2)} (p = ${k8(U.pAdjusted)})`;(U.delta<0?C:O).push(_)}return{totals:Y,cases:z,graders:D,missing:H,comparisons:N.filter((P)=>P.p!==null).length,alpha:Z,adjust:W,regressions:C,improvements:O}}function k8(J){return J<0.001?"<0.001":J.toFixed(3)}function T8(J,$){let Q=$.baseline&&!$.baseline.aborted&&!J.aborted?wQ($.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((H)=>Math.max(...[[Y,"n","pass rate","score"],...z].map((C)=>C[H].length))),N=(H)=>H.map((C,O)=>C.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 qQ(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function xQ(J){return Math.min(1,Math.max(0,J))}function fQ(J){return J instanceof Error?J.message:String(J)}function KJ(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 j8=/^[A-Za-z0-9_-]{1,64}$/;function x8(J,$){let Q=I8($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((z)=>Z$(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(!j8.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(Z$(J,z,Z));else G.get(D).push(Z$(J,z,!1))}let Y=[];for(let[z,D]of K){let N=G.get(z);if(N.length===0)continue;Y.push(W$.create({name:z,description:D.description,tools:N,deferred:D.deferred??Z}))}return[...Y,...V]}function I8(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function Z$(J,$,Q){if($.kind==="tool")return w8(J,$,Q);return EJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Q,execute:(Z,W)=>{let K=c.getStore()?.req;if(!K)throw new p(`"${$.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 w8(J,$,Q){let Z=J.nativeTool($.name);return EJ.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=c.getStore()?.req;return J.startNative(X?{kind:"local",req:X}:void 0,$.name,W,K)}})}function q8(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 bQ(J,$){if(J.size!==void 0)try{q8(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 yQ(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 K${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;bQ(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new K$(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)=>yQ(Q,`image-${Z}`)),...J.mask?{mask:yQ(J.mask,"mask")}:{},signal:J.signal}))}present(J){return vQ(this.provider.model,J.usage),f8(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 bQ($,`ImageModel "${this.name}"`),$}}function f8(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}var X$=300000;function G$(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 kJ 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 b8={png:"image/png",jpeg:"image/jpeg"};function y8(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 v8(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function h8(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new kJ({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:v8(Q),mimeType:b8[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:y8(J.usage)}}async function gQ(J,$,Q,Z){let W;try{W=await hQ(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 kJ(a(K),{cause:K})}return h8(await W.json())}async function uQ(J,$,Q={}){return await gQ(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function cQ(J,$,Q={}){return await gQ(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class TJ{static models(){return[]}modelName(){return this.model}async generate(J){return await uQ(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 cQ(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 a(J)}}var lQ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class Y$ extends TJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new Y$(J,$)}static models(){return lQ}endpoint(){return G$(pQ(this.config,{timeoutMs:X$}))}}class V$ extends TJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new V$(J,$)}static models(){return lQ}modelName(){return this.config.deployment??this.model}endpoint(){return G$(mQ(this.config,{timeoutMs:X$}))}}class jJ{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 dQ=Symbol("timed-out");class GJ extends H${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=z$(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 jJ;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=g8(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new GJ(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 GJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new GJ([$],this.options)}upload(J){return this.entries[0].provider.upload(J)}deleteFile(J){let $=this.entries[0].provider;if(!$.deleteFile)return Promise.reject(Error(`${$.constructor.name} cannot delete provider files: it does not implement deleteFile().`));return $.deleteFile(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(L)=>{if(V)return;V=!0,await this.record(W,K,L)},z=new AbortController,D=()=>z.abort(Q?.reason);if(Q?.aborted)z.abort(Q.reason);else Q?.addEventListener("abort",D,{once:!0});let N=[],H=!1,C=!1,O,P,F,U=!1,_,R=!1,E=(L)=>{let k=$?T(T(A(),$),L.usage):L.usage;return $=void 0,{...L,usage:k}};try{_=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:z.signal})[Symbol.asyncIterator]();let L=K.timeoutMs!==void 0?Date.now()+K.timeoutMs:void 0;for(;;){let k=!H&&L!==void 0?await u8(_.next(),Math.max(0,L-Date.now())):await _.next();if(k===dQ){U=!0,F={error:{code:"provider_error",message:`${G} did not start answering within ${K.timeoutMs}ms.`,retryable:!0}};break}if(k.done){R=!0;break}let M=k.value;if(M.type==="finish"&&M.model)P=M.model;if(M.type==="retry"){yield M;continue}if(H){if(M.type==="finish")O=T(O??A(),M.usage),C=!0,yield E(M);else{if(M.type==="error")F={error:M.error};yield M}continue}if(iQ(M)){H=!0,await Y("success"),yield*N.splice(0),yield M;continue}if(M.type==="error")F={error:M.error,...t(M)};else if(M.type==="finish"){if(O=T(O??A(),M.usage),M.reason==="error"&&!F)F={error:{code:"provider_error",message:`${G} ended the call with an error and did not say which.`,retryable:!1}}}N.push(M)}}catch(L){let k=K.provider.normalizeError(L);if(H){if(k.code!=="aborted")yield{type:"error",error:k,...t(L)};this.report({index:W,model:G,responseModel:P,attempt:Z,usage:O,outcome:D$(k),error:k}),yield E({type:"finish",reason:k.code==="aborted"?"aborted":"error",usage:A(),...P?{model:P}:{}});return}F={error:k,...t(L)}}finally{if(Q?.removeEventListener("abort",D),!R)z.abort(),_?.return?.()?.catch(()=>{})}if(H){if(!C&&$)yield{type:"finish",reason:F?"error":"stop",usage:$},$=void 0;this.report({index:W,model:G,responseModel:P,attempt:Z,usage:O,outcome:F?D$(F.error):"ok",...F?{error:F.error}:{}});return}if(Q?.aborted){await Y("none"),this.report({index:W,model:G,responseModel:P,attempt:Z,usage:O,outcome:"aborted"}),yield E({type:"finish",reason:"aborted",usage:O??A(),...P?{model:P}:{}});return}if(!F){await Y("success"),this.report({index:W,model:G,responseModel:P,attempt:Z,usage:O,outcome:"ok"});for(let L of N)yield L.type==="finish"?E(L):L;return}let j=!X&&F.error.code!=="aborted"&&this.shouldFallBack(F.error,{index:W,model:G,timedOut:U,...t(F)});if(await Y(j?"failure":"none"),this.report({index:W,model:G,responseModel:P,attempt:Z,usage:O,outcome:j?"fallback":D$(F.error),error:F.error}),j){if(O)$=T($??A(),O);continue}let x=!1,f;for(let L of N){if(L.type==="finish"){f=L;continue}if(L.type==="error")x=!0;yield L}if(!x&&F.error.code!=="aborted")yield{type:"error",error:F.error,...t(F)};yield E({type:"finish",reason:F.error.code==="aborted"?"aborted":f?.reason??"error",usage:O??A(),...P?{model:P}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(z$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=z$($),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 z$(J){return J.circuitKey??J.provider.model}function D$(J){return J.code==="aborted"?"aborted":"failed"}function g8(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch),supportsForcedToolChoice:J.every(($)=>$.supportsForcedToolChoice!==!1)}}function u8(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(dQ),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function c8(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 IJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var VJ="ask_agent",p8={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},m8={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 YJ(J={}){return[{name:J.name??VJ,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 xJ=new Map;class m{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 m(J)}static get(J){return xJ.get(J)}static async endAll(J){await Promise.all([...xJ.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={...p8,...nQ(J.limits)},this.lines={...m8,...nQ(J.lines)},this.delegateName=J.delegate?.name??VJ;let $=new Set(YJ(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),xJ.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=T(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?T(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=l8(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)=>i8(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,H)=>{V=setTimeout(()=>{H(new p(`"${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 IJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let N=D instanceof p?D.message:"The tool failed.";if(!(D instanceof p))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??d8();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 IJ)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([...YJ(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};xJ.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 nQ(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function l8(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function i8(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 d8(){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 oQ="http://gemi.internal/__gemi__/voice/mcp";async function P$(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(sQ()),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=sQ();return c.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 sQ(){return new I(new Request(oQ,{method:"POST"}),{},"api",new URL(oQ).pathname)}class N${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 F$=new N$;var aQ=new WeakMap,tQ=100;class O${threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(J,$={}){this.threadsTable=rQ($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=rQ($.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 O$({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return $.scope=J,$}async createTable(){let J=s8(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($);await this.addScopeColumns()}async addScopeColumns(){let J=a8(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`
182
182
  INSERT INTO ${this.threads(Z)} (id, user_id, created_at, updated_at)
183
183
  VALUES (${$}, ${Q}, ${W}, ${W})
184
184
  `;else await Z`
@@ -190,14 +190,14 @@ import{ca as wQ,da as yQ,ea as vQ,fa as z6,ga as D6,ha as H6,ia as y$,ja as P6,k
190
190
  SELECT message FROM ${this.messages($)}
191
191
  WHERE thread_id = ${J} AND ${this.inScope($)}
192
192
  ORDER BY position
193
- `).map((W)=>JSON.parse(String(W.message)))})}async appendMessages(J,$){if($.length===0){if(await this.getThread(J)===null)throw nQ(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 eQ(J);return}await this.atomically(async(Q)=>{await Q`
194
194
  UPDATE ${this.threads(Q)} SET updated_at = ${this.clock(Q)}
195
195
  WHERE id = ${J} AND ${this.inScope(Q)}
196
196
  `;let Z=await Q`
197
197
  SELECT title FROM ${this.threads(Q)} WHERE id = ${J} AND ${this.inScope(Q)}
198
- `;if(Z.length===0)throw nQ(J);let W=[...new Set($.map((Y)=>Y.id))],K=await Q`
198
+ `;if(Z.length===0)throw eQ(J);let W=[...new Set($.map((Y)=>Y.id))],K=await Q`
199
199
  SELECT id FROM ${this.messages(Q)}
200
- WHERE thread_id = ${J} AND id IN (${oQ(Q,W)})
200
+ WHERE thread_id = ${J} AND id IN (${JZ(Q,W)})
201
201
  `,X=new Set(K.map((Y)=>String(Y.id))),[G]=await Q`
202
202
  SELECT MAX(position) AS position FROM ${this.messages(Q)} WHERE thread_id = ${J}
203
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`
@@ -209,21 +209,21 @@ import{ca as wQ,da as yQ,ea as vQ,fa as z6,ga as D6,ha as H6,ia as y$,ja as P6,k
209
209
  `,X.add(Y.id),V+=1;else await Q`
210
210
  INSERT INTO ${this.messages(Q)} (thread_id, scope, id, position, message, created_at)
211
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=u8($);if(Y!==null)await Q`
212
+ `,X.add(Y.id),V+=1}if(Z[0].title===null||Z[0].title===void 0){let Y=n8($);if(Y!==null)await Q`
213
213
  UPDATE ${this.threads(Q)} SET title = ${Y}
214
214
  WHERE id = ${J} AND title IS NULL
215
215
  `}})}async removeMessages(J,$){if($.length===0)return;await this.run(async(Q)=>{await Q`
216
216
  DELETE FROM ${this.messages(Q)}
217
217
  WHERE thread_id = ${J} AND ${this.inScope(Q)}
218
- AND id IN (${oQ(Q,[...new Set($)])})
218
+ AND id IN (${JZ(Q,[...new Set($)])})
219
219
  `})}async loadSummaries(J){return this.run(async($)=>{let[Q]=await $`
220
220
  SELECT summaries FROM ${this.threads($)} WHERE id = ${J} AND ${this.inScope($)}
221
- `;return Q?sQ(Q.summaries):[]})}async saveSummary(J,$){await this.atomically(async(Q)=>{await Q`
221
+ `;return Q?$Z(Q.summaries):[]})}async saveSummary(J,$){await this.atomically(async(Q)=>{await Q`
222
222
  UPDATE ${this.threads(Q)} SET updated_at = updated_at
223
223
  WHERE id = ${J} AND ${this.inScope(Q)}
224
224
  `;let[Z]=await Q`
225
225
  SELECT summaries FROM ${this.threads(Q)} WHERE id = ${J} AND ${this.inScope(Q)}
226
- `;if(!Z)return;let W=YJ(sQ(Z.summaries),$);await Q`
226
+ `;if(!Z)return;let W=zJ($Z(Z.summaries),$);await Q`
227
227
  UPDATE ${this.threads(Q)} SET summaries = ${JSON.stringify(W)}
228
228
  WHERE id = ${J}
229
229
  `})}async lockSummary(J,$,Q){let Z=`${$}:${crypto.randomUUID()}`;if(!await this.run(async(K)=>{let X=this.clock(K),G=await K`
@@ -231,20 +231,20 @@ import{ca as wQ,da as yQ,ea as vQ,fa as z6,ga as D6,ha as H6,ia as y$,ja as P6,k
231
231
  SET summary_lock = ${Z}, summary_lock_until = ${X} + ${this.ms(K,Q)}
232
232
  WHERE id = ${J} AND ${this.inScope(K)}
233
233
  AND (summary_lock_until IS NULL OR summary_lock_until <= ${X})
234
- `;return c8(G)>0}))return null;return async()=>{await this.run(async(K)=>{await K`
234
+ `;return o8(G)>0}))return null;return async()=>{await this.run(async(K)=>{await K`
235
235
  UPDATE ${this.threads(K)} SET summary_lock = NULL, summary_lock_until = NULL
236
236
  WHERE id = ${J} AND ${this.inScope(K)} AND summary_lock = ${Z}
237
237
  `})}}async getThread(J){return this.run(async($)=>{let[Q]=await $`
238
238
  SELECT id, user_id, title, created_at, updated_at FROM ${this.threads($)}
239
239
  WHERE id = ${J} AND ${this.inScope($)}
240
- `;return Q?aQ(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?QZ(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`
241
241
  SELECT id, user_id, title, created_at, updated_at FROM ${this.threads(Z)}
242
242
  WHERE ${this.inScope(Z)} AND ${W}
243
243
  ORDER BY updated_at DESC, id DESC
244
244
  LIMIT ${$} OFFSET ${Q}
245
- `).map(aQ)})}async deleteThread(J){await this.atomically(async($)=>{if((await $`
245
+ `).map(QZ)})}async deleteThread(J){await this.atomically(async($)=>{if((await $`
246
246
  SELECT id FROM ${this.threads($)} WHERE id = ${J} AND ${this.inScope($)}
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 BJ(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=(lQ.get(this.sql)??Promise.resolve()).then(Z,Z);return lQ.set(this.sql,K.then(()=>{},()=>{})),K}joinable(){if(this.connection===void 0)return;let J=n();if(J===void 0||o()!==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 dQ(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 nQ(J){return Error(`Thread ${J} does not exist here, or has been deleted.`)}function oQ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function u8(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>iQ?`${Q.slice(0,iQ-1)}\u2026`:Q}return null}function sQ(J){if(J===null||J===void 0||J==="")return[];let $=JSON.parse(String(J));return Array.isArray($)?$:[]}function aQ(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 c8(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function m8(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 SJ(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=(aQ.get(this.sql)??Promise.resolve()).then(Z,Z);return aQ.set(this.sql,K.then(()=>{},()=>{})),K}joinable(){if(this.connection===void 0)return;let J=o();if(J===void 0||s()!==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 rQ(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 eQ(J){return Error(`Thread ${J} does not exist here, or has been deleted.`)}function JZ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function n8(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>tQ?`${Q.slice(0,tQ-1)}\u2026`:Q}return null}function $Z(J){if(J===null||J===void 0||J==="")return[];let $=JSON.parse(String(J));return Array.isArray($)?$:[]}function QZ(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 o8(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function s8(J,$,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
248
248
  \`id\` VARCHAR(191) NOT NULL,
249
249
  \`scope\` VARCHAR(191) NULL,
250
250
  \`user_id\` VARCHAR(191) NULL,
@@ -289,14 +289,14 @@ import{ca as wQ,da as yQ,ea as vQ,fa as z6,ga as D6,ha as H6,ia as y$,ja as P6,k
289
289
  "created_at" BIGINT NOT NULL,
290
290
 
291
291
  CONSTRAINT "${Q}_pkey" PRIMARY KEY ("thread_id", "id")
292
- )`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}function p8(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 a 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 VJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class xJ{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 VJ(J);if($!==void 0&&$<Q.lostBefore)throw new a(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)=>F$($,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)=>F$($,K))}}catch(Z){F$($,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 a($,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 N$=new xJ;function F$(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 O$=new IJ;class L${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 tQ="pending",C$="done:",l8=`
292
+ )`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}function a8(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 r 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 DJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class wJ{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 DJ(J);if($!==void 0&&$<Q.lostBefore)throw new r(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)=>U$($,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)=>U$($,K))}}catch(Z){U$($,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 r($,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 C$=new wJ;function U$(J,$){try{J.onInternalError?.($)}catch{}}class qJ{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}async delete(J){this.records.delete(J)}async expired(J,$){let Q=[];for(let[Z,W]of this.records){if(Q.length>=$)break;if(W.expiresAt&&Date.parse(W.expiresAt)<=J.getTime())Q.push(Z)}return Q}}var _$=new qJ;class M${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 ZZ="pending",L$="done:",t8=`
293
293
  if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
294
294
  local held = redis.call('GET', KEYS[1])
295
295
  if not held then return ARGV[1] end
296
- return held`,i8=`
296
+ return held`,r8=`
297
297
  if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
298
- return 0`;class _${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",[l8,"1",this.key(J),tQ,rQ($)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(C$))return{status:"replay",result:JSON.parse(Z.slice(C$.length))};return{status:"blocked"}}async complete(J,$,Q){await this.client.send("SET",[this.key(J),C$+JSON.stringify($),"PX",rQ(Q)])}async release(J){await this.client.send("EVAL",[i8,"1",this.key(J),tQ])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=eQ(),$=J.bound(U$)?J.make(U$).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 rQ(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var d8=86400000,n8=60000;class zJ{ttlMs;clientOwnedIds;scope=null;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??d8,this.clientOwnedIds=J.clientOwnedIds??!1}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A MemoryAgentStore scope is a non-empty string.");let $=new zJ({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=YJ(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<n8)return;this.lastSweep=J;for(let[$,Q]of this.threads)if(J-Q.touchedAt>this.ttlMs)this.threads.delete($)}}var B$=new zJ;function ZZ(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 WZ(J,$,Q=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==J.cursorRunId)&&$.seq<=J.seq)return J;return{...KZ(J,$.event,Q),seq:$.seq}}function KZ(J,$,Q){switch($.type){case"run-start":return{...J,messages:o8(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($Z(J,$.messageId))return J;return b(J,$.messageId,Q,(Z)=>({...Z,content:e8(Z.content,$.delta)}));case"reasoning-delta":if($Z(J,$.messageId))return J;return b(J,$.messageId,Q,(Z)=>({...Z,content:J9(Z.content,$.delta,$.id,$.providerMetadata)}));case"output-delta":return b(J,$.messageId,Q,(Z)=>({...Z,content:QZ(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 JZ(J,$.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],$.data]}));case"nested-event":{let Z=$;return JZ(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=t8(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:QZ(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:XZ(J,$.finishReason)};default:return J}}function o8(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 XZ(J,$){return J.messages.map((Q)=>Q.role==="assistant"&&J.runMessageIds.includes(Q.id)?s8(Q,$):Q)}function s8(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?a8(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 a8(J,$){let Q={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:$,messages:XZ(Q,$)}}function JZ(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&&!r8(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 t8(J,$,Q){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((K)=>K.id),loadedTools:[],finishReason:J.finishReason},W=KZ(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 r8(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 $Z(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 e8(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 J9(J,$,Q,Z){let W=J[J.length-1];if(W&&W.type==="reasoning"&&W.id===Q&&!W.providerMetadata)return[...J.slice(0,-1),{...W,text:(W.text??"")+$,...Z?{providerMetadata:Z}:{}}];return[...J,{type:"reasoning",...Q?{id:Q}:{},text:$,...Z?{providerMetadata:Z}:{}}]}function QZ(J,$,Q){let Z=J.findIndex(Q);if(Z===-1)return[...J,$];let W=J.slice();return W[Z]=$,W}class S${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=ZZ({messages:Q})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[M$(J)])}frame(J){if(this.closed)return;let $=J.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=WZ(this.state,J),$.type){case"message":this.write(()=>[M$($.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=M$($);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 M$(J){return structuredClone(J)}async function GZ(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"?YZ(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 YZ(J){let{partial:$,...Q}=J;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map($9)}}function $9(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"?YZ(Q):Q)}:$)}}var Q9=50,Z9=["waiting","running","ok","error"];async function DZ(J,$){let{store:Q,threadId:Z}=$,W=Math.max(Q9,$.scan??0),K=await Q.listForThread(Z,{limit:W}),X,G=async(P)=>{if(P.state!=="running")return P;if(X??=await VZ(Q),P.deadlineAt>X)return P;return await zZ(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]=W9(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 HZ(J,$,Q){for(let Z of $)try{await J.transition(Z.id,Z9,{orphaned:!0})}catch(W){Q(W)}}function W9(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 K9=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;class gJ 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 gJ(Q("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:Q("code"),kind:Q("kind")})}}function X9(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 G9=TZ,DJ=new Map,A$=new WeakMap,t=new WeakMap,PZ=new WeakMap,FZ=new WeakMap,R$=new WeakMap,oZ="thread_busy",NZ="http://gemi.internal/__gemi/agent-turn",wJ=new Map,Y9=4194304,V9=1000,z9=5,HJ=65536,e=()=>{};class sZ{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 OZ=new WeakMap,k$=new WeakMap;function D9(J){let $=k$.get(J);if(!$)$=new Map,k$.set(J,$);return $}function H9(J,$,Q){let Z=k$.get(J)?.get($);if(!Z)return;for(let W of[...Z])try{W(Q)}catch{}}function P9(J){let $=OZ.get(J);if(!$)$=new sZ,OZ.set(J,$);return $}function F9(J){return J}class v$ extends G9{static kind="agent-controller";hooks;store=B$;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=PZ.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=EZ(this.store,Z);this.boundScope=Z}liveRuns=N$;voice;voiceStore=H$;attachments=hJ;attachmentStorage=IZ;fileOwners=O$;nonces=f$;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=Y9;maxHistoryMessages=V9;contextWindow=void 0;prepareStep(J,$){return this.hooks?.prepareStep?.(J,$)}maxConcurrentRuns=z9;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:E9(J),W={...J.turn,...J.text!==void 0?{text:J.text}:{}},K={...J.body,threadId:$,turn:W},X=new j(new Request(NZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K)}),{},"api",new URL(NZ).pathname),G=new this;if(t.set(X,null),J.scope!==void 0)PZ.set(X,J.scope);if(FZ.set(X,Q),Z)R$.set(X,Z);let V=await h.run(X,()=>G.stream(X),{user:J.user??null}),Y=t.get(X);if(!Y){let O=await gJ.from(V);if(Q==="skip"&&O.code===oZ)return{skipped:!0,threadId:$};throw O}t.delete(X),V.body?.cancel().catch(e);let{run:z,hooks:D}=Y,N=[],P=(async()=>{for await(let O of z)if(O.type==="awaiting-input")N=O.pending})().catch(e),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:X9(F),pending:O.finishReason==="awaiting-input"?N:[]}})()}}async stream(J=new j){let $=await r(J,this.maxBodyBytes);if($.error)return c($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=M9(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=qJ(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 I$(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)wJ.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 i=await this.settleThread(Z,S,{write:!0});if(O=i.messages,F=this.jobsBlock(i.jobs),X){let JJ=R9(O);if(!JJ)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});N=O.slice(JJ.index),await this.store.removeMessages(Z,N.map((J8)=>J8.id)),O=O.slice(0,JJ.index),K=K?.localId?{...JJ.turn,localId:K.localId}:JJ.turn}}else O=Array.isArray(Q.messages)?Q.messages:[],q9(this.nonces);let H=[await this.instructions(J,{body:V})||void 0,F??void 0].filter(Boolean).join(`
298
+ return 0`;class S${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",[t8,"1",this.key(J),ZZ,WZ($)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(L$))return{status:"replay",result:JSON.parse(Z.slice(L$.length))};return{status:"blocked"}}async complete(J,$,Q){await this.client.send("SET",[this.key(J),L$+JSON.stringify($),"PX",WZ(Q)])}async release(J){await this.client.send("EVAL",[r8,"1",this.key(J),ZZ])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=KZ(),$=J.bound(B$)?J.make(B$).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 WZ(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var e8=86400000,J9=60000;class HJ{ttlMs;clientOwnedIds;scope=null;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??e8,this.clientOwnedIds=J.clientOwnedIds??!1}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A MemoryAgentStore scope is a non-empty string.");let $=new HJ({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=zJ(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<J9)return;this.lastSweep=J;for(let[$,Q]of this.threads)if(J-Q.touchedAt>this.ttlMs)this.threads.delete($)}}var A$=new HJ;function VZ(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{...DZ(J,$.event,Q),seq:$.seq}}function DZ(J,$,Q){switch($.type){case"run-start":return{...J,messages:$9(J.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return v(J,$.messageId,Q,(Z)=>({...Z,role:$.role}));case"text-delta":if(GZ(J,$.messageId))return J;return v(J,$.messageId,Q,(Z)=>({...Z,content:X9(Z.content,$.delta)}));case"reasoning-delta":if(GZ(J,$.messageId))return J;return v(J,$.messageId,Q,(Z)=>({...Z,content:G9(Z.content,$.delta,$.id,$.providerMetadata)}));case"output-delta":return v(J,$.messageId,Q,(Z)=>({...Z,content:YZ(Z.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return v(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 v(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 XZ(J,$.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],$.data]}));case"nested-event":{let Z=$;return XZ(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=W9(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=v(J,$.messageId,Q,(W)=>({...W,content:YZ(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 v(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:HZ(J,$.finishReason)};default:return J}}function $9(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 HZ(J,$){return J.messages.map((Q)=>Q.role==="assistant"&&J.runMessageIds.includes(Q.id)?Q9(Q,$):Q)}function Q9(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?Z9(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 Z9(J,$){let Q={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:$,messages:HZ(Q,$)}}function XZ(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&&!K9(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 W9(J,$,Q){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((K)=>K.id),loadedTools:[],finishReason:J.finishReason},W=DZ(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 K9(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 GZ(J,$){let Q=J.messages.find((Z)=>Z.id===$);return Q!==void 0&&Q.finishReason!==void 0}function v(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 X9(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 G9(J,$,Q,Z){let W=J[J.length-1];if(W&&W.type==="reasoning"&&W.id===Q&&!W.providerMetadata)return[...J.slice(0,-1),{...W,text:(W.text??"")+$,...Z?{providerMetadata:Z}:{}}];return[...J,{type:"reasoning",...Q?{id:Q}:{},text:$,...Z?{providerMetadata:Z}:{}}]}function YZ(J,$,Q){let Z=J.findIndex(Q);if(Z===-1)return[...J,$];let W=J.slice();return W[Z]=$,W}class E${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=VZ({messages:Q})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[R$(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(()=>[R$($.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=R$($);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 R$(J){return structuredClone(J)}async function PZ(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"?NZ(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 NZ(J){let{partial:$,...Q}=J;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(Y9)}}function Y9(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"?NZ(Q):Q)}:$)}}var V9=50,z9=["waiting","running","ok","error"];async function UZ(J,$){let{store:Q,threadId:Z}=$,W=Math.max(V9,$.scan??0),K=await Q.listForThread(Z,{limit:W}),X,G=async(H)=>{if(H.state!=="running")return H;if(X??=await FZ(Q),H.deadlineAt>X)return H;return await OZ(Q,H),await Q.get(H.id)??H};for(let H=0;H<K.length;H++)K[H]=await G(K[H]);let V=new Map(K.map((H)=>[H.id,H])),Y=J.slice(),z=[],D=new Set;for(let H=0;H<Y.length;H++){let C=Y[H],O=null;for(let P=0;P<C.content.length;P++){let F=C.content[P];if(F.type==="tool-call")D.add(F.toolCallId);if(F.type!=="tool-result"||F.status!=="running")continue;let U=F.job?.id,_=U?V.get(U):void 0;if(U&&_===void 0){let R=await Q.get(U);if(_=R?await G(R):void 0,_)V.set(U,_)}if(_&&!b(_.state))continue;O??=C.content.slice(),O[P]=D9(F,_,$.outputSchemaFor,$.modelOutputFor)}if(O){let P={...C,content:O};Y[H]=P,z.push(P)}}let N=[];for(let H of K){if(H.orphaned||H.toolCallId===""||D.has(H.toolCallId))continue;if(await $.isRunLive(H.runId))continue;N.push(H)}return{messages:Y,settled:z,orphans:N,jobs:K}}async function CZ(J,$,Q){for(let Z of $)try{await J.transition(Z.id,z9,{orphaned:!0})}catch(W){Q(W)}}function D9(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 H9=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;class mJ 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 mJ(Q("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:Q("code"),kind:Q("kind")})}}function P9(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 N9=fZ,PJ=new Map,k$=new WeakMap,e=new WeakMap,_Z=new WeakMap,LZ=new WeakMap,T$=new WeakMap,J8="thread_busy",BZ="http://gemi.internal/__gemi/agent-turn",fJ=new Map,F9=4194304,O9=1000,U9=5,NJ=65536,$J=()=>{};class $8{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 MZ=new WeakMap,I$=new WeakMap;function C9(J){let $=I$.get(J);if(!$)$=new Map,I$.set(J,$);return $}function _9(J,$,Q){let Z=I$.get(J)?.get($);if(!Z)return;for(let W of[...Z])try{W(Q)}catch{}}function L9(J){let $=MZ.get(J);if(!$)$=new $8,MZ.set(J,$);return $}function B9(J){return J}class hJ extends N9{static kind="agent-controller";hooks;store=A$;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=_Z.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=wZ(this.store,Z);this.boundScope=Z}liveRuns=C$;voice;voiceStore=F$;attachments=pJ;attachmentStorage=vZ;turnAttachmentMaxAgeMs=3600000;fileOwners=_$;nonces=v$;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=F9;maxHistoryMessages=O9;contextWindow=void 0;prepareStep(J,$){return this.hooks?.prepareStep?.(J,$)}maxConcurrentRuns=U9;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:q9(J),W={...J.turn,...J.text!==void 0?{text:J.text}:{}},K={...J.body,threadId:$,turn:W},X=new I(new Request(BZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K)}),{},"api",new URL(BZ).pathname),G=new this;if(e.set(X,null),J.scope!==void 0)_Z.set(X,J.scope);if(LZ.set(X,Q),Z)T$.set(X,Z);let V=await c.run(X,()=>G.stream(X),{user:J.user??null}),Y=e.get(X);if(!Y){let O=await mJ.from(V);if(Q==="skip"&&O.code===J8)return{skipped:!0,threadId:$};throw O}e.delete(X),V.body?.cancel().catch($J);let{run:z,hooks:D}=Y,N=[],H=(async()=>{for await(let O of z)if(O.type==="awaiting-input")N=O.pending})().catch($J),C;return{runId:z.runId,threadId:$,run:z,stop:(O)=>z.stop(O),result:()=>C??=(async()=>{let O=await z.result();await Promise.all([D,H]);let P=O.messages;return{...O,threadId:$,text:P9(P),pending:O.finishReason==="awaiting-input"?N:[]}})()}}async stream(J=new I){let $=await JJ(J,this.maxBodyBytes);if($.error)return l($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=j9(Q);if(W.error)return l({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=vJ(Q);if(this.requireThread&&!Z)return B(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 B(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 b$(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)fJ.set(G,z);let D=null,N=[],H=async()=>{try{return await C()}finally{if(Z&&N.length>0&&D===null)await this.store.appendMessages(Z,N).catch((O)=>this.reportHookFailure(O))}},C=async()=>{let O,P=null;if(Z){let S=await this.store.loadThread(Z);if(!S)return B(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let d=await this.settleThread(Z,S,{write:!0});if(O=d.messages,P=this.jobsBlock(d.jobs),X){let QJ=w9(O);if(!QJ)return B(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});N=O.slice(QJ.index),await this.store.removeMessages(Z,N.map((G8)=>G8.id)),O=O.slice(0,QJ.index),K=K?.localId?{...QJ.turn,localId:K.localId}:QJ.turn}}else O=Array.isArray(Q.messages)?Q.messages:[],c9(this.nonces);let F=[await this.instructions(J,{body:V})||void 0,P??void 0].filter(Boolean).join(`
299
299
 
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 MZ();let _=Z?new S$(this.store,Z,O,(S)=>this.reportHookFailure(S)):null,E=`run_${crypto.randomUUID()}`,B=[],l={req:J,runId:E,threadId:Z,get denials(){return B}},FJ={id:null,notified:Promise.resolve()},w=this.agent.stream({runId:E,messages:O,turn:K,threadId:Z,..._?{onMessage:(S)=>_.finish(S)}:{},onTurn:(S)=>{if(FJ.id!==null)return;FJ.id=S.id;let i=_?_.settled():Promise.resolve();FJ.notified=i.then(()=>this.safely(()=>this.onMessage(S,l)))},instructions:H,...R$.has(J)?{event:R$.get(J)}:{},...t.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,i)=>this.redactError(S,i,l),onProviderRetry:(S)=>this.onProviderRetry(S,l),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&&iZ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==v$.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(S)=>this.prepareStep(S,l)}:{}});B=w.denials;let rZ=this.liveRuns.register(w,{threadId:Z,owner:Y,clientRunId:G,onEvent:(S)=>this.dispatchEvent(S,l),onInternalError:(S)=>this.reportHookFailure(S),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=w,_)this.follow(w,_);if(Z)H9(this.liveRuns,Z,w.runId);let{stored:eZ,hooks:h$}=this.persistRun(w,l,rZ,_,FJ);if(A$.set(w,eZ),t.has(J))t.set(J,{run:w,hooks:h$});return J.ctx?.()?.waitUntil(h$),w.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let O=await this.foreignFile([...K?.files??[],...Z?[]:T9(Q.messages)],Y);if(O)return O;if(z?.cancelled)return MZ();let F=await this.runLimitKey(J,{owner:Y,threadId:Z}),H=F===null?e:P9(this.liveRuns).take(F,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!H)return I$(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,FZ.get(J)??"supersede"):await P()}finally{let C=D;if(C)C.result().then(H,H);else H()}}finally{if(z&&wJ.get(G)===z)wJ.delete(G)}}async withThread(J,$,Q,Z="supersede"){if(Z==="skip"&&DJ.has(J))return SZ(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=DJ.get(J)??Promise.resolve(),K,X=new Promise((V)=>{K=V}),G=W.then(()=>X);DJ.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:SZ(J)};let z=this.liveRuns.get(V.runId),D=z?A$.get(z)??z.result():null;if(D)return{waitFor:D.then(e,e)}}if(V&&this.liveRuns.isRunning(V.runId)&&!this.liveRuns.mayAccess(V.runId,$))return{response:PJ()};let Y=V?this.liveRuns.get(V.runId):null;if(Y)Y.stop({reason:"superseded by a later turn on this thread"}),await A$.get(Y);return{response:await Q()}}finally{if(K(),DJ.get(J)===G)DJ.delete(J)}}async attach(J=new j){let $=await r(J,HJ);if($.error)return c($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:BZ(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 kZ(Z,W);let K=await this.liveRuns.find({threadId:Z});if(K&&!this.liveRuns.mayAccess(K.runId,await this.runOwner(J)))return PJ();if(!K)return kZ(Z,W);let X=typeof Q.runId==="string"?Q.runId:void 0,G=X&&X!==K.runId?void 0:A9(J,Q);try{return bZ(this.liveRuns.replay(K.runId,G))}catch(V){if(V instanceof a)return M(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof VJ)return M(404,{code:V.code,message:V.message});throw V}}async watch(J=new j){let $=await r(J,HJ);if($.error)return c($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:BZ(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=D9(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=fZ(P);let U=(F)=>{if(!K.mayAccess(F,W))return;try{P.enqueue(new TextEncoder().encode(wZ({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:qZ()})}async stop(J=new j){let $=await r(J,HJ);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=wJ.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return PJ();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 PJ();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 vJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new j){let $=this.voice;if(!$)return E$();let Q=await r(J,HJ);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=qJ(Q.body,j9),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 z$(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:[...XJ($.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 y$&&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??GJ,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 E$();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await r(J,HJ);if(Q.error)return c(Q);let Z=qJ(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 E$();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 PJ();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=O9($.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=U9(await this.attachmentLimits(J),Q,Z,W);if(G)throw new x$(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 x$(N.code||"upload_refused",N.message);let P=await this.attachmentDestination(Q,J,D),U=x9(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()`.');I9()}if(U==="provider"||!O){let R=await CZ(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=cZ(),C=await this.attachmentStorage.put({name:mZ(H,Z),body:Q,contentType:W}),L=U==="both"?await CZ(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 k9()}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 q$(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:nZ(Q)});return}case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(hZ(J.error),$);return;default:return}}async readThread(J,$={}){let Z=await($.scope===null||$.scope===void 0?this.store:EZ(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 GZ($,Z),K=W.messages,X=[],G=new Map(W.settled.map((V)=>[V.id,V]));if(b9(K)||Q)try{let V=await DZ(K,{threadId:J,store:y.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolNamed(Y)?.outputSchema,modelOutputFor:(Y,z)=>dZ(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 HZ(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??LJ}jobsBlock(J){return n$(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(()=>f9(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 T$=["turn","clientRunId","threadId","messages","regenerate"],N9=["text","files","toolResults"];function qJ(J,$=tZ(J)?T$:[...T$,...N9]){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 O9(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new j$("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new j$("The upload's `body` field must be a JSON object.");return qJ($,T$)}class j$ extends bJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function CZ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof lZ&&C9.has(Q.status))throw new aZ(s(Q).message);throw Q}}var C9=new Set([400,413,415,422]);class x$ extends bJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function U9(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 ${UZ($.size)}; the limit is ${UZ(W)}.`};if(K&&K.length>0&&!K.some((X)=>L9(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 L9(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 UZ(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 aZ extends bJ{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 r(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!_9(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 LZ($);let W;try{let X=await B9(Q,$);if(X===null)return LZ($);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 _9(J){return xZ(J)==="application/json"}async function B9(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(e),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 LZ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function I$(J,$,Q){return M(J,{...yJ(jZ(J),Q,J),code:$})}function c(J){if(J.status===413)return I$(413,J.code??"body_too_large",J.error??"");return M(J.status??400,{code:J.code??"invalid_request",message:J.error})}function tZ(J){return Boolean(J.turn)&&typeof J.turn==="object"}function M9(J){let $=tZ(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=S9($.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>_Z)return{error:`turn.localId is longer than ${_Z} characters.`};Q.localId=Z}return{turn:Q}}var _Z=200;function S9(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(fJ))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(fJ))return`${W}.attachmentId is not a gemi attachment id: it must start with "${fJ}".`;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 A9(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 BZ(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function R9(J){let $=b$(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 MZ(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function E9(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"||!K9.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 SZ(J){return M(409,{code:oZ,message:`Thread ${J} has a run going, and this turn was not to interrupt it.`})}function PJ(){return M(403,yJ("permission","This run belongs to someone else.",403))}function k9(){return M(403,yJ("permission","A file in this turn was uploaded by someone else.",403))}function T9(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 j9=["sdp","threadId","pushToTalk"];function E$(){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 x9(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 AZ=!1;function I9(){if(AZ)return;AZ=!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 w9=2147483647;function f9(J,$){let Q=J.then(()=>{},()=>{});if(!($<=w9))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var RZ=!1;function q9(J){if(RZ||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof w$))return;RZ=!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 b9(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}function EZ(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 kZ(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{i9 as windowMessages,XJ as voiceTools,u9 as turnStarts,H6 as toRealtimeUsage,S8 as toAgentTools,h9 as supportsStrict,c9 as splitTurns,r9 as settleSummaries,v9 as s,q$ as redactError,V6 as parsePartialJson,m9 as messageSize,WJ as measureUsage,z$ as mcpVoiceTools,N$ as liveRuns,YJ as keepSummary,F6 as isCallNotFound,b$ as injectedMessageIds,rJ as generate,q8 as evalChain,F9 as defineAgentHooks,H$ as defaultVoiceStore,J6 as defaultUsageLimitStore,t9 as defaultSummaryStore,Y6 as defaultPromptCacheKey,f$ as defaultNonceStore,O$ as defaultFileOwners,hJ as defaultAttachmentStore,B$ as defaultAgentStore,jJ as VoiceHangup,u as VoiceBridge,g9 as Usage,J$ as ToolNamespace,g as ToolError,X6 as ToolArgumentsTooLongError,Q6 as Skill,vJ as ScopedAttachments,Z6 as SKILLS_NAMESPACE,_$ as RedisReceiptStore,yZ as RedisNonceStore,z6 as RealtimeSideband,y$ as RealtimeRequestError,P6 as RealtimeClient,l$ as Prompt,vZ as PrismaNonceStore,$6 as PendingEscalation,N6 as OpenAIProvider,W$ as OpenAIImageProvider,D$ as MemoryVoiceSessionStore,e9 as MemoryUsageLimitStore,a9 as MemorySummaryStore,L$ as MemoryReceiptStore,w$ as MemoryNonceStore,xJ as MemoryLiveRuns,IJ as MemoryFileOwners,kJ as MemoryCircuitStore,pZ as MemoryAttachmentStore,zJ as MemoryAgentStore,t$ as MemoryAgentJobStore,FQ as MEMORY_NAMESPACE,VJ as LiveRunNotFoundError,e$ as JobsRequireThreadError,r$ as JobHandle,y9 as JSONSchemaError,uZ as InvalidAttachmentScopeError,YQ as InMemoryAgentMemoryStore,RJ as ImageRequestError,EJ as ImageProvider,$$ as ImageModel,a as FrameCursorEvictedError,KJ as FallbackProvider,HQ as FakeAgentMemoryStore,SJ as Eval,P$ as DatabaseAgentStore,dJ as DatabaseAgentMemoryStore,lJ as DatabaseAgentJobStore,D6 as DEFAULT_TRANSCRIPTION_MODEL,GQ as DEFAULT_MEMORY_MAX_TOKENS,PQ as DEFAULT_MEMORY_LIMITS,d9 as DEFAULT_MAX_SUMMARY_TOKENS,W6 as DEFAULT_MAX_RUN_DURATION_MS,JQ as DEFAULT_JOB_DEADLINE_MS,LJ as DEFAULT_JOBS_CONTEXT_MAX,GJ as DEFAULT_DELEGATE_NAME,p9 as DEFAULT_CONTEXT_WINDOW_STEP,l9 as DEFAULT_CONTEXT_WINDOW_NOTE,n9 as DEFAULT_COMPACT_TRIGGER_TOKENS,o9 as DEFAULT_COMPACT_INSTRUCTIONS,s9 as COMPACT_SUMMARY_HEADER,U6 as AzureOpenAIProvider,K$ as AzureOpenAIImageProvider,C6 as AzureAnthropicProvider,gZ as AttachmentNotFoundError,O6 as AnthropicProvider,gJ as AgentTurnError,AJ as AgentTool,K6 as AgentRunError,V$ as AgentProvider,VQ as AgentMemoryRefusedError,zQ as AgentMemoryConflictError,DQ as AgentMemories,y as AgentJobs,pJ as AgentJobDeadlineSweep,$Q as AgentJob,v$ as AgentController,G6 as Agent};
300
+ `)||void 0,U=await this.context(J,{body:V}),_=await this.reasoning(J,{body:V})||void 0,R=await this.skills(J,{body:V})||void 0,E=await this.runTools(J,{body:V,context:U})||void 0,j=await this.usageLimits(J,{body:V,context:U})||void 0,x=await this.attachmentsFor(J,Z,{body:V}),f=await this.attachmentRetention(J,{route:"stream",threadId:Z,body:V});yJ(f,this.turnAttachmentMaxAgeMs);let L=[],k=x&&f?x.withLifetime({next:()=>yJ(f,this.turnAttachmentMaxAgeMs),onPut:(S)=>L.push(S)}):x,M=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(z?.cancelled)return TZ();let h=Z?new E$(this.store,Z,O,(S)=>this.reportHookFailure(S)):null,c$=`run_${crypto.randomUUID()}`,p$=[],i={req:J,runId:c$,threadId:Z,get denials(){return p$}},OJ={id:null,notified:Promise.resolve()},q=this.agent.stream({runId:c$,messages:O,turn:K,threadId:Z,...h?{onMessage:(S)=>h.finish(S)}:{},onTurn:(S)=>{if(OJ.id!==null)return;OJ.id=S.id;let d=h?h.settled():Promise.resolve();OJ.notified=d.then(()=>this.safely(()=>this.onMessage(S,i)))},instructions:F,...T$.has(J)?{event:T$.get(J)}:{},...e.has(J)?{echoTurn:!0}:{},..._?{reasoning:_}:{},...R&&R.length>0?{skills:R}:{},...E?.tools&&E.tools.length>0?{tools:E.tools}:{},...E?.activeTools?{activeTools:E.activeTools}:{},...j?{usageLimits:j}:{},context:U,attachments:k,body:V,redactError:(S,d)=>this.redactError(S,d,i),onProviderRetry:(S)=>this.onProviderRetry(S,i),nonces:this.nonces,receipts:this.receipts,subject:Y,...M?{memory:{scopes:M,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&tZ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==hJ.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(S)=>this.prepareStep(S,i)}:{}});p$=q.denials;let W8=this.liveRuns.register(q,{threadId:Z,owner:Y,clientRunId:G,onEvent:(S)=>this.dispatchEvent(S,i),onInternalError:(S)=>this.reportHookFailure(S),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=q,h)this.follow(q,h);if(Z)_9(this.liveRuns,Z,q.runId);let m$=K?.files??[],K8=this.definesRetention()&&(m$.length>0||f==="turn")?()=>this.expireTurn({scoped:x,files:m$,made:L,owner:Y}):null,{stored:X8,hooks:l$}=this.persistRun(q,i,W8,h,OJ,K8);if(k$.set(q,X8),e.has(J))e.set(J,{run:q,hooks:l$});return J.ctx?.()?.waitUntil(l$),q.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let O=await this.foreignFile([...K?.files??[],...Z?[]:b9(Q.messages)],Y);if(O)return O;if(z?.cancelled)return TZ();let P=await this.runLimitKey(J,{owner:Y,threadId:Z}),F=P===null?$J:L9(this.liveRuns).take(P,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!F)return b$(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,H,LZ.get(J)??"supersede"):await H()}finally{let U=D;if(U)U.result().then(F,F);else F()}}finally{if(z&&fJ.get(G)===z)fJ.delete(G)}}async withThread(J,$,Q,Z="supersede"){if(Z==="skip"&&PJ.has(J))return jZ(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=PJ.get(J)??Promise.resolve(),K,X=new Promise((V)=>{K=V}),G=W.then(()=>X);PJ.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:jZ(J)};let z=this.liveRuns.get(V.runId),D=z?k$.get(z)??z.result():null;if(D)return{waitFor:D.then($J,$J)}}if(V&&this.liveRuns.isRunning(V.runId)&&!this.liveRuns.mayAccess(V.runId,$))return{response:FJ()};let Y=V?this.liveRuns.get(V.runId):null;if(Y)Y.stop({reason:"superseded by a later turn on this thread"}),await k$.get(Y);return{response:await Q()}}finally{if(K(),PJ.get(J)===G)PJ.delete(J)}}async attach(J=new I){let $=await JJ(J,NJ);if($.error)return l($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:kZ(J,"threadId");if(!Z)return B(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 qZ(Z,W);let K=await this.liveRuns.find({threadId:Z});if(K&&!this.liveRuns.mayAccess(K.runId,await this.runOwner(J)))return FJ();if(!K)return qZ(Z,W);let X=typeof Q.runId==="string"?Q.runId:void 0,G=X&&X!==K.runId?void 0:I9(J,Q);try{return cZ(this.liveRuns.replay(K.runId,G))}catch(V){if(V instanceof r)return B(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof DJ)return B(404,{code:V.code,message:V.message});throw V}}async watch(J=new I){let $=await JJ(J,NJ);if($.error)return l($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:kZ(J,"threadId");if(!Z)return B(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 B(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=C9(K),G=await K.find({threadId:Z}),V=null,Y=null,z=0,D=()=>{if(Y?.stop(),!V)return;let H=X.get(Z);if(H?.delete(V),H&&H.size===0)X.delete(Z);V=null},N=new ReadableStream({start(H){Y=gZ(H);let C=(P)=>{if(!K.mayAccess(P,W))return;try{H.enqueue(new TextEncoder().encode(hZ({seq:++z,event:{type:"run-start",runId:P,threadId:Z}}))),Y?.touch()}catch{D()}};V=C;let O=X.get(Z);if(!O)O=new Set,X.set(Z,O);if(O.add(C),G&&K.isRunning(G.runId))C(G.runId)},cancel(){D()}});return J.rawRequest?.signal?.addEventListener("abort",D,{once:!0}),new Response(N,{status:200,headers:uZ()})}async stop(J=new I){let $=await JJ(J,NJ);if($.error)return l($);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=fJ.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return FJ();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 FJ();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}attachmentRetention(J,$){return this.hooks?.attachmentRetention?.(J,$)??null}definesRetention(){return this.attachmentRetention!==hJ.prototype.attachmentRetention||Boolean(this.hooks?.attachmentRetention)}async sweepAttachments(J={}){let $=J.now??new Date,Q=J.limit??500;if(!this.attachments.expired||!this.attachments.delete)throw Error("sweepAttachments() needs an attachment store with expired() and delete(). Implement both on the controller's `attachments` store.");let Z={deleted:0,failed:0},W=this.deletionTargets();for(let K of await this.attachments.expired($,Q))try{await x$(K,W),Z.deleted++}catch(X){Z.failed++,this.reportHookFailure(X)}for(let K of await this.fileOwners.expired?.($,Q)??[])try{await this.deleteProviderFile(K),Z.deleted++}catch(X){Z.failed++,this.reportHookFailure(X)}return Z}deletionTargets(){return{store:this.attachments,storage:this.attachmentStorage,provider:this.agent.provider,fileOwners:this.fileOwners}}async deleteProviderFile(J){let $=this.agent.provider;if(!$.deleteFile)throw Error(`Cannot delete provider file ${J}: the agent's provider has no deleteFile().`);await $.deleteFile(J),await this.fileOwners.delete?.(J)}async expireTurn(J){let $=this.deletionTargets(),Q=new Set,Z=new Set,W=async(K)=>{if(Q.has(K.id))return;if(Q.add(K.id),K.fileId)Z.add(K.fileId);try{await x$(K,$)}catch(X){this.reportHookFailure(X)}};for(let K of J.made)if(K.deleteAfterTurn)await W(K);for(let K of J.files){if(K.attachmentId&&J.scoped){let X=await J.scoped.get(K.attachmentId).catch(()=>null);if(X?.deleteAfterTurn)await W(X)}if(K.fileId&&!Z.has(K.fileId)){Z.add(K.fileId);let X=await this.fileOwners.get(K.fileId);if(X?.deleteAfterTurn&&X.owner===J.owner)try{await this.deleteProviderFile(K.fileId)}catch(G){this.reportHookFailure(G)}}}}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 cJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new I){let $=this.voice;if(!$)return j$();let Q=await JJ(J,NJ);if(Q.error)return l(Q);let{sdp:Z,threadId:W,pushToTalk:K}=Q.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return B(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let X=vJ(Q.body,y9),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(U)=>{if(U!==void 0)console.error("[gemi/ai] a voice session could not start.",U);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 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(_){console.error("[gemi/ai] a voice session's onEnd threw.",_)}},H=Y.threadId??G;if(!H)return await N(void 0),B(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(H!==G)await this.authorizeRequest(J,{route:"stream",threadId:H,body:X})}catch(U){throw await N(void 0),U}let C=crypto.randomUUID(),O=Y.tools??[];try{if(Y.mcp)O=[...O,...await P$(Y.mcp,{user:V,sessionId:C})]}catch(U){return await N(U),B(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...Y.session,tools:[...YJ($.delegate),...Y.session?.tools??[],...O.map((U)=>U.tool)],...K===!0?{turnDetection:null}:{}},F;try{F=await $.realtime.createCall({sdp:Z,session:P,safetyIdentifier:Y.safetyIdentifier})}catch(U){await N(U);let _=U instanceof u$&&U.code==="rate_limited";return B(_?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=F.callId;try{await this.voiceStore.create({id:C,callId:F.callId,threadId:H,owner:await this.runOwner(J),body:X,startedAt:z});let{threadId:U,session:_,safetyIdentifier:R,mcp:E,tools:j,...x}=Y;return{sessionId:m.start({...x,tools:O,controller:this.constructor,threadId:H,user:V,body:X,call:{realtime:$.realtime,callId:F.callId},sessionId:C,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:P}).sessionId,sdp:F.sdpAnswer,threadId:H,delegate:$.delegate?.name??VJ,endsAt:z+(Y.limits?.maxDurationMs??900000)}}catch(U){return await N(U),B(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new I){if(!this.voice)return j$();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await JJ(J,NJ);if(Q.error)return l(Q);let Z=vJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return B(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),m.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new I){let $=this.voice;if(!$)return j$();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=m.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 B(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return FJ();return Q}async upload(J=new I){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=S9($.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=R9(await this.attachmentLimits(J),Q,Z,W);if(G)throw new f$(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=null,D=(j)=>this.fileOwners.record(j,{owner:Y,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),...z}),N={body:K,threadId:V},H=await this.checkUpload({name:Z,size:Q.size,mimeType:W},J,N);if(H)throw new f$(H.code||"upload_refused",H.message);let C=await this.attachmentDestination(Q,J,N),O=v9(C,$.get("destination")),P=await this.attachmentScope(J,V,{body:K});z=yJ(await this.attachmentRetention(J,{route:"upload",threadId:V,body:K}),this.turnAttachmentMaxAgeMs);let F=O!=="provider"&&!P;if(F){if(O==="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()`.');h9()}if(O==="provider"||!P){let j=await SZ(this.agent.provider,Q);await D(j);let x={fileId:j,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(F)x.downgraded="no_scope";return x}let U=nZ(),_=await this.attachmentStorage.put({name:oZ(U,Z),body:Q,contentType:W}),R=O==="both"?await SZ(this.agent.provider,Q):void 0;if(R)await D(R);let E={id:U,scopeKey:P.key,fileId:R,objectName:_,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:O,...z};return await this.attachments.put(P,E),{fileId:R,attachmentId:U,name:Z,mimeType:W,size:Q.size,destination:O}}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 f9()}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 h$(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:eZ(Q)});return}case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(lZ(J.error),$);return;default:return}}async readThread(J,$={}){let Z=await($.scope===null||$.scope===void 0?this.store:wZ(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 PZ($,Z),K=W.messages,X=[],G=new Map(W.settled.map((V)=>[V.id,V]));if(p9(K)||Q)try{let V=await UZ(K,{threadId:J,store:g.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolNamed(Y)?.outputSchema,modelOutputFor:(Y,z)=>rZ(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 CZ(g.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??BJ}jobsBlock(J){return e$(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()},K=null){let X=(z)=>K?z.then(()=>this.safely(K)):z,G=Promise.resolve(),V=(async()=>{let z;try{z=await J.result()}catch(N){Z?.close(),await Z?.settled(),G=X(W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:N instanceof Error?N.message:String(N),retryable:!1},$))));return}let D=z.messages;if(Z?.close(D),await Z?.settled(),$.threadId&&D.length>0)try{await this.store.appendMessages($.threadId,D)}catch(N){this.reportHookFailure(N)}G=X(this.notifyRun(z,D,$,W))})(),Y=V.then(()=>u9(Promise.all([G,Q]).then(()=>{}),this.hookHoldMs));return{stored:V,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 w$=["turn","clientRunId","threadId","messages","regenerate"],M9=["text","files","toolResults"];function vJ(J,$=Z8(J)?w$:[...w$,...M9]){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 S9(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new q$("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new q$("The upload's `body` field must be a JSON object.");return vJ($,w$)}class q$ extends gJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function SZ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof aZ&&A9.has(Q.status))throw new Q8(a(Q).message);throw Q}}var A9=new Set([400,413,415,422]);class f$ extends gJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function R9(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 ${AZ($.size)}; the limit is ${AZ(W)}.`};if(K&&K.length>0&&!K.some((X)=>E9(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 E9(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 AZ(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 Q8 extends gJ{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 JJ(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!k9(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 RZ($);let W;try{let X=await T9(Q,$);if(X===null)return RZ($);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 k9(J){return yZ(J)==="application/json"}async function T9(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($J),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 RZ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function b$(J,$,Q){return B(J,{...uJ(bZ(J),Q,J),code:$})}function l(J){if(J.status===413)return b$(413,J.code??"body_too_large",J.error??"");return B(J.status??400,{code:J.code??"invalid_request",message:J.error})}function Z8(J){return Boolean(J.turn)&&typeof J.turn==="object"}function j9(J){let $=Z8(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=x9($.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>EZ)return{error:`turn.localId is longer than ${EZ} characters.`};Q.localId=Z}return{turn:Q}}var EZ=200;function x9(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(bJ))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(bJ))return`${W}.attachmentId is not a gemi attachment id: it must start with "${bJ}".`;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 I9(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 kZ(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function w9(J){let $=g$(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 TZ(){return B(409,{code:"stopped",message:"The turn was stopped before it started."})}function q9(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"||!H9.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 jZ(J){return B(409,{code:J8,message:`Thread ${J} has a run going, and this turn was not to interrupt it.`})}function FJ(){return B(403,uJ("permission","This run belongs to someone else.",403))}function f9(){return B(403,uJ("permission","A file in this turn was uploaded by someone else.",403))}function b9(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 y9=["sdp","threadId","pushToTalk"];function j$(){return B(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function B(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function v9(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 xZ=!1;function h9(){if(xZ)return;xZ=!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 g9=2147483647;function u9(J,$){let Q=J.then(()=>{},()=>{});if(!($<=g9))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var IZ=!1;function c9(J){if(IZ||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof y$))return;IZ=!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 p9(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}function wZ(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 qZ(J,$=!1){if($)return new Response(null,{status:204});return B(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`})}export{r9 as windowMessages,YJ as voiceTools,n9 as turnStarts,_6 as toRealtimeUsage,x8 as toAgentTools,i9 as supportsStrict,o9 as splitTurns,K6 as settleSummaries,l9 as s,h$ as redactError,O6 as parsePartialJson,s9 as messageSize,XJ as measureUsage,P$ as mcpVoiceTools,C$ as liveRuns,zJ as keepSummary,B6 as isCallNotFound,g$ as injectedMessageIds,Q$ as generate,c8 as evalChain,B9 as defineAgentHooks,F$ as defaultVoiceStore,G6 as defaultUsageLimitStore,W6 as defaultSummaryStore,F6 as defaultPromptCacheKey,v$ as defaultNonceStore,_$ as defaultFileOwners,pJ as defaultAttachmentStore,A$ as defaultAgentStore,IJ as VoiceHangup,m as VoiceBridge,d9 as Usage,W$ as ToolNamespace,p as ToolError,P6 as ToolArgumentsTooLongError,V6 as Skill,cJ as ScopedAttachments,z6 as SKILLS_NAMESPACE,S$ as RedisReceiptStore,pZ as RedisNonceStore,U6 as RealtimeSideband,u$ as RealtimeRequestError,L6 as RealtimeClient,a$ as Prompt,mZ as PrismaNonceStore,Y6 as PendingEscalation,M6 as OpenAIProvider,Y$ as OpenAIImageProvider,N$ as MemoryVoiceSessionStore,X6 as MemoryUsageLimitStore,Z6 as MemorySummaryStore,M$ as MemoryReceiptStore,y$ as MemoryNonceStore,wJ as MemoryLiveRuns,qJ as MemoryFileOwners,jJ as MemoryCircuitStore,sZ as MemoryAttachmentStore,HJ as MemoryAgentStore,ZQ as MemoryAgentJobStore,LQ as MEMORY_NAMESPACE,DJ as LiveRunNotFoundError,KQ as JobsRequireThreadError,WQ as JobHandle,m9 as JSONSchemaError,dZ as InvalidAttachmentScopeError,NQ as InMemoryAgentMemoryStore,kJ as ImageRequestError,TJ as ImageProvider,K$ as ImageModel,r as FrameCursorEvictedError,GJ as FallbackProvider,CQ as FakeAgentMemoryStore,RJ as Eval,O$ as DatabaseAgentStore,aJ as DatabaseAgentMemoryStore,oJ as DatabaseAgentJobStore,C6 as DEFAULT_TRANSCRIPTION_MODEL,PQ as DEFAULT_MEMORY_MAX_TOKENS,_Q as DEFAULT_MEMORY_LIMITS,e9 as DEFAULT_MAX_SUMMARY_TOKENS,D6 as DEFAULT_MAX_RUN_DURATION_MS,XQ as DEFAULT_JOB_DEADLINE_MS,BJ as DEFAULT_JOBS_CONTEXT_MAX,VJ as DEFAULT_DELEGATE_NAME,a9 as DEFAULT_CONTEXT_WINDOW_STEP,t9 as DEFAULT_CONTEXT_WINDOW_NOTE,J6 as DEFAULT_COMPACT_TRIGGER_TOKENS,$6 as DEFAULT_COMPACT_INSTRUCTIONS,Q6 as COMPACT_SUMMARY_HEADER,R6 as AzureOpenAIProvider,V$ as AzureOpenAIImageProvider,A6 as AzureAnthropicProvider,iZ as AttachmentNotFoundError,S6 as AnthropicProvider,mJ as AgentTurnError,EJ as AgentTool,H6 as AgentRunError,H$ as AgentProvider,FQ as AgentMemoryRefusedError,OQ as AgentMemoryConflictError,UQ as AgentMemories,g as AgentJobs,nJ as AgentJobDeadlineSweep,GQ as AgentJob,hJ as AgentController,N6 as Agent};
301
301
 
302
- //# debugId=124282E71F1B6B1864756E2164756E21
302
+ //# debugId=9C8414B2FDC4F3F164756E2164756E21