gemi 0.157.0 → 0.160.1

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 (251) hide show
  1. package/dist/ai/Agent.d.ts +231 -55
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +45 -11
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/eval/Eval.d.ts +15 -14
  6. package/dist/ai/eval/Eval.d.ts.map +1 -1
  7. package/dist/ai/generate.d.ts +165 -7
  8. package/dist/ai/generate.d.ts.map +1 -1
  9. package/dist/ai/index.d.ts +5 -5
  10. package/dist/ai/index.d.ts.map +1 -1
  11. package/dist/ai/index.js +11 -11
  12. package/dist/ai/index.js.map +4 -4
  13. package/dist/ai/usageMeter.d.ts +149 -6
  14. package/dist/ai/usageMeter.d.ts.map +1 -1
  15. package/dist/app/index.js +1 -1
  16. package/dist/bin/gemi.js +178 -121
  17. package/dist/bin/gemi.js.map +5 -4
  18. package/dist/bun/plugin.js +1 -1
  19. package/dist/bun/preload.js +1 -1
  20. package/dist/{chunk-0v3bca8k.js → chunk-0b8m1f07.js} +3 -3
  21. package/dist/{chunk-0v3bca8k.js.map → chunk-0b8m1f07.js.map} +1 -1
  22. package/dist/{chunk-zv9d6jkj.js → chunk-0gazmssx.js} +2 -2
  23. package/dist/{chunk-zv9d6jkj.js.map → chunk-0gazmssx.js.map} +1 -1
  24. package/dist/{chunk-xff7tkde.js → chunk-0qernzn1.js} +2 -2
  25. package/dist/{chunk-xff7tkde.js.map → chunk-0qernzn1.js.map} +1 -1
  26. package/dist/chunk-0qrbspbe.js +5 -0
  27. package/dist/{chunk-6np1r9gk.js.map → chunk-0qrbspbe.js.map} +1 -1
  28. package/dist/{chunk-517fjfme.js → chunk-0vb4j7cx.js} +3 -3
  29. package/dist/{chunk-517fjfme.js.map → chunk-0vb4j7cx.js.map} +1 -1
  30. package/dist/{chunk-0yjm936b.js → chunk-191gkynh.js} +3 -3
  31. package/dist/{chunk-0yjm936b.js.map → chunk-191gkynh.js.map} +1 -1
  32. package/dist/chunk-1xxh48bd.js +4 -0
  33. package/dist/{chunk-cmt3jw6j.js.map → chunk-1xxh48bd.js.map} +2 -2
  34. package/dist/chunk-27habdva.js +4 -0
  35. package/dist/{chunk-3ndc8adc.js.map → chunk-27habdva.js.map} +2 -2
  36. package/dist/{chunk-qvngsa1c.js → chunk-2ednvght.js} +2 -2
  37. package/dist/{chunk-qvngsa1c.js.map → chunk-2ednvght.js.map} +1 -1
  38. package/dist/chunk-3cvza61a.js +4 -0
  39. package/dist/{chunk-pw5h5935.js.map → chunk-3cvza61a.js.map} +2 -2
  40. package/dist/{chunk-1de3awrh.js → chunk-3d8jxky6.js} +3 -3
  41. package/dist/{chunk-1de3awrh.js.map → chunk-3d8jxky6.js.map} +1 -1
  42. package/dist/chunk-3vmc6adw.js +4 -0
  43. package/dist/{chunk-z7224rhm.js.map → chunk-3vmc6adw.js.map} +2 -2
  44. package/dist/chunk-44ensgdq.js +10 -0
  45. package/dist/{chunk-set6qmjw.js.map → chunk-44ensgdq.js.map} +3 -3
  46. package/dist/{chunk-7yww9aq7.js → chunk-4670xxae.js} +2 -2
  47. package/dist/{chunk-7yww9aq7.js.map → chunk-4670xxae.js.map} +1 -1
  48. package/dist/{chunk-xtqd9vpp.js → chunk-4vqnv41y.js} +2 -2
  49. package/dist/{chunk-xtqd9vpp.js.map → chunk-4vqnv41y.js.map} +1 -1
  50. package/dist/{chunk-exb35whf.js → chunk-4ye6p5yk.js} +2 -2
  51. package/dist/{chunk-exb35whf.js.map → chunk-4ye6p5yk.js.map} +1 -1
  52. package/dist/{chunk-9md6acv2.js → chunk-57qnqcrp.js} +1 -1
  53. package/dist/{chunk-zcg6m7gf.js → chunk-5c6dfy75.js} +2 -2
  54. package/dist/{chunk-zcg6m7gf.js.map → chunk-5c6dfy75.js.map} +1 -1
  55. package/dist/{chunk-t7yt8egz.js → chunk-5pc21syf.js} +3 -3
  56. package/dist/{chunk-t7yt8egz.js.map → chunk-5pc21syf.js.map} +1 -1
  57. package/dist/{chunk-5zxxd7qp.js → chunk-5qzxyj68.js} +1 -1
  58. package/dist/{chunk-pgdxqrjv.js → chunk-664ewdjv.js} +4 -4
  59. package/dist/{chunk-pgdxqrjv.js.map → chunk-664ewdjv.js.map} +2 -2
  60. package/dist/chunk-6d6p0q3p.js +5 -0
  61. package/dist/{chunk-7zy6nq9e.js.map → chunk-6d6p0q3p.js.map} +2 -2
  62. package/dist/{chunk-k1aw97dm.js → chunk-6ytezxzj.js} +2 -2
  63. package/dist/{chunk-78wht1ph.js.map → chunk-6ytezxzj.js.map} +1 -1
  64. package/dist/{chunk-00z7s34q.js → chunk-79nypedr.js} +2 -2
  65. package/dist/{chunk-00z7s34q.js.map → chunk-79nypedr.js.map} +1 -1
  66. package/dist/{chunk-4vnrnbn3.js → chunk-7bc9ypbk.js} +3 -3
  67. package/dist/{chunk-4vnrnbn3.js.map → chunk-7bc9ypbk.js.map} +1 -1
  68. package/dist/{chunk-wg0ttent.js → chunk-7rfw4h2x.js} +3 -3
  69. package/dist/{chunk-wg0ttent.js.map → chunk-7rfw4h2x.js.map} +1 -1
  70. package/dist/{chunk-rrz2ry81.js → chunk-8m3m5hcf.js} +2 -2
  71. package/dist/{chunk-rrz2ry81.js.map → chunk-8m3m5hcf.js.map} +1 -1
  72. package/dist/{chunk-aq5zx3vg.js → chunk-8tyw6faf.js} +2 -2
  73. package/dist/{chunk-aq5zx3vg.js.map → chunk-8tyw6faf.js.map} +1 -1
  74. package/dist/{chunk-p83cjehh.js → chunk-8z29qvvm.js} +3 -3
  75. package/dist/{chunk-p83cjehh.js.map → chunk-8z29qvvm.js.map} +1 -1
  76. package/dist/{chunk-dhq7zv0t.js → chunk-982x8jps.js} +2 -2
  77. package/dist/{chunk-dhq7zv0t.js.map → chunk-982x8jps.js.map} +1 -1
  78. package/dist/{chunk-38kjpa6q.js → chunk-98byy5m4.js} +1 -1
  79. package/dist/{chunk-986eh0n3.js → chunk-9983zmhx.js} +2 -2
  80. package/dist/{chunk-986eh0n3.js.map → chunk-9983zmhx.js.map} +1 -1
  81. package/dist/{chunk-r5y2khw4.js → chunk-9f2ps5v2.js} +2 -2
  82. package/dist/{chunk-r5y2khw4.js.map → chunk-9f2ps5v2.js.map} +1 -1
  83. package/dist/{chunk-q3e1bqrs.js → chunk-bfj2jafb.js} +3 -3
  84. package/dist/{chunk-q3e1bqrs.js.map → chunk-bfj2jafb.js.map} +1 -1
  85. package/dist/{chunk-0vc2akg0.js → chunk-bqxt1she.js} +1 -1
  86. package/dist/{chunk-159j20yr.js → chunk-bzcfw8qd.js} +2 -2
  87. package/dist/{chunk-159j20yr.js.map → chunk-bzcfw8qd.js.map} +1 -1
  88. package/dist/{chunk-jr9qerbr.js → chunk-cb873vjm.js} +2 -2
  89. package/dist/{chunk-jr9qerbr.js.map → chunk-cb873vjm.js.map} +1 -1
  90. package/dist/{chunk-x82f3q6a.js → chunk-cq16azbw.js} +4 -4
  91. package/dist/{chunk-x82f3q6a.js.map → chunk-cq16azbw.js.map} +1 -1
  92. package/dist/{chunk-72f6pbap.js → chunk-csvffxjh.js} +2 -2
  93. package/dist/{chunk-72f6pbap.js.map → chunk-csvffxjh.js.map} +1 -1
  94. package/dist/chunk-ctrmztan.js +4 -0
  95. package/dist/{chunk-42646nt7.js.map → chunk-ctrmztan.js.map} +2 -2
  96. package/dist/{chunk-4t2j3zcg.js → chunk-d249m2ct.js} +2 -2
  97. package/dist/{chunk-4t2j3zcg.js.map → chunk-d249m2ct.js.map} +2 -2
  98. package/dist/{chunk-h3gcxf2k.js → chunk-day21sfa.js} +3 -3
  99. package/dist/{chunk-h3gcxf2k.js.map → chunk-day21sfa.js.map} +1 -1
  100. package/dist/chunk-dvwfhc5n.js +117 -0
  101. package/dist/{chunk-t66ex43f.js.map → chunk-dvwfhc5n.js.map} +10 -9
  102. package/dist/{chunk-78wht1ph.js → chunk-egwz89ze.js} +2 -2
  103. package/dist/{chunk-k1aw97dm.js.map → chunk-egwz89ze.js.map} +1 -1
  104. package/dist/chunk-fcjjd162.js +4 -0
  105. package/dist/{chunk-jrv31jp9.js.map → chunk-fcjjd162.js.map} +2 -2
  106. package/dist/{chunk-rtv4ax8z.js → chunk-g71ppv6x.js} +2 -2
  107. package/dist/{chunk-rtv4ax8z.js.map → chunk-g71ppv6x.js.map} +1 -1
  108. package/dist/{chunk-56a3vnrj.js → chunk-gmeeyg19.js} +3 -3
  109. package/dist/{chunk-56a3vnrj.js.map → chunk-gmeeyg19.js.map} +1 -1
  110. package/dist/{chunk-yzsyg1f7.js → chunk-j144nwvh.js} +3 -3
  111. package/dist/{chunk-yzsyg1f7.js.map → chunk-j144nwvh.js.map} +1 -1
  112. package/dist/{chunk-q7k2hc45.js → chunk-jarsydtr.js} +3 -3
  113. package/dist/{chunk-q7k2hc45.js.map → chunk-jarsydtr.js.map} +1 -1
  114. package/dist/chunk-k43m5dvs.js +4 -0
  115. package/dist/{chunk-69c2s43a.js.map → chunk-k43m5dvs.js.map} +2 -2
  116. package/dist/chunk-kan3yz82.js +5 -0
  117. package/dist/{chunk-3t4nw1n2.js.map → chunk-kan3yz82.js.map} +2 -2
  118. package/dist/{chunk-ah2jy1vx.js → chunk-m4pkbndk.js} +2 -2
  119. package/dist/{chunk-ah2jy1vx.js.map → chunk-m4pkbndk.js.map} +1 -1
  120. package/dist/{chunk-fe12f946.js → chunk-m73mjzeh.js} +2 -2
  121. package/dist/{chunk-fe12f946.js.map → chunk-m73mjzeh.js.map} +1 -1
  122. package/dist/{chunk-9gt9qdge.js → chunk-m8a80sgn.js} +1 -1
  123. package/dist/chunk-mn9v157z.js +6 -0
  124. package/dist/{chunk-ks9t82g0.js.map → chunk-mn9v157z.js.map} +2 -2
  125. package/dist/{chunk-px3ctjxh.js → chunk-msxhf3m6.js} +2 -2
  126. package/dist/{chunk-px3ctjxh.js.map → chunk-msxhf3m6.js.map} +1 -1
  127. package/dist/chunk-p6nkfcn1.js +5 -0
  128. package/dist/{chunk-kwc68y45.js.map → chunk-p6nkfcn1.js.map} +2 -2
  129. package/dist/{chunk-ss3yn4g2.js → chunk-p9syxzxh.js} +3 -3
  130. package/dist/{chunk-ss3yn4g2.js.map → chunk-p9syxzxh.js.map} +1 -1
  131. package/dist/{chunk-yewj83ez.js → chunk-pyyhmeg1.js} +3 -3
  132. package/dist/{chunk-yewj83ez.js.map → chunk-pyyhmeg1.js.map} +1 -1
  133. package/dist/{chunk-nvhbkqmd.js → chunk-qbsk0jr8.js} +2 -2
  134. package/dist/{chunk-nvhbkqmd.js.map → chunk-qbsk0jr8.js.map} +1 -1
  135. package/dist/{chunk-g5d62d1n.js → chunk-qsbtqh47.js} +2 -2
  136. package/dist/{chunk-g5d62d1n.js.map → chunk-qsbtqh47.js.map} +1 -1
  137. package/dist/{chunk-wnjvfmqc.js → chunk-qz9n2e59.js} +3 -3
  138. package/dist/{chunk-wnjvfmqc.js.map → chunk-qz9n2e59.js.map} +1 -1
  139. package/dist/{chunk-qbvm5q1g.js → chunk-rq3wrwfa.js} +1 -1
  140. package/dist/{chunk-8eyxj78g.js → chunk-ryq2ezgt.js} +3 -3
  141. package/dist/{chunk-8eyxj78g.js.map → chunk-ryq2ezgt.js.map} +1 -1
  142. package/dist/{chunk-v10xzpqs.js → chunk-s0xwqcrf.js} +2 -2
  143. package/dist/{chunk-v10xzpqs.js.map → chunk-s0xwqcrf.js.map} +1 -1
  144. package/dist/{chunk-kbdt84xg.js → chunk-szdbsmq7.js} +2 -2
  145. package/dist/{chunk-kbdt84xg.js.map → chunk-szdbsmq7.js.map} +1 -1
  146. package/dist/{chunk-n95dppzm.js → chunk-tsbxdz4h.js} +2 -2
  147. package/dist/{chunk-n95dppzm.js.map → chunk-tsbxdz4h.js.map} +1 -1
  148. package/dist/chunk-ttvzfwqw.js +41 -0
  149. package/dist/chunk-ttvzfwqw.js.map +28 -0
  150. package/dist/chunk-v0gjdknx.js +4 -0
  151. package/dist/{chunk-7426gfgw.js.map → chunk-v0gjdknx.js.map} +2 -2
  152. package/dist/chunk-v8fx4vgq.js +4 -0
  153. package/dist/{chunk-zfbqgzwa.js.map → chunk-v8fx4vgq.js.map} +2 -2
  154. package/dist/{chunk-dce3w52r.js → chunk-vb73ddwz.js} +3 -3
  155. package/dist/{chunk-dce3w52r.js.map → chunk-vb73ddwz.js.map} +1 -1
  156. package/dist/{chunk-xyyq577r.js → chunk-w0rfypzx.js} +2 -2
  157. package/dist/{chunk-xyyq577r.js.map → chunk-w0rfypzx.js.map} +1 -1
  158. package/dist/{chunk-tr8se94g.js → chunk-weyv3zrt.js} +3 -3
  159. package/dist/{chunk-tr8se94g.js.map → chunk-weyv3zrt.js.map} +1 -1
  160. package/dist/{chunk-9kyfaeey.js → chunk-wtddr3vs.js} +2 -2
  161. package/dist/{chunk-9kyfaeey.js.map → chunk-wtddr3vs.js.map} +1 -1
  162. package/dist/{chunk-tzheb6ak.js → chunk-xp7x27n8.js} +3 -3
  163. package/dist/{chunk-tzheb6ak.js.map → chunk-xp7x27n8.js.map} +1 -1
  164. package/dist/{chunk-ycn7w2e9.js → chunk-yzw2tvqq.js} +2 -2
  165. package/dist/{chunk-ycn7w2e9.js.map → chunk-yzw2tvqq.js.map} +1 -1
  166. package/dist/{chunk-wbv6218d.js → chunk-zz2n9pa5.js} +3 -3
  167. package/dist/{chunk-wbv6218d.js.map → chunk-zz2n9pa5.js.map} +1 -1
  168. package/dist/client/index.js +1 -1
  169. package/dist/client/index.js.map +1 -1
  170. package/dist/config/index.js +1 -1
  171. package/dist/console/run.js +2 -2
  172. package/dist/console/run.js.map +1 -1
  173. package/dist/container/index.js +2 -2
  174. package/dist/container/index.js.map +1 -1
  175. package/dist/database/index.js +2 -2
  176. package/dist/database/index.js.map +1 -1
  177. package/dist/email/index.js +2 -2
  178. package/dist/email/index.js.map +1 -1
  179. package/dist/facades/index.js +2 -2
  180. package/dist/facades/index.js.map +1 -1
  181. package/dist/foundation/index.js +2 -2
  182. package/dist/foundation/index.js.map +1 -1
  183. package/dist/http/ApiRouter.d.ts.map +1 -1
  184. package/dist/http/McpRouter.d.ts +203 -6
  185. package/dist/http/McpRouter.d.ts.map +1 -1
  186. package/dist/http/index.d.ts +1 -1
  187. package/dist/http/index.d.ts.map +1 -1
  188. package/dist/http/index.js +2 -2
  189. package/dist/http/index.js.map +1 -1
  190. package/dist/i18n/dictionaryRuntime.js +2 -2
  191. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  192. package/dist/i18n/index.js +2 -2
  193. package/dist/i18n/index.js.map +1 -1
  194. package/dist/kernel/index.js +2 -2
  195. package/dist/kernel/index.js.map +1 -1
  196. package/dist/orm/index.js +2 -2
  197. package/dist/orm/index.js.map +1 -1
  198. package/dist/probe/index.d.ts +79 -0
  199. package/dist/probe/index.d.ts.map +1 -0
  200. package/dist/probe/index.js +8 -0
  201. package/dist/probe/index.js.map +10 -0
  202. package/dist/server/index.js +2 -2
  203. package/dist/server/index.js.map +1 -1
  204. package/dist/services/image-optimization/ImageManager.d.ts +3 -0
  205. package/dist/services/image-optimization/ImageManager.d.ts.map +1 -1
  206. package/dist/services/image-optimization/config.d.ts +12 -0
  207. package/dist/services/image-optimization/config.d.ts.map +1 -1
  208. package/dist/services/image-optimization/fetchSourceImage.d.ts +37 -0
  209. package/dist/services/image-optimization/fetchSourceImage.d.ts.map +1 -0
  210. package/dist/services/index.d.ts +1 -1
  211. package/dist/services/index.d.ts.map +1 -1
  212. package/dist/services/index.js +9 -9
  213. package/dist/services/index.js.map +3 -3
  214. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  215. package/dist/services/queue/work.js +2 -2
  216. package/dist/services/queue/work.js.map +1 -1
  217. package/dist/services/rate-limiter/drivers/RedisRateLimiterDriver.d.ts +95 -13
  218. package/dist/services/rate-limiter/drivers/RedisRateLimiterDriver.d.ts.map +1 -1
  219. package/dist/services/router/ApiRouteDispatcher.d.ts +12 -0
  220. package/dist/services/router/ApiRouteDispatcher.d.ts.map +1 -1
  221. package/dist/services/router/createFlatApiRoutes.d.ts +10 -0
  222. package/dist/services/router/createFlatApiRoutes.d.ts.map +1 -1
  223. package/dist/stats/route-table.js +1 -1
  224. package/dist/support/index.js +2 -2
  225. package/dist/support/index.js.map +1 -1
  226. package/dist/vitest/index.js +1 -1
  227. package/package.json +2 -1
  228. package/dist/chunk-3ndc8adc.js +0 -4
  229. package/dist/chunk-3t4nw1n2.js +0 -5
  230. package/dist/chunk-42646nt7.js +0 -4
  231. package/dist/chunk-69c2s43a.js +0 -4
  232. package/dist/chunk-6np1r9gk.js +0 -5
  233. package/dist/chunk-7426gfgw.js +0 -4
  234. package/dist/chunk-7zy6nq9e.js +0 -5
  235. package/dist/chunk-cmt3jw6j.js +0 -4
  236. package/dist/chunk-jrv31jp9.js +0 -4
  237. package/dist/chunk-ks9t82g0.js +0 -6
  238. package/dist/chunk-kwc68y45.js +0 -5
  239. package/dist/chunk-pw5h5935.js +0 -4
  240. package/dist/chunk-set6qmjw.js +0 -10
  241. package/dist/chunk-t66ex43f.js +0 -117
  242. package/dist/chunk-xp5axyb5.js +0 -30
  243. package/dist/chunk-xp5axyb5.js.map +0 -28
  244. package/dist/chunk-z7224rhm.js +0 -4
  245. package/dist/chunk-zfbqgzwa.js +0 -4
  246. /package/dist/{chunk-9md6acv2.js.map → chunk-57qnqcrp.js.map} +0 -0
  247. /package/dist/{chunk-5zxxd7qp.js.map → chunk-5qzxyj68.js.map} +0 -0
  248. /package/dist/{chunk-38kjpa6q.js.map → chunk-98byy5m4.js.map} +0 -0
  249. /package/dist/{chunk-0vc2akg0.js.map → chunk-bqxt1she.js.map} +0 -0
  250. /package/dist/{chunk-9gt9qdge.js.map → chunk-m8a80sgn.js.map} +0 -0
  251. /package/dist/{chunk-qbvm5q1g.js.map → chunk-rq3wrwfa.js.map} +0 -0
package/dist/ai/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{$c as v0,Ac as U$,Bc as S$,Cc as C$,Dc as _$,Ec as M$,Fc as A$,Gc as R$,Hc as T$,Ic as E$,Jc as j$,Kc as k$,Lc as q$,Nc as w,Oc as a$,Pc as n,Qc as E,Rc as J$,Sc as E0,Tc as j0,Uc as k0,Vc as q0,Wc as x0,Xb as tQ,Xc as I0,Yb as Z9,Yc as w0,Zb as W9,Zc as b0,_b as rQ,_c as f0,ad as y0,bc as TJ,bd as mQ,cc as S,cd as h0,dc as A,dd as z9,ec as ZJ,ed as g0,fc as i$,fd as u0,gc as g,gd as MJ,hc as eQ,hd as VQ,ic as K9,id as c0,jc as X9,jd as m0,kc as G9,kd as p0,lc as m,ld as l0,mc as Y9,md as d0,nc as lJ,nd as GQ,oc as V9,pc as H9,qc as dJ,rc as F$,sc as P$,uc as B$,vc as v,wc as h8,xc as g8,yc as N$}from"../chunk-xp5axyb5.js";import{Fd as G$}from"../chunk-9kyfaeey.js";import"../chunk-0yjm936b.js";import{Ah as r8,Bi as Q9,Dh as J9,Ei as gQ,Ii as $9,Th as N8,Uh as A0,Vh as R0,Wh as T0,Xh as x}from"../chunk-0v3bca8k.js";import{Ji as e8,Li as mJ,Mi as pJ}from"../chunk-xyyq577r.js";import{Vi as h}from"../chunk-159j20yr.js";import"../chunk-aq5zx3vg.js";import"../chunk-n95dppzm.js";import"../chunk-zcg6m7gf.js";import{Yj as LJ,Zj as OJ,lk as D$}from"../chunk-yzsyg1f7.js";import"../chunk-fe12f946.js";import{_k as j8}from"../chunk-tzheb6ak.js";import"../chunk-rtv4ax8z.js";import"../chunk-7yww9aq7.js";import"../chunk-nvhbkqmd.js";import"../chunk-78wht1ph.js";import{readFileSync as L9}from"fs";import{isAbsolute as O9,join as nJ}from"path";var C9=/\{\{>\s*([\w./-]+)\s*\}\}/g,Z$=/\{\{(\w+)\}\}/g,_9=/^[\w-]+(\/[\w-]+)*$/,W$={dir:"app/agents",shared:"prompts"},PJ={},oJ=new Map;function K$(){return PJ.cache??Bun.env.NODE_ENV==="production"}function M9(J){if(!_9.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=PJ.dir??W$.dir,$=O9(Q)?Q:nJ(process.cwd(),Q),Z=J.includes("/")?`${J}.md`:nJ(PJ.shared??W$.shared,`${J}.md`);return nJ($,Z)}function S9(J){let Q=M9(J),$=K$()?oJ.get(Q):void 0;if($!==void 0)return $;let Z;try{Z=L9(Q,"utf8").replace(/\r?\n$/,"")}catch(W){if(W.code==="ENOENT")throw Error(`The prompt "${J}" does not exist (looked for ${Q}).`);throw W}if(K$())oJ.set(Q,Z);return Z}function sJ(J,Q){if(Q.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...Q,J].join(" > ")}.`);return S9(J).replace(C9,($,Z)=>sJ(Z,[...Q,J]))}class X${static configure(J){PJ={...J},oJ.clear()}static render(J,Q={}){return sJ(J,[]).replace(Z$,($,Z)=>{if(!Object.hasOwn(Q,Z))throw Error(`The prompt "${J}" has no value for {{${Z}}}.`);return String(Q[Z])})}static placeholders(J){let Q=[...sJ(J,[]).matchAll(Z$)].map(($)=>$[1]);return[...new Set(Q)]}}class aJ extends G${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await v.sweep({limit:100})===100);}}var BJ=20;function V$(J,Q){if(Q<=0||J.length===0)return null;let $=(K,X)=>X.createdAt-K.createdAt||(K.id<X.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>K.state==="running").sort($),...J.filter((K)=>K.state!=="running").sort($)].slice(0,Q).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="running")X.push(`running since ${tJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${tJ(K.settledAt??K.updatedAt)}`);else{let Y=K.error?`${K.error.code}: ${Y$(K.error.message,200)}`:"failed";X.push(`failed at ${tJ(K.settledAt??K.updatedAt)} (${Y})`)}if(K.summary!==void 0)X.push(`summary: ${Y$(JSON.stringify(K.summary),300)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
3
- `)}function tJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function Y$(J,Q){return J.length<=Q?J:`${J.slice(0,Q-1)}\u2026`}class eJ{table;sql;dialect;connection;constructor(J,Q={}){let $=Q.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The agent jobs table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);this.table=$,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of A9(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return D$(this.sql,()=>J(),{connection:this.connection})}async create(J){let Q=this.q(),$=this.clock(Q);await Q`
2
+ import{$c as b0,Ac as u8,Bc as N$,Dc as O$,Ec as S$,Fc as C$,Gc as _$,Hc as M$,Ic as A$,Jc as R$,Kc as T$,Lc as E$,Mc as j$,Nc as k$,Oc as q$,Qc as w,Rc as t$,Sc as n,Tc as E,Uc as J$,Vc as j0,Wc as k0,Xb as tQ,Xc as q0,Yb as W9,Yc as x0,Zb as K9,Zc as I0,_b as rQ,_c as w0,ad as f0,bc as TJ,bd as v0,cc as S,cd as y0,dc as A,dd as h0,ed as mQ,fc as n$,fd as g0,gc as c$,gd as D9,hc as ZJ,hd as u0,ic as E0,id as c0,jc as g,jd as MJ,kc as eQ,kd as VQ,lc as X9,ld as m0,mc as G9,md as p0,nc as Y9,nd as l0,oc as m,od as d0,pc as V9,pd as i0,qc as lJ,qd as GQ,rc as H9,sc as z9,tc as dJ,uc as F$,vc as P$,xc as B$,yc as v,zc as g8}from"../chunk-ttvzfwqw.js";import{Id as G$}from"../chunk-wtddr3vs.js";import"../chunk-191gkynh.js";import{Dh as e8,Ei as $9,Gh as Q9,Hi as gQ,Li as Z9,Wh as O8,Xh as A0,Yh as R0,Zh as T0,_h as x}from"../chunk-0b8m1f07.js";import{Mi as J9,Oi as mJ,Pi as pJ}from"../chunk-w0rfypzx.js";import{Yi as h}from"../chunk-bzcfw8qd.js";import"../chunk-8tyw6faf.js";import"../chunk-tsbxdz4h.js";import"../chunk-5c6dfy75.js";import{$j as LJ,ak as UJ,ok as D$}from"../chunk-j144nwvh.js";import"../chunk-m73mjzeh.js";import{bl as k8}from"../chunk-xp7x27n8.js";import"../chunk-g71ppv6x.js";import"../chunk-4670xxae.js";import"../chunk-qbsk0jr8.js";import"../chunk-egwz89ze.js";import{readFileSync as U9}from"fs";import{isAbsolute as C9,join as nJ}from"path";var _9=/\{\{>\s*([\w./-]+)\s*\}\}/g,Z$=/\{\{(\w+)\}\}/g,M9=/^[\w-]+(\/[\w-]+)*$/,W$={dir:"app/agents",shared:"prompts"},PJ={},oJ=new Map;function K$(){return PJ.cache??Bun.env.NODE_ENV==="production"}function S9(J){if(!M9.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=PJ.dir??W$.dir,$=C9(Q)?Q:nJ(process.cwd(),Q),Z=J.includes("/")?`${J}.md`:nJ(PJ.shared??W$.shared,`${J}.md`);return nJ($,Z)}function A9(J){let Q=S9(J),$=K$()?oJ.get(Q):void 0;if($!==void 0)return $;let Z;try{Z=U9(Q,"utf8").replace(/\r?\n$/,"")}catch(W){if(W.code==="ENOENT")throw Error(`The prompt "${J}" does not exist (looked for ${Q}).`);throw W}if(K$())oJ.set(Q,Z);return Z}function sJ(J,Q){if(Q.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...Q,J].join(" > ")}.`);return A9(J).replace(_9,($,Z)=>sJ(Z,[...Q,J]))}class X${static configure(J){PJ={...J},oJ.clear()}static render(J,Q={}){return sJ(J,[]).replace(Z$,($,Z)=>{if(!Object.hasOwn(Q,Z))throw Error(`The prompt "${J}" has no value for {{${Z}}}.`);return String(Q[Z])})}static placeholders(J){let Q=[...sJ(J,[]).matchAll(Z$)].map(($)=>$[1]);return[...new Set(Q)]}}class aJ extends G${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await v.sweep({limit:100})===100);}}var BJ=20;function V$(J,Q){if(Q<=0||J.length===0)return null;let $=(K,X)=>X.createdAt-K.createdAt||(K.id<X.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>K.state==="running").sort($),...J.filter((K)=>K.state!=="running").sort($)].slice(0,Q).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="running")X.push(`running since ${tJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${tJ(K.settledAt??K.updatedAt)}`);else{let Y=K.error?`${K.error.code}: ${Y$(K.error.message,200)}`:"failed";X.push(`failed at ${tJ(K.settledAt??K.updatedAt)} (${Y})`)}if(K.summary!==void 0)X.push(`summary: ${Y$(JSON.stringify(K.summary),300)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
3
+ `)}function tJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function Y$(J,Q){return J.length<=Q?J:`${J.slice(0,Q-1)}\u2026`}class eJ{table;sql;dialect;connection;constructor(J,Q={}){let $=Q.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The agent jobs table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);this.table=$,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of R9(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return D$(this.sql,()=>J(),{connection:this.connection})}async create(J){let Q=this.q(),$=this.clock(Q);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)
@@ -28,7 +28,7 @@ import{$c as v0,Ac as U$,Bc as S$,Cc as C$,Dc as _$,Ec as M$,Fc as A$,Gc as R$,H
28
28
  `).map(rJ)}async now(){let J=this.q(),[Q]=await J`SELECT ${this.clock(J)} AS now`;return Number(Q.now)}async prune(J){let Q=this.q(),$=await Q`
29
29
  DELETE FROM ${this.name(Q)}
30
30
  WHERE state <> 'running' AND settled_at <= ${this.clock(Q)} - ${this.ms(Q,J)}
31
- `;return z$($)}joinable(){if(this.connection===void 0)return;let J=LJ();if(J===void 0||OJ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,Q){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${Q}\``:`"${Q}"`)}name(J){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${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,Q){let $=Math.max(0,Math.round(Q));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${$} AS SIGNED)`:J`CAST(${$} AS BIGINT)`}}function H$(J,Q){return Q.map(($)=>J`${$}`).reduce(($,Z)=>J`${$}, ${Z}`)}function NJ(J){return J===void 0?null:JSON.stringify(J)}function UJ(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function rJ(J){let Q=UJ(J.summary),$=UJ(J.output),Z=UJ(J.error),W=UJ(J.usage);return{id:String(J.id),threadId:String(J.thread_id),runId:String(J.run_id),toolCallId:String(J.tool_call_id),toolName:String(J.tool_name),owner:J.owner===null||J.owner===void 0?null:String(J.owner),job:J.job===null||J.job===void 0?null:String(J.job),...Q!==void 0?{summary:Q}:{},state:String(J.state),...$!==void 0?{output:$}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number(J.orphaned)===1?{orphaned:!0}:{},attachmentScope:J.attachment_scope===null||J.attachment_scope===void 0?null:String(J.attachment_scope),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),deadlineAt:Number(J.deadline_at),...J.settled_at===null||J.settled_at===void 0?{}:{settledAt:Number(J.settled_at)}}}function z$(J){let Q=J;return Math.max(Number(Q.count??0),Number(Q.affectedRows??0))}function A9(J,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Q}\` (
31
+ `;return z$($)}joinable(){if(this.connection===void 0)return;let J=LJ();if(J===void 0||UJ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,Q){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${Q}\``:`"${Q}"`)}name(J){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${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,Q){let $=Math.max(0,Math.round(Q));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${$} AS SIGNED)`:J`CAST(${$} AS BIGINT)`}}function H$(J,Q){return Q.map(($)=>J`${$}`).reduce(($,Z)=>J`${$}, ${Z}`)}function NJ(J){return J===void 0?null:JSON.stringify(J)}function OJ(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function rJ(J){let Q=OJ(J.summary),$=OJ(J.output),Z=OJ(J.error),W=OJ(J.usage);return{id:String(J.id),threadId:String(J.thread_id),runId:String(J.run_id),toolCallId:String(J.tool_call_id),toolName:String(J.tool_name),owner:J.owner===null||J.owner===void 0?null:String(J.owner),job:J.job===null||J.job===void 0?null:String(J.job),...Q!==void 0?{summary:Q}:{},state:String(J.state),...$!==void 0?{output:$}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number(J.orphaned)===1?{orphaned:!0}:{},attachmentScope:J.attachment_scope===null||J.attachment_scope===void 0?null:String(J.attachment_scope),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),deadlineAt:Number(J.deadline_at),...J.settled_at===null||J.settled_at===void 0?{}:{settledAt:Number(J.settled_at)}}}function z$(J){let Q=J;return Math.max(Number(Q.count??0),Number(Q.affectedRows??0))}function R9(J,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Q}\` (
32
32
  \`id\` VARCHAR(191) NOT NULL,
33
33
  \`thread_id\` VARCHAR(191) NOT NULL,
34
34
  \`run_id\` VARCHAR(191) NOT NULL,
@@ -72,7 +72,7 @@ import{$c as v0,Ac as U$,Bc as S$,Cc as C$,Dc as _$,Ec as M$,Fc as A$,Gc as R$,H
72
72
  "updated_at" BIGINT NOT NULL,
73
73
  "deadline_at" BIGINT NOT NULL,
74
74
  "settled_at" BIGINT${Z}
75
- )`,`CREATE INDEX IF NOT EXISTS "${Q}_thread_id_created_at_idx" ON "${Q}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_state_deadline_at_idx" ON "${Q}"("state", "deadline_at")`]}var L$=4;class QQ{table;sql;dialect;connection;constructor(J,Q={}){let $=Q.table??"gemi_agent_memories";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The agent memories table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);this.table=$,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of R9(this.dialect,this.table))await this.sql.unsafe(J)}async list(J,Q={}){if(J.length===0)return[];if(Q.kinds!==void 0&&Q.kinds.length===0)return[];let $=this.q(),Z=[$`scope IN (${JJ($,J)})`];if(Q.kinds!==void 0)Z.push($`kind IN (${JJ($,Q.kinds)})`);if(!Q.includeExpired)Z.push($`(expires_at IS NULL OR expires_at > ${this.clock($)})`);if(Q.after!==void 0){let[V]=await $`
75
+ )`,`CREATE INDEX IF NOT EXISTS "${Q}_thread_id_created_at_idx" ON "${Q}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_state_deadline_at_idx" ON "${Q}"("state", "deadline_at")`]}var L$=4;class QQ{table;sql;dialect;connection;constructor(J,Q={}){let $=Q.table??"gemi_agent_memories";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The agent memories table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);this.table=$,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of T9(this.dialect,this.table))await this.sql.unsafe(J)}async list(J,Q={}){if(J.length===0)return[];if(Q.kinds!==void 0&&Q.kinds.length===0)return[];let $=this.q(),Z=[$`scope IN (${JJ($,J)})`];if(Q.kinds!==void 0)Z.push($`kind IN (${JJ($,Q.kinds)})`);if(!Q.includeExpired)Z.push($`(expires_at IS NULL OR expires_at > ${this.clock($)})`);if(Q.after!==void 0){let[V]=await $`
76
76
  SELECT created_at, id FROM ${this.name($)}
77
77
  WHERE id = ${Q.after} AND scope IN (${JJ($,J)})
78
78
  `;if(V){let G=this.ms($,Number(V.created_at));Z.push($`(created_at > ${G} OR (created_at = ${G} AND id > ${String(V.id)}))`)}}let W=Z.reduce((V,G)=>$`${V} AND ${G}`),K=Q.limit===void 0||Q.tags!==void 0?void 0:Math.max(0,Math.floor(Q.limit)),Y=(K===void 0?await $`
@@ -102,7 +102,7 @@ import{$c as v0,Ac as U$,Bc as S$,Cc as C$,Dc as _$,Ec as M$,Fc as A$,Gc as R$,H
102
102
  ${W===null?null:this.ms($,W)})
103
103
  `}async atKey(J,Q){let $=this.q(),Z=await $`
104
104
  SELECT * FROM ${this.name($)} WHERE scope = ${J} AND ${this.column($,"key")} = ${Q}
105
- `;return Z[0]?JQ(Z[0]):null}async mustGet(J){let Q=await this.get(J);if(!Q)throw Error(`The memory ${J} was not found after it was written.`);return Q}joinable(){if(this.connection===void 0)return;let J=LJ();if(J===void 0||OJ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,Q){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${Q}\``:`"${Q}"`)}name(J){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${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,Q){let $=Math.max(0,Math.round(Q));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${$} AS SIGNED)`:J`CAST(${$} AS BIGINT)`}}function JJ(J,Q){return Q.map(($)=>J`${$}`).reduce(($,Z)=>J`${$}, ${Z}`)}function O$(J,Q){if(J===null||J===void 0||J==="")return Q;try{return JSON.parse(String(J))}catch{return Q}}function JQ(J){let Q=O$(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(Q)?Q.map(String):[],pinned:Number(J.pinned)===1,source:O$(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 CJ(J){let Q=J;return Math.max(Number(Q.count??0),Number(Q.affectedRows??0))}function R9(J,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Q}\` (
105
+ `;return Z[0]?JQ(Z[0]):null}async mustGet(J){let Q=await this.get(J);if(!Q)throw Error(`The memory ${J} was not found after it was written.`);return Q}joinable(){if(this.connection===void 0)return;let J=LJ();if(J===void 0||UJ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,Q){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${Q}\``:`"${Q}"`)}name(J){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${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,Q){let $=Math.max(0,Math.round(Q));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${$} AS SIGNED)`:J`CAST(${$} AS BIGINT)`}}function JJ(J,Q){return Q.map(($)=>J`${$}`).reduce(($,Z)=>J`${$}, ${Z}`)}function U$(J,Q){if(J===null||J===void 0||J==="")return Q;try{return JSON.parse(String(J))}catch{return Q}}function JQ(J){let Q=U$(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(Q)?Q.map(String):[],pinned:Number(J.pinned)===1,source:U$(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 CJ(J){let Q=J;return Math.max(Number(Q.count??0),Number(Q.affectedRows??0))}function T9(J,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Q}\` (
106
106
  \`id\` VARCHAR(191) NOT NULL,
107
107
  \`scope\` VARCHAR(191) NOT NULL,
108
108
  \`kind\` VARCHAR(191) NOT NULL,
@@ -139,18 +139,18 @@ import{$c as v0,Ac as U$,Bc as S$,Cc as C$,Dc as _$,Ec as M$,Fc as A$,Gc as R$,H
139
139
  "updated_at" BIGINT NOT NULL,
140
140
  "last_used_at" BIGINT,
141
141
  "expires_at" BIGINT${Z}
142
- )`,`CREATE INDEX IF NOT EXISTS "${Q}_scope_kind_created_at_idx" ON "${Q}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_expires_at_idx" ON "${Q}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_scope_key_key" ON "${Q}"("scope", "key")`]}var I$={n:0,mean:0,stddev:0,low:null,high:null};function y(J){let Q=[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))-y(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($)}function x$(J,Q,$){let W=1,K=1-(J+Q)*$/(J+1);if(Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let X=K;for(let Y=1;Y<=300;Y++){let V=2*Y,G=Y*(Q-Y)*$/((J+V-1)*(J+V));if(K=1+G*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+G/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(K=1/K,X*=K*W,G=-(J+Y)*(J+Q+Y)*$/((J+V)*(J+V+1)),K=1+G*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+G/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let H=K*W;if(X*=H,Math.abs(H-1)<0.00000000000001)break}return X}function T9(J,Q,$){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(y(Q+$)-y(Q)-y($)+Q*Math.log(J)+$*Math.log(1-J));return J<(Q+1)/(Q+$+2)?Z*x$(Q,$,J)/Q:1-Z*x$($,Q,1-J)/$}function $Q(J,Q){return T9(Q/(Q+J*J),Q/2,0.5)}function E9(J){if(!(J>0))return Number.POSITIVE_INFINITY;let Q=1.959964,$=2;while($Q($,J)>0.05)$*=2;for(let Z=0;Z<100;Z++){let W=(Q+$)/2;if($Q(W,J)>0.05)Q=W;else $=W}return(Q+$)/2}function j9(J,Q,$,Z){let W=J+$,K=Q+Z,X=(H,D)=>y(H+1)-y(D+1)-y(H-D+1),Y=(H)=>Math.exp(X(Q,H)+X(Z,W-H)-X(K,W)),V=Y(J),G=0;for(let H=Math.max(0,W-Z);H<=Math.min(Q,W);H++){let D=Y(H);if(D<=V*1.0000001)G+=D}return Math.min(1,G)}function w$(J,Q){if(J.length<2)return 0;let $=J.reduce((W,K)=>W+(K-Q)**2,0),Z=Math.sqrt($/(J.length-1));return Z<0.000000000001*Math.max(1,Math.abs(Q))?0:Z}function ZQ(J){let Q=J.length;if(Q===0)return I$;let $=J.map((Y)=>Y?1:0),Z=$.reduce((Y,V)=>Y+V,0)/Q,W=3.841458881296,K=(Z+W/(2*Q))/(1+W/Q),X=1.959964*Math.sqrt(Z*(1-Z)/Q+W/(4*Q*Q))/(1+W/Q);return{n:Q,mean:Z,stddev:w$($,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function WQ(J){let Q=J.length;if(Q===0)return I$;let $=J.reduce((K,X)=>K+X,0)/Q,Z=w$(J,$);if(Q<2||Z===0)return{n:Q,mean:$,stddev:Z,low:null,high:null};let W=E9(Q-1)*Z/Math.sqrt(Q);return{n:Q,mean:$,stddev:Z,low:$-W,high:$+W}}function QJ(J,Q,$){return{before:J.mean,after:Q.mean,delta:Q.mean-J.mean,p:$,pAdjusted:$,significant:!1}}function b$(J,Q){if(J.n===0||Q.n===0)return QJ(J,Q,null);let $=(Z)=>Math.round(Z.mean*Z.n);return QJ(J,Q,j9($(J),J.n,$(Q),Q.n))}function f$(J,Q){if(J.n<2||Q.n<2)return QJ(J,Q,null);let $=J.stddev**2/J.n,Z=Q.stddev**2/Q.n,W=Math.sqrt($+Z);if(W===0)return QJ(J,Q,null);let K=($+Z)**2/($**2/(J.n-1)+Z**2/(Q.n-1));return QJ(J,Q,$Q((Q.mean-J.mean)/W,K))}function v$(J,Q,$){if($==="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<Q&&Z.delta!==0}class _J{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:(Q)=>_J.judge(Q)}):J.graders,this.pricing=J.pricing}static create(J){let Q=`The eval "${J.name}"`;$J(J.runs,Q,"runs"),$J(J.concurrency,Q,"concurrency");let $=new Set;for(let W of J.cases){if($.has(W.id))throw Error(`${Q} has two cases with the id "${W.id}".`);$.add(W.id)}let Z=new _J(J);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")$J(K.samples,`${Q}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,Q,$={}){return c$(J,Q,$)}static format(J,Q={}){return w9(J,Q)}async run(J={}){let Q=`${this.name}.run`;$J(J.runs,Q,"runs"),$J(J.concurrency,Q,"concurrency");let $=J.only?new Set(J.only):null;if($){let P=[...$].filter((B)=>!this.cases.some((L)=>L.id===B));if(P.length>0)throw Error(`The eval "${this.name}" has no case ${P.map((B)=>`"${B}"`).join(", ")}.`)}let Z=J.runs??this.runs,W=Date.now(),K=new AbortController,X=J.signal?AbortSignal.any([J.signal,K.signal]):K.signal,Y=this.cases.filter((P)=>!$||$.has(P.id)),V={};for(let[P,B]of Object.entries(this.graders)){if(X.aborted)break;if(typeof B==="function"||B.kind!=="judge"||!B.calibration)continue;V[P]=await this.calibrate(B,X)}let G=Y.flatMap((P)=>Array.from({length:Z},(B,L)=>({test:P,run:L+1}))),H=Array.from({length:G.length}),D=0,z,F=async()=>{while(D<G.length&&!X.aborted){let P=D++,B=G[P],L=await this.sample(B.test,B.run,X,J.keepOutputs??!1);H[P]=L;try{J.onSample?.(L)}catch(O){z??={error:O},K.abort(O)}}},U=Math.min(J.concurrency??this.concurrency,G.length);if(await Promise.all(Array.from({length:U},F)),z)throw z.error;let N=H.filter((P)=>P!==void 0);return this.report(N,V,Z,new Date(W).toISOString(),Date.now()-W,{aborted:X.aborted||N.length<G.length,planned:Y.map((P)=>P.id)})}async sample(J,Q,$,Z){let W=Date.now(),K,X,Y=await ZJ(async()=>{try{K=await this.task(J.input,{case:J,run:Q,signal:$})}catch(U){X=p$(U)}}),V={},G=!1,H=await ZJ(async()=>{if(X!==void 0)return;let U={case:J,input:J.input,run:Q};for(let[N,P]of Object.entries(this.graders)){if(J.skip?.includes(N))continue;let B=await y$(P,K,U,$);if(!B)continue;if(V[N]=B,!B.pass&&typeof P!=="function"&&P.gate)G=!0}}),D=Object.values(V).map((U)=>U.score),z=X===void 0&&D.length===0,F=this.pricing?KQ(this.pricing,Y.byModel).cost+KQ(this.pricing,H.byModel).cost:void 0;return{case:J.id,run:Q,pass:X===void 0&&!z&&Object.values(V).every((U)=>U.pass),excluded:G||z,...z?{ungraded:!0}:{},score:X!==void 0||z?0:m$(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:Y.usage,byModel:x9(Y.byModel,H.byModel),judgeUsage:H.usage,...F!==void 0?{cost:F}:{},durationMs:Date.now()-W}}async calibrate(J,Q){let $=J.calibration,Z=[],W=0,K=await ZJ(async()=>{for(let[V,G]of $.examples.entries()){if(Q.aborted)break;let H=G.id??`example-${V+1}`,D={case:{id:H,input:G.input},input:G.input,run:0},z=await y$(J,G.output,D,Q),F=z?.pass??!1;if(F===G.expected)W++;else Z.push({id:H,expected:G.expected,got:F,...z?.note?{note:z.note}:{}})}}),X=$.examples.length,Y=X===0?1:W/X;return{n:X,agreement:Y,ok:Y>=($.minAgreement??0.8),disagreements:Z,usage:K.usage}}report(J,Q,$,Z,W,K){let X=new Set(Object.entries(this.graders).filter(([,z])=>typeof z!=="function"&&z.gate).map(([z])=>z)),Y={};for(let z of this.cases){let F=J.filter((U)=>U.case===z.id);if(F.length===0)continue;Y[z.id]={...h$(F),graders:g$(F,X)}}let V=S(),G=S(),H={};for(let z of J){V=A(V,z.usage),G=A(G,z.judgeUsage);for(let[F,U]of Object.entries(z.byModel))H[F]=A(H[F]??S(),U)}let D=this.pricing?KQ(this.pricing,H):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:$,aborted:K.aborted,planned:K.planned,samples:J,cases:Y,graders:g$(J,X),calibration:Q,totals:{...h$(J),usage:V,judgeUsage:G,byModel:H,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(H)}}}}async function y$(J,Q,$,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return XQ(await J(Q,$),W);if(J.kind!=="judge")return XQ(await J.check(Q,$),W);return await k9(J,Q,$,W,Z)}catch(K){return{pass:!1,score:0,error:p$(K)}}}async function k9(J,Q,$,Z,W){let K=await J.prompt(Q,$),X=typeof K==="string"?{prompt:K}:K,Y=[];for(let D=0;D<(J.samples??1)&&!W.aborted;D++){let z=await GQ({signal:W,provider:J.provider,...J.instructions!==void 0?{instructions:J.instructions}:{},...X,output:J.output,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},...J.maxOutputTokens!==void 0?{maxOutputTokens:J.maxOutputTokens}:{},...J.temperature!==void 0?{temperature:J.temperature}:{},logErrors:!1});if(!z.ok){Y.push({pass:!1,score:0,error:`The judge failed: ${z.error.message}`});continue}let F=XQ(J.verdict(z.output,$),Z);if(F)Y.push(F)}if(Y.length===0)return null;if(Y.length===1)return Y[0];let V=Y.filter((D)=>D.pass).length,G=Y.map((D)=>D.note??D.error).filter(Boolean),H=Y.map((D)=>D.error).filter(Boolean);return{pass:V*2>Y.length,score:m$(Y.map((D)=>D.score)),...G.length>0?{note:G.join(" | ")}:{},...H.length===Y.length?{error:H.join(" | ")}:{}}}function XQ(J,Q){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 $=u$(J);return{pass:$>=Q,score:$}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:u$(J.score),...J.note!==void 0?{note:J.note}:{}}}function h$(J){let Q=J.filter(($)=>!$.excluded);return{samples:J.length,kept:Q.length,passed:Q.filter(($)=>$.pass).length,errors:J.filter(($)=>$.error!==void 0).length,passRate:ZQ(Q.map(($)=>$.pass)),score:WQ(Q.map(($)=>$.score))}}function g$(J,Q){let $=J.filter((W)=>!W.excluded),Z=[...new Set(J.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let X=(Q.has(W)?J:$).flatMap((Y)=>Y.grades[W]?[Y.grades[W]]:[]);return[W,{passRate:ZQ(X.map((Y)=>Y.pass)),score:WQ(X.map((Y)=>Y.score))}]}))}function q9(J,Q){if(J[Q])return J[Q];let $=Object.keys(J).filter((Z)=>Q.startsWith(Z)).sort((Z,W)=>W.length-Z.length)[0];return $?J[$]:void 0}function KQ(J,Q){let $=0,Z=[];for(let[W,K]of Object.entries(Q)){let X=q9(J,W);if(!X){Z.push(W);continue}let Y=K.cachedInputTokens??0,V=K.imageInputTokens??0,G=K.imageOutputTokens??0;$+=((K.inputTokens-Y-V)*X.input+Y*(X.cachedInput??X.input)+V*(X.imageInput??X.input)+(K.outputTokens-G)*X.output+G*(X.imageOutput??X.output))/1e6}return{cost:$,unpriced:Z}}function x9(...J){let Q={};for(let $ of J)for(let[Z,W]of Object.entries($))Q[Z]=A(Q[Z]??S(),W);return Q}function c$(J,Q,$){for(let[P,B]of[["baseline",J],["current report",Q]])if(B.aborted)throw Error(`Eval.compare: the ${P} for "${B.name}" was aborted (${B.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`);let Z=$.alpha??0.05,W=$.adjust??"holm",K=[],X=(P,B,L)=>{let O={label:P,passRate:b$(B.passRate,L.passRate),score:f$(B.score,L.score)};return K.push(O),{passRate:O.passRate,score:O.score}},Y=(P,B,L)=>Object.fromEntries(Object.keys(L).filter((O)=>(O in B)).map((O)=>[O,X(`${P} ${O}`,B[O],L[O])])),V=(P,B)=>({fromCurrent:P.filter((L)=>!B.includes(L)),fromBaseline:B.filter((L)=>!P.includes(L))}),G=X("total",J.totals,Q.totals),H=Y("case",J.cases,Q.cases),D=Y("grader",J.graders,Q.graders),z=K.flatMap((P)=>[P.passRate,P.score]);v$(z,Z,W);let F={cases:V([...new Set([...J.planned??[],...Object.keys(J.cases)])],[...new Set([...Q.planned??[],...Object.keys(Q.cases)])]),graders:V(Object.keys(J.graders),Object.keys(Q.graders))},U=[...F.cases.fromCurrent.map((P)=>`case ${P}: in the baseline, missing from this report`),...F.graders.fromCurrent.map((P)=>`grader ${P}: in the baseline, missing from this report`)],N=[];for(let P of K)for(let[B,L]of[["pass rate",P.passRate],["score",P.score]]){if(!L.significant)continue;let O=`${P.label}: ${B} ${L.before.toFixed(2)} \u2192 ${L.after.toFixed(2)} (p = ${I9(L.pAdjusted)})`;(L.delta<0?U:N).push(O)}return{totals:G,cases:H,graders:D,missing:F,comparisons:z.filter((P)=>P.p!==null).length,alpha:Z,adjust:W,regressions:U,improvements:N}}function I9(J){return J<0.001?"<0.001":J.toFixed(3)}function w9(J,Q){let $=Q.baseline&&!Q.baseline.aborted&&!J.aborted?c$(Q.baseline,J,Q):void 0,{totals:Z}=J,W=[];if(W.push(`eval ${J.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(J.durationMs/1000).toFixed(1)}s)`),J.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let K=(G)=>{if(G.n===0)return"-";let H=G.mean.toFixed(2);if(G.low===null||G.high===null)return`${H} (${G.n===1?"n=1":"no spread"})`;return`${H} [${G.low.toFixed(2)}, ${G.high.toFixed(2)}]`},X=(G)=>G?` ${G.delta>=0?"+":""}${G.delta.toFixed(2)}${G.significant?"*":""}`:"",Y=(G,H)=>{let D=[0,1,2,3].map((F)=>Math.max(...[[G,"n","pass rate","score"],...H].map((U)=>U[F].length))),z=(F)=>F.map((U,N)=>U.padEnd(D[N])).join(" ").trimEnd();W.push("",z([G,"n","pass rate","score"]),...H.map(z))};Y("case",Object.entries(J.cases).map(([G,H])=>[G,`${H.kept}/${H.samples}`,K(H.passRate)+X($?.cases[G]?.passRate),K(H.score)+X($?.cases[G]?.score)])),Y("grader",Object.entries(J.graders).map(([G,H])=>[G,String(H.passRate.n),K(H.passRate)+X($?.graders[G]?.passRate),K(H.score)+X($?.graders[G]?.score)])),W.push("",`total pass rate ${K(Z.passRate)}${X($?.totals.passRate)} score ${K(Z.score)}${X($?.totals.score)}`);for(let[G,H]of Object.entries(J.calibration))W.push(`judge ${G}: agreement ${H.agreement.toFixed(2)} on ${H.n} examples${H.ok?"":" (BELOW minAgreement)"}`);let V=(G)=>`${G.inputTokens} in, ${G.outputTokens} out`;if(W.push(`tokens: task ${V(Z.usage)}; judges ${V(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),$){W.push("",`* significant at ${$.alpha} over ${$.comparisons} tests (${$.adjust==="holm"?"Holm-adjusted":"unadjusted"}; Fisher's exact for pass rates, Welch's t for scores)`);for(let G of $.regressions)W.push(`regression: ${G}`);for(let G of $.improvements)W.push(`improvement: ${G}`)}return W.join(`
143
- `)}function m$(J){return J.reduce((Q,$)=>Q+$,0)/J.length}function u$(J){return Math.min(1,Math.max(0,J))}function p$(J){return J instanceof Error?J.message:String(J)}function $J(J,Q,$){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${Q} sets \`${$}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var b9=/^[A-Za-z0-9_-]{1,64}$/;function f9(J,Q){let $=v9(Q)?Q:{filter:Q},Z=$.deferred===!0,W=J.descriptors($.filter);if(!$.namespaces)return W.map((H)=>YQ(J,H,Z));let K=Object.entries($.namespaces),X=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,D]of K){if(!b9.test(H))throw Error(`toAgentTools: "${H}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!X.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let Y=new Map(K.map(([H])=>[H,[]])),V=[];for(let H of W){let D=K.find(([z])=>H.tags.includes(z))?.[0];if(D===void 0)V.push(YQ(J,H,Z));else Y.get(D).push(YQ(J,H,!1))}let G=[];for(let[H,D]of K){let z=Y.get(H);if(z.length===0)continue;G.push(VQ.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...G,...V]}function v9(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function YQ(J,Q,$){if(Q.kind==="tool")return y9(J,Q,$);return MJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,execute:(Z,W)=>{let K=h.getStore()?.req;if(!K)throw new g(`"${Q.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},Q.name,Z,W)}})}function y9(J,Q,$){let Z=J.nativeTool(Q.name);return MJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:J.nativeApproval(Q.name),deferred:$,...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,Q.name,W,K)}})}function h9(J){if(J==="auto")return;let Q=/^(\d+)x(\d+)$/.exec(J);if(!Q)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let $=Number(Q[1]),Z=Number(Q[2]);if($%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($/Z,Z/$)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function l$(J,Q){if(J.size!==void 0)try{h9(J.size)}catch($){throw Error(`${Q}: ${$.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${Q}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let $=J.compression;if(!Number.isInteger($)||$<0||$>100)throw Error(`${Q}: compression is an integer from 0 to 100; got ${$}.`)}}function d$(J,Q){if(J instanceof File)return J;let $=J.type||"image/png",Z=$==="image/jpeg"?"jpg":$.split("/")[1]??"png";return new File([J],`${Q}.${Z}`,{type:$})}class HQ{name;provider;settings;constructor(J){let{name:Q,provider:$,...Z}=J;l$(Z,`ImageModel "${Q}"`),this.name=Q,this.provider=$,this.settings=Z}static create(J){return new HQ(J)}async generate(J){let Q=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...Q,signal:J.signal}))}async edit(J){let Q=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...Q,images:J.images.map(($,Z)=>d$($,`image-${Z}`)),...J.mask?{mask:d$(J.mask,"mask")}:{},signal:J.signal}))}present(J){return i$(this.provider.model,J.usage),g9(J)}merge(J){let Q={...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 l$(Q,`ImageModel "${this.name}"`),Q}}function g9(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function u(J){return typeof process>"u"?void 0:process.env?.[J]}var u9="preview";function n$(J){let Q=J.trim().replace(/\/+$/,"");if(!Q)return"";return`${Q.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function c9(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function WJ(J,Q={}){return{base:(J.baseURL??u("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??u("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function o$(J){let Q=J.baseURL??J.endpoint??u("AZURE_OPENAI_ENDPOINT");if(Q)return n$(Q);let $=J.resourceName??u("AZURE_OPENAI_RESOURCE_NAME")??u("AZURE_RESOURCE_NAME");return $?n$(`https://${$.trim()}.cognitiveservices.azure.com`):""}function KJ(J,Q={}){let $=J.apiVersion??u("AZURE_OPENAI_API_VERSION")??u9;return{base:`${o$(J)}${c9($)}`,query:`?api-version=${encodeURIComponent($)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??u("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function s$(J,Q={}){return{...KJ(J,Q),base:`${o$(J)}/v1`,query:""}}var m9=500,t$=20000;function p9(J,Q){if(!J)return;let $=J.trim();if(/^\d+(\.\d+)?$/.test($))return Math.max(0,Number($)*1000);let Z=Date.parse($);if(Number.isNaN(Z))return;return Math.max(0,Z-Q)}function SJ(J,Q){let $=Math.min(t$,m9*2**J);return Math.round($*(0.5+Q()*0.5))}function l9(J){return J===429||J===408||J===409||J>=500}function d9(J,Q){return l9(J)&&E(Q).retryable}function r$(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function e$(J,Q){return new Promise(($,Z)=>{let W=setTimeout($,J);Q?.addEventListener("abort",()=>{clearTimeout(W),Z(r$(Q))},{once:!0})})}async function zQ(J,Q,$=e$){if(!Q)return await $(J);Q.throwIfAborted();let Z;try{await Promise.race([$(J,Q),new Promise((W,K)=>{Z=()=>K(r$(Q)),Q.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)Q.removeEventListener("abort",Z)}}async function c(J,Q,$){let Z=$.fetchImpl??((H,D)=>fetch(H,D)),W=$.sleep??e$,K=$.random??Math.random,X=$.now??Date.now,Y=Math.max(0,$.maxRetries),V=(H)=>zQ(H,$.signal,W),G;for(let H=0;H<=Y;H++){$.signal?.throwIfAborted();let D=new AbortController,z=()=>D.abort($.signal?.reason);$.signal?.addEventListener("abort",z,{once:!0});let F=!1,U=$.timeoutMs>0?setTimeout(()=>{F=!0,D.abort()},$.timeoutMs):void 0,N;try{N=await Z(J,{...Q,signal:D.signal})}catch(O){if(U!==void 0)clearTimeout(U);if($.signal?.removeEventListener("abort",z),$.signal?.aborted)throw O;if(G=F?new a$($.timeoutMs):O,F&&$.retryTimeouts===!1)throw G;if(H===Y)throw G;await V(SJ(H,K));continue}if(U!==void 0)clearTimeout(U);if(N.ok)return N;$.signal?.removeEventListener("abort",z);let P=await i9(N),B=new w(N.status,P,N.headers.get("x-request-id")??void 0,p9(N.headers.get("retry-after"),X()));if(H===Y||!d9(N.status,B))throw B;let L=B.retryAfter??(N.status===429?E(B).retryAfter:void 0);await V(L===void 0?SJ(H,K):Math.min(L,t$)),G=B}throw G??Error("Provider request failed with no response.")}async function i9(J){let Q;try{Q=await J.text()}catch{return null}try{return JSON.parse(Q)}catch{return Q}}var DQ=300000;function FQ(J){return{generationsUrl:`${J.base}/images/generations${J.query}`,editsUrl:`${J.base}/images/edits${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}class AJ extends Error{code;retryable;retryAfter;constructor(J,Q={}){super(J.message,Q);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var n9={png:"image/png",jpeg:"image/jpeg"};function o9(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,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 s9(J){let Q=atob(J),$=new Uint8Array(Q.length);for(let Z=0;Z<Q.length;Z++)$[Z]=Q.charCodeAt(Z);return $}function a9(J){let $=J?.data?.[0]?.b64_json;if(typeof $!=="string"||$.length===0)throw new AJ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof J.output_format==="string"?J.output_format:"png";return{bytes:s9($),mimeType:n9[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:o9(J.usage)}}async function J8(J,Q,$,Z){let W;try{W=await c(J,Q,{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(K){if(Z.signal?.aborted)throw K;throw new AJ(E(K),{cause:K})}return a9(await W.json())}async function Q8(J,Q,$={}){return await J8(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Q)},J,$)}async function $8(J,Q,$={}){return await J8(J.editsUrl,{method:"POST",headers:await J.headers(),body:Q},J,$)}class RJ{static models(){return[]}modelName(){return this.model}async generate(J){return await Q8(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let Q=new FormData;for(let[$,Z]of Object.entries(this.body(J)))if(Z!==void 0)Q.set($,String(Z));for(let $ of J.images)Q.append("image[]",$,$.name);if(J.mask)Q.set("mask",J.mask,J.mask.name);return await $8(this.endpoint(),Q,{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 E(J)}}var Z8=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class PQ extends RJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new PQ(J,Q)}static models(){return Z8}endpoint(){return FQ(WJ(this.config,{timeoutMs:DQ}))}}class BQ extends RJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new BQ(J,Q)}static models(){return Z8}modelName(){return this.config.deployment??this.model}endpoint(){return FQ(KJ(this.config,{timeoutMs:DQ}))}}var X8=3;function NQ(J){let Q=new Map;for(let $ of J)for(let Z of $.content??[]){if(Z.type!=="file"||!Z.fileId||Q.has(Z.fileId))continue;Q.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return Q}function G8(J,Q,$=new Map){if(!(Q instanceof w))return[];if(Q.status!==400&&Q.status!==404)return[];let Z=r9(Q.body);if(!Z)return[];let W=t9(J.input);if(W.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let G=J.input[Number(K[1])],H=LQ(G)[Number(K[2])],D=H&&typeof H.file_id==="string"?H.file_id:void 0;if(D)return[D]}let X=Z.message??"",Y=K8(W.map((G)=>G.fileId).filter((G)=>e9(X,G)));if(Y.length>0)return Y;let V=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(X);if(V){let G=V[1].toLowerCase()==="image type"?"input_image":"input_file",H=V[2].toLowerCase(),D=K8(W.filter((F)=>F.type===G).map((F)=>F.fileId)),z=D.filter((F)=>($.get(F)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(z.length===1)return z;if(z.length===0&&D.length===1)return D}return[]}function Y8(J,Q,$=new Map){return{...J,input:J.input.map((Z)=>{let W=LQ(Z);if(!W.some((K)=>W8(K,Q)))return Z;return{...Z,content:W.map((K)=>W8(K,Q)?{type:"input_text",text:UQ($.get(String(K.file_id))?.name)}:K)}})}}function UQ(J){return`[${J?`attachment ${JSON.stringify(J)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function W8(J,Q){return typeof J.file_id==="string"&&Q.has(J.file_id)}function LQ(J){let Q=J?.content;return Array.isArray(Q)?Q:[]}function t9(J){let Q=[];for(let $ of J)for(let Z of LQ($))if(typeof Z.file_id==="string"&&Z.file_id)Q.push({type:String(Z.type),fileId:Z.file_id});return Q}function r9(J){if(!J||typeof J!=="object")return null;let Q=J,$=Q.error&&typeof Q.error==="object"?Q.error:J;return{message:typeof $.message==="string"?$.message:void 0,param:typeof $.param==="string"?$.param:void 0}}function e9(J,Q){let $=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${$}($|[^A-Za-z0-9_-])`).test(J)}function K8(J){return[...new Set(J)]}async function*JZ(J){let Q="",$="",Z=[],W,K=()=>{if(Z.length===0&&!$)return null;let V={event:$,data:Z.join(`
142
+ )`,`CREATE INDEX IF NOT EXISTS "${Q}_scope_kind_created_at_idx" ON "${Q}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_expires_at_idx" ON "${Q}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_scope_key_key" ON "${Q}"("scope", "key")`]}var I$={n:0,mean:0,stddev:0,low:null,high:null};function y(J){let Q=[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))-y(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($)}function x$(J,Q,$){let W=1,K=1-(J+Q)*$/(J+1);if(Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let X=K;for(let Y=1;Y<=300;Y++){let V=2*Y,G=Y*(Q-Y)*$/((J+V-1)*(J+V));if(K=1+G*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+G/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(K=1/K,X*=K*W,G=-(J+Y)*(J+Q+Y)*$/((J+V)*(J+V+1)),K=1+G*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+G/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let H=K*W;if(X*=H,Math.abs(H-1)<0.00000000000001)break}return X}function E9(J,Q,$){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(y(Q+$)-y(Q)-y($)+Q*Math.log(J)+$*Math.log(1-J));return J<(Q+1)/(Q+$+2)?Z*x$(Q,$,J)/Q:1-Z*x$($,Q,1-J)/$}function $Q(J,Q){return E9(Q/(Q+J*J),Q/2,0.5)}function j9(J){if(!(J>0))return Number.POSITIVE_INFINITY;let Q=1.959964,$=2;while($Q($,J)>0.05)$*=2;for(let Z=0;Z<100;Z++){let W=(Q+$)/2;if($Q(W,J)>0.05)Q=W;else $=W}return(Q+$)/2}function k9(J,Q,$,Z){let W=J+$,K=Q+Z,X=(H,D)=>y(H+1)-y(D+1)-y(H-D+1),Y=(H)=>Math.exp(X(Q,H)+X(Z,W-H)-X(K,W)),V=Y(J),G=0;for(let H=Math.max(0,W-Z);H<=Math.min(Q,W);H++){let D=Y(H);if(D<=V*1.0000001)G+=D}return Math.min(1,G)}function w$(J,Q){if(J.length<2)return 0;let $=J.reduce((W,K)=>W+(K-Q)**2,0),Z=Math.sqrt($/(J.length-1));return Z<0.000000000001*Math.max(1,Math.abs(Q))?0:Z}function ZQ(J){let Q=J.length;if(Q===0)return I$;let $=J.map((Y)=>Y?1:0),Z=$.reduce((Y,V)=>Y+V,0)/Q,W=3.841458881296,K=(Z+W/(2*Q))/(1+W/Q),X=1.959964*Math.sqrt(Z*(1-Z)/Q+W/(4*Q*Q))/(1+W/Q);return{n:Q,mean:Z,stddev:w$($,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function WQ(J){let Q=J.length;if(Q===0)return I$;let $=J.reduce((K,X)=>K+X,0)/Q,Z=w$(J,$);if(Q<2||Z===0)return{n:Q,mean:$,stddev:Z,low:null,high:null};let W=j9(Q-1)*Z/Math.sqrt(Q);return{n:Q,mean:$,stddev:Z,low:$-W,high:$+W}}function QJ(J,Q,$){return{before:J.mean,after:Q.mean,delta:Q.mean-J.mean,p:$,pAdjusted:$,significant:!1}}function b$(J,Q){if(J.n===0||Q.n===0)return QJ(J,Q,null);let $=(Z)=>Math.round(Z.mean*Z.n);return QJ(J,Q,k9($(J),J.n,$(Q),Q.n))}function f$(J,Q){if(J.n<2||Q.n<2)return QJ(J,Q,null);let $=J.stddev**2/J.n,Z=Q.stddev**2/Q.n,W=Math.sqrt($+Z);if(W===0)return QJ(J,Q,null);let K=($+Z)**2/($**2/(J.n-1)+Z**2/(Q.n-1));return QJ(J,Q,$Q((Q.mean-J.mean)/W,K))}function v$(J,Q,$){if($==="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<Q&&Z.delta!==0}class _J{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:(Q)=>_J.judge(Q)}):J.graders,this.pricing=J.pricing}static create(J){let Q=`The eval "${J.name}"`;$J(J.runs,Q,"runs"),$J(J.concurrency,Q,"concurrency");let $=new Set;for(let W of J.cases){if($.has(W.id))throw Error(`${Q} has two cases with the id "${W.id}".`);$.add(W.id)}let Z=new _J(J);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")$J(K.samples,`${Q}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,Q,$={}){return m$(J,Q,$)}static format(J,Q={}){return w9(J,Q)}async run(J={}){let Q=`${this.name}.run`;$J(J.runs,Q,"runs"),$J(J.concurrency,Q,"concurrency");let $=J.only?new Set(J.only):null;if($){let P=[...$].filter((B)=>!this.cases.some((L)=>L.id===B));if(P.length>0)throw Error(`The eval "${this.name}" has no case ${P.map((B)=>`"${B}"`).join(", ")}.`)}let Z=J.runs??this.runs,W=Date.now(),K=new AbortController,X=J.signal?AbortSignal.any([J.signal,K.signal]):K.signal,Y=this.cases.filter((P)=>!$||$.has(P.id)),V={};for(let[P,B]of Object.entries(this.graders)){if(X.aborted)break;if(typeof B==="function"||B.kind!=="judge"||!B.calibration)continue;V[P]=await this.calibrate(B,X)}let G=Y.flatMap((P)=>Array.from({length:Z},(B,L)=>({test:P,run:L+1}))),H=Array.from({length:G.length}),D=0,z,F=async()=>{while(D<G.length&&!X.aborted){let P=D++,B=G[P],L=await this.sample(B.test,B.run,X,J.keepOutputs??!1);H[P]=L;try{J.onSample?.(L)}catch(U){z??={error:U},K.abort(U)}}},O=Math.min(J.concurrency??this.concurrency,G.length);if(await Promise.all(Array.from({length:O},F)),z)throw z.error;let N=H.filter((P)=>P!==void 0);return this.report(N,V,Z,new Date(W).toISOString(),Date.now()-W,{aborted:X.aborted||N.length<G.length,planned:Y.map((P)=>P.id)})}async sample(J,Q,$,Z){let W=Date.now(),K,X,Y=await ZJ(async()=>{try{K=await this.task(J.input,{case:J,run:Q,signal:$})}catch(O){X=l$(O)}}),V={},G=!1,H=await ZJ(async()=>{if(X!==void 0)return;let O={case:J,input:J.input,run:Q};for(let[N,P]of Object.entries(this.graders)){if(J.skip?.includes(N))continue;let B=await y$(P,K,O,$);if(!B)continue;if(V[N]=B,!B.pass&&typeof P!=="function"&&P.gate)G=!0}}),D=Object.values(V).map((O)=>O.score),z=X===void 0&&D.length===0,F=this.pricing?KQ(this.pricing,Y.byModel).cost+KQ(this.pricing,H.byModel).cost:void 0;return{case:J.id,run:Q,pass:X===void 0&&!z&&Object.values(V).every((O)=>O.pass),excluded:G||z,...z?{ungraded:!0}:{},score:X!==void 0||z?0:p$(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:Y.usage,byModel:x9(Y.byModel,H.byModel),judgeUsage:H.usage,...F!==void 0?{cost:F}:{},durationMs:Date.now()-W}}async calibrate(J,Q){let $=J.calibration,Z=[],W=0,K=await ZJ(async()=>{for(let[V,G]of $.examples.entries()){if(Q.aborted)break;let H=G.id??`example-${V+1}`,D={case:{id:H,input:G.input},input:G.input,run:0},z=await y$(J,G.output,D,Q),F=z?.pass??!1;if(F===G.expected)W++;else Z.push({id:H,expected:G.expected,got:F,...z?.note?{note:z.note}:{}})}}),X=$.examples.length,Y=X===0?1:W/X;return{n:X,agreement:Y,ok:Y>=($.minAgreement??0.8),disagreements:Z,usage:K.usage}}report(J,Q,$,Z,W,K){let X=new Set(Object.entries(this.graders).filter(([,z])=>typeof z!=="function"&&z.gate).map(([z])=>z)),Y={};for(let z of this.cases){let F=J.filter((O)=>O.case===z.id);if(F.length===0)continue;Y[z.id]={...h$(F),graders:g$(F,X)}}let V=S(),G=S(),H={};for(let z of J){V=A(V,z.usage),G=A(G,z.judgeUsage);for(let[F,O]of Object.entries(z.byModel))H[F]=A(H[F]??S(),O)}let D=this.pricing?KQ(this.pricing,H):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:$,aborted:K.aborted,planned:K.planned,samples:J,cases:Y,graders:g$(J,X),calibration:Q,totals:{...h$(J),usage:V,judgeUsage:G,byModel:H,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(H)}}}}async function y$(J,Q,$,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return XQ(await J(Q,$),W);if(J.kind!=="judge")return XQ(await J.check(Q,$),W);return await q9(J,Q,$,W,Z)}catch(K){return{pass:!1,score:0,error:l$(K)}}}async function q9(J,Q,$,Z,W){let K=await J.prompt(Q,$),X=typeof K==="string"?{prompt:K}:K,Y=[];for(let D=0;D<(J.samples??1)&&!W.aborted;D++){let z=await GQ({signal:W,provider:J.provider,...J.instructions!==void 0?{instructions:J.instructions}:{},...X,output:J.output,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},...J.maxOutputTokens!==void 0?{maxOutputTokens:J.maxOutputTokens}:{},...J.temperature!==void 0?{temperature:J.temperature}:{},logErrors:!1});if(!z.ok){Y.push({pass:!1,score:0,error:`The judge failed: ${z.error.message}`});continue}let F=XQ(J.verdict(z.output,$),Z);if(F)Y.push(F)}if(Y.length===0)return null;if(Y.length===1)return Y[0];let V=Y.filter((D)=>D.pass).length,G=Y.map((D)=>D.note??D.error).filter(Boolean),H=Y.map((D)=>D.error).filter(Boolean);return{pass:V*2>Y.length,score:p$(Y.map((D)=>D.score)),...G.length>0?{note:G.join(" | ")}:{},...H.length===Y.length?{error:H.join(" | ")}:{}}}function XQ(J,Q){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 $=u$(J);return{pass:$>=Q,score:$}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:u$(J.score),...J.note!==void 0?{note:J.note}:{}}}function h$(J){let Q=J.filter(($)=>!$.excluded);return{samples:J.length,kept:Q.length,passed:Q.filter(($)=>$.pass).length,errors:J.filter(($)=>$.error!==void 0).length,passRate:ZQ(Q.map(($)=>$.pass)),score:WQ(Q.map(($)=>$.score))}}function g$(J,Q){let $=J.filter((W)=>!W.excluded),Z=[...new Set(J.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let X=(Q.has(W)?J:$).flatMap((Y)=>Y.grades[W]?[Y.grades[W]]:[]);return[W,{passRate:ZQ(X.map((Y)=>Y.pass)),score:WQ(X.map((Y)=>Y.score))}]}))}function KQ(J,Q){let $=0,Z=[];for(let[W,K]of Object.entries(Q)){let X=c$(J,W,K);if(X===void 0){Z.push(W);continue}$+=X}return{cost:$,unpriced:Z}}function x9(...J){let Q={};for(let $ of J)for(let[Z,W]of Object.entries($))Q[Z]=A(Q[Z]??S(),W);return Q}function m$(J,Q,$){for(let[P,B]of[["baseline",J],["current report",Q]])if(B.aborted)throw Error(`Eval.compare: the ${P} for "${B.name}" was aborted (${B.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`);let Z=$.alpha??0.05,W=$.adjust??"holm",K=[],X=(P,B,L)=>{let U={label:P,passRate:b$(B.passRate,L.passRate),score:f$(B.score,L.score)};return K.push(U),{passRate:U.passRate,score:U.score}},Y=(P,B,L)=>Object.fromEntries(Object.keys(L).filter((U)=>(U in B)).map((U)=>[U,X(`${P} ${U}`,B[U],L[U])])),V=(P,B)=>({fromCurrent:P.filter((L)=>!B.includes(L)),fromBaseline:B.filter((L)=>!P.includes(L))}),G=X("total",J.totals,Q.totals),H=Y("case",J.cases,Q.cases),D=Y("grader",J.graders,Q.graders),z=K.flatMap((P)=>[P.passRate,P.score]);v$(z,Z,W);let F={cases:V([...new Set([...J.planned??[],...Object.keys(J.cases)])],[...new Set([...Q.planned??[],...Object.keys(Q.cases)])]),graders:V(Object.keys(J.graders),Object.keys(Q.graders))},O=[...F.cases.fromCurrent.map((P)=>`case ${P}: in the baseline, missing from this report`),...F.graders.fromCurrent.map((P)=>`grader ${P}: in the baseline, missing from this report`)],N=[];for(let P of K)for(let[B,L]of[["pass rate",P.passRate],["score",P.score]]){if(!L.significant)continue;let U=`${P.label}: ${B} ${L.before.toFixed(2)} \u2192 ${L.after.toFixed(2)} (p = ${I9(L.pAdjusted)})`;(L.delta<0?O:N).push(U)}return{totals:G,cases:H,graders:D,missing:F,comparisons:z.filter((P)=>P.p!==null).length,alpha:Z,adjust:W,regressions:O,improvements:N}}function I9(J){return J<0.001?"<0.001":J.toFixed(3)}function w9(J,Q){let $=Q.baseline&&!Q.baseline.aborted&&!J.aborted?m$(Q.baseline,J,Q):void 0,{totals:Z}=J,W=[];if(W.push(`eval ${J.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(J.durationMs/1000).toFixed(1)}s)`),J.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let K=(G)=>{if(G.n===0)return"-";let H=G.mean.toFixed(2);if(G.low===null||G.high===null)return`${H} (${G.n===1?"n=1":"no spread"})`;return`${H} [${G.low.toFixed(2)}, ${G.high.toFixed(2)}]`},X=(G)=>G?` ${G.delta>=0?"+":""}${G.delta.toFixed(2)}${G.significant?"*":""}`:"",Y=(G,H)=>{let D=[0,1,2,3].map((F)=>Math.max(...[[G,"n","pass rate","score"],...H].map((O)=>O[F].length))),z=(F)=>F.map((O,N)=>O.padEnd(D[N])).join(" ").trimEnd();W.push("",z([G,"n","pass rate","score"]),...H.map(z))};Y("case",Object.entries(J.cases).map(([G,H])=>[G,`${H.kept}/${H.samples}`,K(H.passRate)+X($?.cases[G]?.passRate),K(H.score)+X($?.cases[G]?.score)])),Y("grader",Object.entries(J.graders).map(([G,H])=>[G,String(H.passRate.n),K(H.passRate)+X($?.graders[G]?.passRate),K(H.score)+X($?.graders[G]?.score)])),W.push("",`total pass rate ${K(Z.passRate)}${X($?.totals.passRate)} score ${K(Z.score)}${X($?.totals.score)}`);for(let[G,H]of Object.entries(J.calibration))W.push(`judge ${G}: agreement ${H.agreement.toFixed(2)} on ${H.n} examples${H.ok?"":" (BELOW minAgreement)"}`);let V=(G)=>`${G.inputTokens} in, ${G.outputTokens} out`;if(W.push(`tokens: task ${V(Z.usage)}; judges ${V(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),$){W.push("",`* significant at ${$.alpha} over ${$.comparisons} tests (${$.adjust==="holm"?"Holm-adjusted":"unadjusted"}; Fisher's exact for pass rates, Welch's t for scores)`);for(let G of $.regressions)W.push(`regression: ${G}`);for(let G of $.improvements)W.push(`improvement: ${G}`)}return W.join(`
143
+ `)}function p$(J){return J.reduce((Q,$)=>Q+$,0)/J.length}function u$(J){return Math.min(1,Math.max(0,J))}function l$(J){return J instanceof Error?J.message:String(J)}function $J(J,Q,$){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${Q} sets \`${$}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var b9=/^[A-Za-z0-9_-]{1,64}$/;function f9(J,Q){let $=v9(Q)?Q:{filter:Q},Z=$.deferred===!0,W=J.descriptors($.filter);if(!$.namespaces)return W.map((H)=>YQ(J,H,Z));let K=Object.entries($.namespaces),X=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,D]of K){if(!b9.test(H))throw Error(`toAgentTools: "${H}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!X.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let Y=new Map(K.map(([H])=>[H,[]])),V=[];for(let H of W){let D=K.find(([z])=>H.tags.includes(z))?.[0];if(D===void 0)V.push(YQ(J,H,Z));else Y.get(D).push(YQ(J,H,!1))}let G=[];for(let[H,D]of K){let z=Y.get(H);if(z.length===0)continue;G.push(VQ.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...G,...V]}function v9(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function YQ(J,Q,$){if(Q.kind==="tool")return y9(J,Q,$);return MJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,execute:(Z,W)=>{let K=h.getStore()?.req;if(!K)throw new g(`"${Q.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},Q.name,Z,W)}})}function y9(J,Q,$){let Z=J.nativeTool(Q.name);return MJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:J.nativeApproval(Q.name),deferred:$,...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,Q.name,W,K)}})}function h9(J){if(J==="auto")return;let Q=/^(\d+)x(\d+)$/.exec(J);if(!Q)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let $=Number(Q[1]),Z=Number(Q[2]);if($%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($/Z,Z/$)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function d$(J,Q){if(J.size!==void 0)try{h9(J.size)}catch($){throw Error(`${Q}: ${$.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${Q}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let $=J.compression;if(!Number.isInteger($)||$<0||$>100)throw Error(`${Q}: compression is an integer from 0 to 100; got ${$}.`)}}function i$(J,Q){if(J instanceof File)return J;let $=J.type||"image/png",Z=$==="image/jpeg"?"jpg":$.split("/")[1]??"png";return new File([J],`${Q}.${Z}`,{type:$})}class HQ{name;provider;settings;constructor(J){let{name:Q,provider:$,...Z}=J;d$(Z,`ImageModel "${Q}"`),this.name=Q,this.provider=$,this.settings=Z}static create(J){return new HQ(J)}async generate(J){let Q=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...Q,signal:J.signal}))}async edit(J){let Q=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...Q,images:J.images.map(($,Z)=>i$($,`image-${Z}`)),...J.mask?{mask:i$(J.mask,"mask")}:{},signal:J.signal}))}present(J){return n$(this.provider.model,J.usage),g9(J)}merge(J){let Q={...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 d$(Q,`ImageModel "${this.name}"`),Q}}function g9(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function u(J){return typeof process>"u"?void 0:process.env?.[J]}var u9="preview";function o$(J){let Q=J.trim().replace(/\/+$/,"");if(!Q)return"";return`${Q.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function c9(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function WJ(J,Q={}){return{base:(J.baseURL??u("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??u("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function s$(J){let Q=J.baseURL??J.endpoint??u("AZURE_OPENAI_ENDPOINT");if(Q)return o$(Q);let $=J.resourceName??u("AZURE_OPENAI_RESOURCE_NAME")??u("AZURE_RESOURCE_NAME");return $?o$(`https://${$.trim()}.cognitiveservices.azure.com`):""}function KJ(J,Q={}){let $=J.apiVersion??u("AZURE_OPENAI_API_VERSION")??u9;return{base:`${s$(J)}${c9($)}`,query:`?api-version=${encodeURIComponent($)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??u("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function a$(J,Q={}){return{...KJ(J,Q),base:`${s$(J)}/v1`,query:""}}var m9=500,r$=20000;function p9(J,Q){if(!J)return;let $=J.trim();if(/^\d+(\.\d+)?$/.test($))return Math.max(0,Number($)*1000);let Z=Date.parse($);if(Number.isNaN(Z))return;return Math.max(0,Z-Q)}function SJ(J,Q){let $=Math.min(r$,m9*2**J);return Math.round($*(0.5+Q()*0.5))}function l9(J){return J===429||J===408||J===409||J>=500}function d9(J,Q){return l9(J)&&E(Q).retryable}function e$(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function J8(J,Q){return new Promise(($,Z)=>{let W=setTimeout($,J);Q?.addEventListener("abort",()=>{clearTimeout(W),Z(e$(Q))},{once:!0})})}async function zQ(J,Q,$=J8){if(!Q)return await $(J);Q.throwIfAborted();let Z;try{await Promise.race([$(J,Q),new Promise((W,K)=>{Z=()=>K(e$(Q)),Q.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)Q.removeEventListener("abort",Z)}}async function c(J,Q,$){let Z=$.fetchImpl??((H,D)=>fetch(H,D)),W=$.sleep??J8,K=$.random??Math.random,X=$.now??Date.now,Y=Math.max(0,$.maxRetries),V=(H)=>zQ(H,$.signal,W),G;for(let H=0;H<=Y;H++){$.signal?.throwIfAborted();let D=new AbortController,z=()=>D.abort($.signal?.reason);$.signal?.addEventListener("abort",z,{once:!0});let F=!1,O=$.timeoutMs>0?setTimeout(()=>{F=!0,D.abort()},$.timeoutMs):void 0,N;try{N=await Z(J,{...Q,signal:D.signal})}catch(U){if(O!==void 0)clearTimeout(O);if($.signal?.removeEventListener("abort",z),$.signal?.aborted)throw U;if(G=F?new t$($.timeoutMs):U,F&&$.retryTimeouts===!1)throw G;if(H===Y)throw G;await V(SJ(H,K));continue}if(O!==void 0)clearTimeout(O);if(N.ok)return N;$.signal?.removeEventListener("abort",z);let P=await i9(N),B=new w(N.status,P,N.headers.get("x-request-id")??void 0,p9(N.headers.get("retry-after"),X()));if(H===Y||!d9(N.status,B))throw B;let L=B.retryAfter??(N.status===429?E(B).retryAfter:void 0);await V(L===void 0?SJ(H,K):Math.min(L,r$)),G=B}throw G??Error("Provider request failed with no response.")}async function i9(J){let Q;try{Q=await J.text()}catch{return null}try{return JSON.parse(Q)}catch{return Q}}var DQ=300000;function FQ(J){return{generationsUrl:`${J.base}/images/generations${J.query}`,editsUrl:`${J.base}/images/edits${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}class AJ extends Error{code;retryable;retryAfter;constructor(J,Q={}){super(J.message,Q);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var n9={png:"image/png",jpeg:"image/jpeg"};function o9(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,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 s9(J){let Q=atob(J),$=new Uint8Array(Q.length);for(let Z=0;Z<Q.length;Z++)$[Z]=Q.charCodeAt(Z);return $}function a9(J){let $=J?.data?.[0]?.b64_json;if(typeof $!=="string"||$.length===0)throw new AJ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof J.output_format==="string"?J.output_format:"png";return{bytes:s9($),mimeType:n9[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:o9(J.usage)}}async function Q8(J,Q,$,Z){let W;try{W=await c(J,Q,{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(K){if(Z.signal?.aborted)throw K;throw new AJ(E(K),{cause:K})}return a9(await W.json())}async function $8(J,Q,$={}){return await Q8(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Q)},J,$)}async function Z8(J,Q,$={}){return await Q8(J.editsUrl,{method:"POST",headers:await J.headers(),body:Q},J,$)}class RJ{static models(){return[]}modelName(){return this.model}async generate(J){return await $8(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let Q=new FormData;for(let[$,Z]of Object.entries(this.body(J)))if(Z!==void 0)Q.set($,String(Z));for(let $ of J.images)Q.append("image[]",$,$.name);if(J.mask)Q.set("mask",J.mask,J.mask.name);return await Z8(this.endpoint(),Q,{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 E(J)}}var W8=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class PQ extends RJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new PQ(J,Q)}static models(){return W8}endpoint(){return FQ(WJ(this.config,{timeoutMs:DQ}))}}class BQ extends RJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new BQ(J,Q)}static models(){return W8}modelName(){return this.config.deployment??this.model}endpoint(){return FQ(KJ(this.config,{timeoutMs:DQ}))}}var G8=3;function NQ(J){let Q=new Map;for(let $ of J)for(let Z of $.content??[]){if(Z.type!=="file"||!Z.fileId||Q.has(Z.fileId))continue;Q.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return Q}function Y8(J,Q,$=new Map){if(!(Q instanceof w))return[];if(Q.status!==400&&Q.status!==404)return[];let Z=r9(Q.body);if(!Z)return[];let W=t9(J.input);if(W.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let G=J.input[Number(K[1])],H=LQ(G)[Number(K[2])],D=H&&typeof H.file_id==="string"?H.file_id:void 0;if(D)return[D]}let X=Z.message??"",Y=X8(W.map((G)=>G.fileId).filter((G)=>e9(X,G)));if(Y.length>0)return Y;let V=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(X);if(V){let G=V[1].toLowerCase()==="image type"?"input_image":"input_file",H=V[2].toLowerCase(),D=X8(W.filter((F)=>F.type===G).map((F)=>F.fileId)),z=D.filter((F)=>($.get(F)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(z.length===1)return z;if(z.length===0&&D.length===1)return D}return[]}function V8(J,Q,$=new Map){return{...J,input:J.input.map((Z)=>{let W=LQ(Z);if(!W.some((K)=>K8(K,Q)))return Z;return{...Z,content:W.map((K)=>K8(K,Q)?{type:"input_text",text:OQ($.get(String(K.file_id))?.name)}:K)}})}}function OQ(J){return`[${J?`attachment ${JSON.stringify(J)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function K8(J,Q){return typeof J.file_id==="string"&&Q.has(J.file_id)}function LQ(J){let Q=J?.content;return Array.isArray(Q)?Q:[]}function t9(J){let Q=[];for(let $ of J)for(let Z of LQ($))if(typeof Z.file_id==="string"&&Z.file_id)Q.push({type:String(Z.type),fileId:Z.file_id});return Q}function r9(J){if(!J||typeof J!=="object")return null;let Q=J,$=Q.error&&typeof Q.error==="object"?Q.error:J;return{message:typeof $.message==="string"?$.message:void 0,param:typeof $.param==="string"?$.param:void 0}}function e9(J,Q){let $=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${$}($|[^A-Za-z0-9_-])`).test(J)}function X8(J){return[...new Set(J)]}async function*JZ(J){let Q="",$="",Z=[],W,K=()=>{if(Z.length===0&&!$)return null;let V={event:$,data:Z.join(`
144
144
  `),id:W};return $="",Z=[],W=void 0,V.data?V:null},X=(V)=>{let G=V.endsWith("\r")?V.slice(0,-1):V;if(G==="")return K();if(G.startsWith(":"))return null;let H=G.indexOf(":"),D=H===-1?G:G.slice(0,H),z=H===-1?"":G.slice(H+1);if(z.startsWith(" "))z=z.slice(1);if(D==="event")$=z;else if(D==="data")Z.push(z);else if(D==="id")W=z;return null};for await(let V of J){Q+=V;let G=Q.indexOf(`
145
145
  `);while(G!==-1){let H=Q.slice(0,G);Q=Q.slice(G+1);let D=X(H);if(D)yield D;G=Q.indexOf(`
146
- `)}}if(Q.length>0){let V=X(Q);if(V)yield V}let Y=K();if(Y)yield Y}async function*V8(J,Q={}){let $=new Map,Z=new Set,W,K=!1,X,Y=(V,G)=>({type:"finish",reason:V,usage:G,...X?{model:X}:{}});for await(let V of JZ(J)){if(V.data==="[DONE]")break;let G;try{G=JSON.parse(V.data)}catch{continue}let H=typeof G.type==="string"?G.type:V.event,D=G.response?.model;if(typeof D==="string"&&D)X=D;switch(H){case"response.output_text.delta":{let z=String(G.delta??"");if(!z)break;yield Q.structuredOutput?{type:"output-delta",delta:z}:{type:"text-delta",delta:z};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let z=String(G.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:G.item_id};break}case"response.output_item.added":{let z=G.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??G.item_id??z.call_id??"");$.set(F,{callId:String(z.call_id??F),name:String(z.name??""),namespace:typeof z.namespace==="string"&&z.namespace?z.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let z=$.get(String(G.item_id??""));if(!z)break;let F=String(G.delta??"");if(!F)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:F,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(G.item_id??""),F=$.get(z);if(!F)break;F.done=!0,yield{type:"tool-call",toolCallId:F.callId,name:F.name,args:String(G.arguments??""),...F.namespace?{namespace:F.namespace}:{}};break}case"response.output_item.done":{let z=G.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??G.item_id??z.call_id??""),U=$.get(F);if(U?.done)break;let N=(typeof z.namespace==="string"?z.namespace:"")||U?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??F),name:String(z.name??U?.name??""),args:String(z.arguments??""),...N?{namespace:N}:{}},U)U.done=!0;break}if(z.type==="tool_search_call"||z.type==="tool_search_output"){if(z.type==="tool_search_call"&&z.arguments!==void 0)W=z.arguments;let F=QZ(z);if(F.loaded.length===0&&F.namespaces.length===0)break;let U=String(z.tool_search_call_id??z.id??"");if(Z.has(U))break;Z.add(U);let N=W;W=void 0,yield{type:"tool-search",...F,...N!==void 0&&N!==null?{arguments:N}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(G.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{K=!0,yield Y("stop",OQ(G.response?.usage));break}case"response.incomplete":{K=!0;let z=OQ(G.response?.usage),F=G.response?.incomplete_details?.reason;if(F==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:$Z(G.response?.content_filters),retryable:!1}},yield Y("error",z);break}yield Y(F==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{K=!0;let z=G.response?.error??G.error??G;yield{type:"error",error:ZZ(z)},yield Y("error",OQ(G.response?.usage));break}}if(K)return}if(!K)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield Y("error",b())}function QZ(J){let Q=[],$=[];return H8(J.results??J.tools??J.loaded??J.output,Q,$,0),{loaded:CQ(Q),namespaces:CQ($)}}function H8(J,Q,$,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){Q.push(W);continue}if(!W||typeof W!=="object")continue;let K=W,X=typeof K.name==="string"?K.name:typeof K.tool_name==="string"?K.tool_name:"",Y=K.tools??K.functions;if(Array.isArray(Y)){if(X)$.push(X);H8(Y,Q,$,Z+1);continue}if(X)Q.push(X)}}function CQ(J){return J.filter((Q,$)=>J.indexOf(Q)===$)}function $Z(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let $=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,K=W.content_filter_results;if(!K||typeof K!=="object")continue;for(let[X,Y]of Object.entries(K))if(Y&&typeof Y==="object"&&Y.filtered===!0)$.push(`${X} (${String(W.source_type??"unknown")})`)}return $.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${CQ($).join(", ")}.`}function ZZ(J){let Q=typeof J?.message==="string"?J.message:"The provider stream failed.",$=String(J?.code??"").toLowerCase();if($==="rate_limit_exceeded")return{code:"rate_limited",message:Q,retryable:!0};if($==="context_length_exceeded")return{code:"context_length_exceeded",message:Q,retryable:!1};if($.includes("content_filter"))return{code:"content_filtered",message:Q,retryable:!1};return{code:"provider_error",message:Q,retryable:!0}}function b(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function OQ(J){if(!J)return b();let Q=Number(J.input_tokens??0),$=Number(J.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J.total_tokens??Q+$)},W=J.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let K=J.input_tokens_details?.cached_tokens;if(typeof K==="number")Z.cachedInputTokens=K;return Z}async function*z8(J){if(!J)return;let Q=J.getReader(),$=new TextDecoder;try{while(!0){let{done:W,value:K}=await Q.read();if(W)break;if(K)yield $.decode(K,{stream:!0})}let Z=$.decode();if(Z)yield Z}finally{Q.releaseLock()}}function _Q(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}async function*MQ(J,Q,$){let Z=Q,W=new Set,K=0,X=Math.max(0,J.maxRetries),Y=J.random??Math.random,V,G=(D)=>{if(!V)return D;let z=A(A(b(),V),D.usage);return V=void 0,{...D,usage:z}},H=()=>G({type:"finish",reason:"aborted",usage:b()});for(let D=0;;D++){let z;while(z===void 0)try{z=await c(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Z)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:$.signal,fetchImpl:J.fetchImpl,sleep:J.sleep,random:J.random})}catch(P){let B=K<X8?G8(Z,P,$.files).filter((O)=>!W.has(O)):[];if(B.length>0){K++;let O=E(P).message;for(let j of B)W.add(j),yield{type:"file-rejected",fileId:j,message:O,...n(P)};Z=Y8(Z,new Set(B),$.files);continue}let L=E(P);if(L.code==="aborted"){yield H();return}yield{type:"error",error:L,...n(P)},yield G({type:"finish",reason:"error",usage:b()});return}let F=[],U=!1,N;try{for await(let P of V8(z8(z.body),{structuredOutput:$.structuredOutput})){if(U){yield P.type==="finish"?G(P):P;continue}if(TJ(P)){U=!0,yield*F.splice(0),yield P;continue}if(P.type==="error")N=P.error;F.push(P)}}catch(P){let B=E(P);if(B.code==="aborted"||$.signal?.aborted){yield H();return}if(U){yield{type:"error",error:B},yield G({type:"finish",reason:"error",usage:b()});return}N=B,F.push({type:"error",error:B},{type:"finish",reason:"error",usage:b()})}if(U)return;if(N?.retryable&&D<X&&!$.signal?.aborted){for(let P of F)if(P.type==="finish")V=A(V??b(),P.usage);try{await zQ(SJ(D,Y),$.signal,J.sleep)}catch{yield H();return}continue}for(let P of F)yield P.type==="finish"?G(P):P;return}}async function SQ(J,Q,$="user_data"){let Z=new FormData;Z.set("purpose",$),Z.set("file",Q);let K=await(await c(J.filesUrl,{method:"POST",headers:await J.headers(),body:Z},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,fetchImpl:J.fetchImpl})).json();if(!K?.id)throw Error("The provider accepted the upload but returned no file id.");return K.id}function AQ(J){let Q=WZ(J);if(Q.startsWith("gpt-3.5")||Q.startsWith("text-")||Q.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let $=KZ(Q);if($?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:$.major>1,toolSearch:D8($)};if($?.kind==="gpt")return{reasoning:$.major>=5,structuredOutput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),fileInput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:D8($)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function D8(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function WZ(J){return J.trim().toLowerCase()}function KZ(J){let Q=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if(Q?.[1])return{kind:"gpt",major:Number(Q[1]),minor:Number(Q[2]??0)};let $=/^o(\d+)(?:[-.]|$)/.exec(J);if($?.[1])return{kind:"o",major:Number($[1]),minor:0};return null}var XZ={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function GZ(J){if(typeof J!=="string")return;let Q;try{Q=JSON.parse(J)}catch{return}if(!Q||typeof Q!=="object"||typeof Q.type!=="string")return;let $=XZ[Q.type];if($)Q.type=$;if(Q.type==="response.done"&&Q.response?.usage)Q.usage=EJ(Q.response.usage);if(Q.type==="conversation.item.input_audio_transcription.completed"&&Q.usage)if(Q.usage.type==="duration"){let Z=Number(Q.usage.seconds);if(Number.isFinite(Z))Q.transcriptionSeconds=Z}else Q.transcriptionUsage=EJ(Q.usage);return Q}var F8=1,YZ=500;function VZ(J,Q){let $=globalThis.WebSocket;if(!$)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new $(J,{headers:Q.headers})}class jJ{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(J){this.init=J,this.callId=J.callId,this.ready=new Promise((Q,$)=>{this.resolveReady=Q,this.rejectReady=$}),this.ready.catch(()=>{}),this.closed=new Promise((Q)=>this.resolveClosed=Q),this.open()}send(J){if(this.finished||this.closing)return;let Q=JSON.stringify(J);if(this.socket?.readyState===F8)this.socket.send(Q);else this.outbox.push(Q)}updateSession(J){this.send({type:"session.update",session:kJ(J)})}addItem(J){this.send({type:"conversation.item.create",item:J})}addNote(J){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:J}]})}functionOutput(J,Q){this.addItem({type:"function_call_output",call_id:J,output:typeof Q==="string"?Q:JSON.stringify(Q)})}createResponse(J={}){let Q={};if(J.instructions!==void 0)Q.instructions=J.instructions;if(J.toolChoice!==void 0)Q.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};if(J.outputModalities)Q.output_modalities=J.outputModalities;if(J.conversation)Q.conversation=J.conversation;if(J.metadata)Q.metadata=J.metadata;Object.assign(Q,J.vendor),this.send(Object.keys(Q).length?{type:"response.create",response:Q}:{type:"response.create"})}cancelResponse(J){this.send(J?{type:"response.cancel",response_id:J}:{type:"response.cancel"})}on(J){return this.listeners.add(J),()=>this.listeners.delete(J)}[Symbol.asyncIterator](){let J={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(J),{next:async()=>{for(;;){let $=J.queue.shift();if($)return{value:$,done:!1};if(J.done)return this.subscribers.delete(J),{value:void 0,done:!0};await new Promise((Z)=>J.wake=Z),J.wake=void 0}},return:async()=>{return J.done=!0,J.queue.length=0,this.subscribers.delete(J),{value:void 0,done:!0}}}}close(J=1000,Q="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=F8)this.socket.close(J,Q);else this.finish(J,Q,!0)}async hangup(){try{await this.init.hangup()}catch(J){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw J}this.close(1000,"hangup")}async open(){let J;try{let $=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);J=(this.init.webSocket??VZ)(this.init.url,{headers:$})}catch($){return this.dropped(1006,$ instanceof Error?$.message:String($),!1)}this.socket=J;let Q=!1;J.addEventListener("open",()=>{Q=!0;let $=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let W of this.outbox.splice(0))J.send(W);if(this.resolveReady(),$)this.emit({type:"sideband.reconnected",attempt:Z})}),J.addEventListener("message",($)=>{let Z=GZ($.data);if(Z)this.emit(Z)}),J.addEventListener("close",($)=>{if(this.socket!==J)return;this.dropped($.code??1006,$.reason??"",Q)}),J.addEventListener("error",()=>{})}dropped(J,Q,$){if(this.socket=void 0,this.closing)return this.finish(J,Q,!0);let Z=this.init.reconnect?.attempts??3;if(!((J!==1000||!$)&&this.failures<Z))return this.finish(J,Q,!1);this.failures+=1;let K=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),K)}finish(J,Q,$){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:J,reason:Q,byClient:$};this.finalEvent=Z,this.emit(Z);for(let W of this.subscribers)W.done=!0,W.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${J} ${Q}).`));this.resolveClosed(Z)}emit(J){if(this.backlog){if(this.backlog.push(J),this.backlog.length>YZ)this.backlog.shift()}for(let Q of this.subscribers){if(Q.done)continue;Q.queue.push(J),Q.wake?.()}for(let Q of this.listeners)try{Q(J)}catch{}}}var RQ=30000,P8=10,B8=7200,HZ=600,U8="gpt-live-transcribe";function zZ(J){return J.type==="transcription"}function DZ(J){if(J.language!==void 0&&J.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let W of J.keywords??[])if(/[<>\r\n]/.test(W))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(W)}.`);let Q={model:J.model??U8};if(J.prompt!==void 0)Q.prompt=J.prompt;if(J.keywords?.length)Q.keywords=J.keywords;if(J.languages?.length)Q.languages=J.languages;if(J.language!==void 0)Q.language=J.language;if(J.delay!==void 0)Q.delay=J.delay;let $={transcription:Q,turn_detection:J.turnDetection?L8(J.turnDetection):null};if(J.noiseReduction!==void 0)$.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let Z={type:"transcription",audio:{input:$}};if(J.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...J.vendor}}function FZ(J){if(!J)return{type:"object",properties:{}};return N8(J)?J.toJSONSchema():J}function kJ(J,Q){if(zZ(J))return DZ(J);let $={type:"realtime"},Z=J.model??Q;if(Z)$.model=Z;if(J.instructions!==void 0)$.instructions=J.instructions;if(J.outputModalities)$.output_modalities=J.outputModalities;if(J.maxOutputTokens!==void 0)$.max_output_tokens=J.maxOutputTokens;if(J.truncation!==void 0)$.truncation=J.truncation;if(J.tools)$.tools=J.tools.map((X)=>({type:"function",name:X.name,...X.description?{description:X.description}:{},parameters:FZ(X.parameters)}));if(J.toolChoice!==void 0)$.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};let W={};if(J.turnDetection!==void 0)W.turn_detection=J.turnDetection&&L8(J.turnDetection);if(J.transcription!==void 0)W.transcription=J.transcription;if(J.noiseReduction!==void 0)W.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let K={};if(J.voice!==void 0)K.voice=J.voice;if(J.speed!==void 0)K.speed=J.speed;if(Object.keys(W).length||Object.keys(K).length)$.audio={...Object.keys(W).length?{input:W}:{},...Object.keys(K).length?{output:K}:{}};return{...$,...J.vendor}}function L8(J){let Q={type:J.type};if(J.createResponse!==void 0)Q.create_response=J.createResponse;if(J.interruptResponse!==void 0)Q.interrupt_response=J.interruptResponse;if(J.type==="semantic_vad"){if(J.eagerness!==void 0)Q.eagerness=J.eagerness}else{if(J.threshold!==void 0)Q.threshold=J.threshold;if(J.prefixPaddingMs!==void 0)Q.prefix_padding_ms=J.prefixPaddingMs;if(J.silenceDurationMs!==void 0)Q.silence_duration_ms=J.silenceDurationMs;if(J.idleTimeoutMs!==void 0)Q.idle_timeout_ms=J.idleTimeoutMs}return Q}function EJ(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J?.total_tokens??Q+$)},W=J?.input_token_details??J?.input_tokens_details,K=J?.output_token_details??J?.output_tokens_details;if(typeof W?.cached_tokens==="number")Z.cachedInputTokens=W.cached_tokens;if(typeof W?.audio_tokens==="number")Z.audioInputTokens=W.audio_tokens;let X=W?.cached_tokens_details?.audio_tokens;if(typeof X==="number")Z.cachedAudioInputTokens=X;if(typeof W?.image_tokens==="number"&&W.image_tokens>0)Z.imageInputTokens=W.image_tokens;if(typeof K?.audio_tokens==="number")Z.audioOutputTokens=K.audio_tokens;return Z}class f extends Error{code;retryable;status;constructor(J,Q={}){super(J.message,{cause:Q.cause});if(this.name="RealtimeRequestError",this.code=J.code,this.retryable=J.retryable,Q.status!==void 0)this.status=Q.status}}var PZ=60;class XJ{model;target;options;constructor(J,Q){this.target=J,this.options=Q,this.model=Q.model}url(J){return`${this.target.base}/realtime${J}${this.target.query}`}sidebandUrl(J){let Q=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),$=this.target.query?`${this.target.query}&`:"?";return`${Q}/realtime${$}call_id=${encodeURIComponent(J)}`}async createCall(J){let Q=J.flow??this.options.callFlow??"unified",$,Z;if(Q==="ephemeral")$={authorization:`Bearer ${(await this.clientSecret({session:J.session,ttlSeconds:PZ,signal:J.signal})).value}`,"content-type":"application/sdp"},Z=J.sdp;else{let V=new FormData;V.set("sdp",J.sdp),V.set("session",JSON.stringify(kJ(J.session??{},this.model))),$=await this.target.headers(),Z=V}if(J.safetyIdentifier)$["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=this.url("/calls"),K=await this.request(J.webrtcFilter?`${W}${W.includes("?")?"&":"?"}webrtcfilter=on`:W,{method:"POST",headers:$,body:Z},J.signal),X=await K.text(),Y=BZ(K);if(!Y)throw new f({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:X,callId:Y}}async clientSecret(J={}){let Q=J.ttlSeconds??HZ;if(!Number.isInteger(Q)||Q<P8||Q>B8)throw RangeError(`ttlSeconds must be a whole number from ${P8} to ${B8}, got ${Q}.`);let $={...await this.target.headers(),"content-type":"application/json"};if(J.safetyIdentifier)$["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:$,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:Q},session:kJ(J.session??{},this.model)})},J.signal)).json();if(typeof W?.value!=="string")throw new f({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:W.value,expiresAt:Number(W.expires_at??0),session:W.session,callsUrl:this.url("/calls")}}async hangup(J,Q={}){try{await this.request(this.url(`/calls/${encodeURIComponent(J)}/hangup`),{method:"POST",headers:await this.target.headers()},Q.signal)}catch($){if(O8($,J))return;throw $}}sideband(J,Q={}){return new jJ({...Q,callId:J,url:this.sidebandUrl(J),headers:this.target.headers,webSocket:Q.webSocket??this.options.webSocket,hangup:()=>this.hangup(J)})}async request(J,Q,$){try{return await c(J,Q,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:$,fetchImpl:this.options.fetchImpl})}catch(Z){if($?.aborted)throw Z;throw new f(E(Z),{cause:Z,...Z instanceof w?{status:Z.status}:{}})}}}function O8(J,Q){if(!(J instanceof f)||J.status!==404)return!1;let $=J.cause instanceof w?J.cause.body:void 0,Z=$?.error??$,W=String(Z?.code??"").toLowerCase(),K=String(Z?.message??"").toLowerCase();if(W.includes("call"))return!0;if(K.includes(Q.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function BZ(J){let Q=J.headers.get("location");if(!Q)return;let $=Q.split("?")[0].replace(/\/+$/,""),Z=$.slice($.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function EQ(J,Q){let{capabilities:$}=Q,Z={model:Q.model,input:NZ(J.messages,$,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=TZ(J.tools,$);if(W.length>0){if(Z.tools=W,!$.parallelToolCalls)Z.parallel_tool_calls=!1}if(J.output)Z.text={format:{type:"json_schema",name:J.output.name,schema:J.output.schema,strict:J.output.strict}};if(J.reasoning&&$.reasoning)Z.reasoning=J.reasoning==="none"?{effort:"none"}:{effort:J.reasoning,summary:"auto"};if(typeof J.temperature==="number")Z.temperature=J.temperature;if(typeof J.maxOutputTokens==="number")Z.max_output_tokens=J.maxOutputTokens;return Z}function NZ(J,Q,$){let Z=[],W=new Map;if(Q.toolSearch){for(let K of $??[])if(qJ(K))W.set(K.name,K)}for(let K of J){let X=K.role,Y=[],V=()=>{if(Y.length===0)return;Z.push({type:"message",role:X,content:Y}),Y=[]};for(let G of K.content??[])switch(G.type){case"text":{if(!G.text)break;Y.push(o(X,G.text));break}case"output":{if(G.partial)break;Y.push(o(X,JSON.stringify(G.value)));break}case"file":{if(X==="assistant")break;let H=OZ(G);if(!Q.fileInput){if(H)Y.push(o(X,TQ(G,!1)));break}if(G.fileId?.startsWith(m))throw Error(`FilePart.fileId holds a gemi attachment id (${G.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!G.fileId&&!H)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(G.providerRejected){if(H)Y.push(o(X,TQ(G,!1)));Y.push(o(X,UQ(G.name)));break}if(H)Y.push(o(X,TQ(G,!!G.fileId)));if(G.fileId)Y.push(CZ(G));break}case"reasoning":{V();let H=SZ(G);if(H)Z.push(H);break}case"tool-call":{if(G.partial)break;if(V(),Q.toolSearch&&Array.isArray(G.toolSearches))for(let D of G.toolSearches)Z.push(...RZ(D,$??[]));let H={type:"function_call",call_id:G.toolCallId,name:String(G.name),arguments:JSON.stringify(G.input??{})};if(G.namespace&&W.has(G.namespace))H.namespace=G.namespace;Z.push(H);break}case"tool-result":{V(),Z.push({type:"function_call_output",call_id:G.toolCallId,output:AZ(G)});break}}V()}return LZ(Z)}var UZ="No result was recorded for this tool call. Assume it did not complete.";function LZ(J){let Q=new Set,$=new Set,Z=[];for(let K of J){if(K.type==="function_call"){let X=String(K.call_id);if(Q.has(X))continue;Q.add(X)}else if(K.type==="function_call_output"){let X=String(K.call_id);if(!Q.has(X)||$.has(X))continue;$.add(X)}Z.push(K)}if($.size===Q.size)return Z;let W=[];for(let K of Z){if(W.push(K),K.type!=="function_call")continue;let X=String(K.call_id);if($.has(X))continue;$.add(X),W.push({type:"function_call_output",call_id:X,output:UZ})}return W}function o(J,Q){return{type:J==="assistant"?"output_text":"input_text",text:Q}}function OZ(J){let Q=J.attachmentId;return typeof Q==="string"&&Q.startsWith(m)?Q:void 0}function TQ(J,Q){let $=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)$.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)$.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${$.join(" ")}`;return Q?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function CZ(J){let Q=J.mimeType?.trim().toLowerCase()??"";return{type:(Q?Q.startsWith("image/")&&Q!=="image/svg+xml":_Z(J.name))?"input_image":"input_file",file_id:J.fileId}}function _Z(J){let Q=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return Q?.[1]!==void 0&&MZ.has(Q[1])}var MZ=new Set(["jpeg","jpg","png","gif","webp"]);function SZ(J){if(!J.id)return null;let Q={type:"reasoning",id:J.id};return Q.summary=J.text?[{type:"summary_text",text:J.text}]:[],Q}function AZ(J){if(J.status==="ok")return typeof J.output==="string"?J.output:JSON.stringify(J.output??null);if(J.status==="running"){let Q=J.job?.summary===void 0?"":` Started with: ${JSON.stringify(J.job.summary)}.`;return`Started background job ${J.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${Q}`}if(J.status==="denied"){let Q=J.reason?` Reason given: ${J.reason}`:"";if(J.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${Q}`;if(J.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${Q}`;return`The user declined this tool call, so it did not run.${Q}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function RZ(J,Q){let $=new Set(C8(J?.loaded)),Z=C8(J?.namespaces),W=new Set(Z),K=[];for(let Y of Q)if(qJ(Y)){if(!W.has(Y.name))continue;let V=Y.tools.filter((G)=>$.size===0||$.has(G.name));if(V.length===0)continue;K.push({type:"namespace",name:Y.name,description:Y.description,tools:V.map((G)=>s(G,!0))})}else if(Y.deferred&&$.has(Y.name))K.push(s(Y,!0));if(K.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:J.arguments&&typeof J.arguments==="object"?J.arguments:{paths:Z.length>0?Z:[...$]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function C8(J){return Array.isArray(J)?J.filter((Q)=>typeof Q==="string"):[]}function qJ(J){return Array.isArray(J.tools)}function TZ(J,Q){if(!J||J.length===0)return[];if(!Q.toolSearch){let W=[];for(let K of J)if(qJ(K))for(let X of K.tools)W.push(s(X,!1));else W.push(s(K,!1));return W}let $=[],Z=!1;for(let W of J)if(qJ(W)){let K=W.tools.map((X)=>{if(X.deferred)Z=!0;return s(X,!0)});$.push({type:"namespace",name:W.name,description:W.description,tools:K})}else{if(W.deferred)Z=!0;$.push(s(W,!0))}if(Z)$.push({type:"tool_search"});return $}function s(J,Q){let $={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if(Q&&J.deferred)$.defer_loading=!0;return $}class a{static models(){return[]}normalizeError(J){return E(J)}}var _8=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class jQ extends a{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=AQ(J),this.config=Q}static model(J,Q){return new jQ(J,Q)}static models(){return _8}stream(J){let Q=EQ(J,{model:this.model,capabilities:this.capabilities});return MQ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:NQ(J.messages)})}upload(J){return SQ(this.endpoint(),J)}endpoint(){return _Q(WJ(this.config))}get realtime(){return new XJ(WJ(this.config,{timeoutMs:RQ}),{model:this.model})}}class kQ extends a{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=AQ(J),this.config=Q}static model(J,Q){return new kQ(J,Q)}static models(){return _8}stream(J){let Q=EQ(J,{model:this.deployment(),capabilities:this.capabilities});return MQ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:NQ(J.messages)})}upload(J){return SQ(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return _Q(KJ(this.config))}get realtime(){return new XJ(s$(this.config,{timeoutMs:RQ}),{model:this.deployment(),callFlow:"ephemeral"})}}class xJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,Q){let $=this.entries.get(J);if($?.openUntil===void 0)return!0;let Z=this.now();if(Z<$.openUntil)return!1;if($.probeUntil!==void 0&&Z<$.probeUntil)return!1;return $.probeUntil=Z+Q.cooldownMs,!0}record(J,Q,$){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if(Q==="success")return this.entries.delete(J),W?"closed":void 0;if(Q==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=$.failures)return Z.openUntil=this.now()+$.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return"closed";return this.now()<Q.openUntil?"open":"half-open"}}var M8=Symbol("timed-out");class GJ extends a{model;capabilities;entries;options;circuit;constructor(J,Q={}){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($){let Z=$.failures??3,W=$.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let K=new Set;for(let Y of J){let V=qQ(Y);if(K.has(V))throw Error(`FallbackProvider: two legs share the circuit key "${V}". Give one of them a \`circuitKey\`.`);K.add(V)}let X=$.store??new xJ;this.options={...Q,circuit:{...$,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...$.onStateChange?{onStateChange:$.onStateChange}:{}}}else this.options=Q,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=EZ(J.map((Z)=>Z.provider.capabilities))}static chain(J,Q){return new GJ(J,Q)}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 Q=this.from(J).entries[0];return new GJ([Q],this.options)}upload(J){return this.entries[0].provider.upload(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let Q,$=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let K=this.entries[W],X=W===this.entries.length-1,Y=K.provider.model;if(this.circuit&&!X&&!await this.allow(K))continue;Z+=1;let V=!1,G=async(_)=>{if(V)return;V=!0,await this.record(W,K,_)},H=new AbortController,D=()=>H.abort($?.reason);if($?.aborted)H.abort($.reason);else $?.addEventListener("abort",D,{once:!0});let z=[],F=!1,U=!1,N,P,B,L=!1,O,j=!1,k=(_)=>{let R=Q?A(A(S(),Q),_.usage):_.usage;return Q=void 0,{..._,usage:R}};try{O=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let _=!0;for(;;){let R=_&&K.timeoutMs!==void 0?await jZ(O.next(),K.timeoutMs):await O.next();if(R===M8){L=!0,B={error:{code:"provider_error",message:`${Y} sent nothing within ${K.timeoutMs}ms.`,retryable:!0}};break}if(_=!1,R.done){j=!0;break}let C=R.value;if(C.type==="finish"&&C.model)P=C.model;if(F){if(C.type==="finish")N=A(N??S(),C.usage),U=!0,yield k(C);else{if(C.type==="error")B={error:C.error};yield C}continue}if(TJ(C)){F=!0,await G("success"),yield*z.splice(0),yield C;continue}if(C.type==="error")B={error:C.error,...C.status!==void 0?{status:C.status}:{},...C.requestId!==void 0?{requestId:C.requestId}:{}};else if(C.type==="finish"){if(N=A(N??S(),C.usage),C.reason==="error"&&!B)B={error:{code:"provider_error",message:`${Y} ended the call with an error and did not say which.`,retryable:!1}}}z.push(C)}}catch(_){let R=K.provider.normalizeError(_);if(F){if(R.code!=="aborted")yield{type:"error",error:R,...n(_)};this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:xQ(R),error:R}),yield k({type:"finish",reason:R.code==="aborted"?"aborted":"error",usage:S(),...P?{model:P}:{}});return}B={error:R,...n(_)}}finally{if($?.removeEventListener("abort",D),!j)H.abort(),O?.return?.()?.catch(()=>{})}if(F){if(!U&&Q)yield{type:"finish",reason:B?"error":"stop",usage:Q},Q=void 0;this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:B?xQ(B.error):"ok",...B?{error:B.error}:{}});return}if($?.aborted){await G("none"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:"aborted"}),yield k({type:"finish",reason:"aborted",usage:N??S(),...P?{model:P}:{}});return}if(!B){await G("success"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:"ok"});for(let _ of z)yield _.type==="finish"?k(_):_;return}let I=!X&&B.error.code!=="aborted"&&this.shouldFallBack(B.error,{index:W,model:Y,timedOut:L,...B.status!==void 0?{status:B.status}:{},...B.requestId!==void 0?{requestId:B.requestId}:{}});if(await G(I?"failure":"none"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:I?"fallback":xQ(B.error),error:B.error}),I){if(N)Q=A(Q??S(),N);continue}let q=!1,d;for(let _ of z){if(_.type==="finish"){d=_;continue}if(_.type==="error")q=!0;yield _}if(!q&&B.error.code!=="aborted")yield{type:"error",error:B.error,...B.status!==void 0?{status:B.status}:{},...B.requestId!==void 0?{requestId:B.requestId}:{}};yield k({type:"finish",reason:B.error.code==="aborted"?"aborted":d?.reason??"error",usage:N??S(),...P?{model:P}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(qQ(J),this.circuit.policy)}catch{return!0}}async record(J,Q,$){if(!this.circuit)return;let Z=qQ(Q),W;try{W=await this.circuit.store.record(Z,$,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:Q.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,Q){let $=this.options.fallbackOn??((Z)=>Z.retryable);try{return $(J,Q)}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 qQ(J){return J.circuitKey??J.provider.model}function xQ(J){return J.code==="aborted"?"aborted":"failed"}function EZ(J){return{reasoning:J.every((Q)=>Q.reasoning),structuredOutput:J.every((Q)=>Q.structuredOutput),fileInput:J.every((Q)=>Q.fileInput),parallelToolCalls:J.every((Q)=>Q.parallelToolCalls),toolSearch:J.every((Q)=>Q.toolSearch)}}function jZ(J,Q){let $,Z=new Promise((W)=>{$=setTimeout(()=>W(M8),Q)});return Promise.race([J,Z]).finally(()=>clearTimeout($))}async function kZ(J,Q,$={}){let Z=$.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let K=0;K<J.entries.length;K++){let X=J.leg(K),Y={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{Y.results.push(await Q(X,{index:K,sample:V}))}catch(G){Y.errors.push({sample:V,error:G})}W.push(Y)}return W}class wJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var VJ="ask_agent",qZ={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},xZ={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 IJ=new Map;class p{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=S();transcription={usage:S(),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 p(J)}static get(J){return IJ.get(J)}static async endAll(J){await Promise.all([...IJ.values()].map((Q)=>Q.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...qZ,...S8(J.limits)},this.lines={...xZ,...S8(J.lines)},this.delegateName=J.delegate?.name??VJ;let Q=new Set(YJ(J.delegate).map(($)=>$.name));for(let $ of J.tools??[]){if(Q.has($.tool.name)||this.toolHandlers.has($.tool.name))throw Error(`VoiceBridge: two tools are named "${$.tool.name}".`);this.toolHandlers.set($.tool.name,$)}if("realtime"in J.call){let{realtime:$,callId:Z}=J.call;this.callId=Z,this.sideband=$.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(($)=>this.resolveEnded=$),IJ.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 Q=this.params.contextNote?.(J);if(Q)this.sideband.addNote(Q)}end(J="hangup",Q){return this.ending??=this.finish(J,Q??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 Q=J.usage;if(Q){this.usage=A(this.usage,Q);let $=this.info();this.hook(()=>this.params.onUsage?.(Q,$))}return}case"conversation.item.input_audio_transcription.completed":{let Q=J;if(this.say("user",String(Q.transcript??"")),Q.transcriptionUsage||Q.transcriptionSeconds!==void 0){this.transcription={usage:Q.transcriptionUsage?A(this.transcription.usage,Q.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+(Q.transcriptionSeconds??0)};let $=this.info(),Z={...Q.transcriptionUsage?{usage:Q.transcriptionUsage}:{},...Q.transcriptionSeconds!==void 0?{seconds:Q.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,$))}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 Q=J;if(this.touch(),!this.ending)this.call(Q.call_id,Q.name,Q.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let Q=J.error;if(this.errors.push({code:Q?.code,message:String(Q?.message??"")}),this.pendingCreate&&Q?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,Q.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let Q=J;if(!this.ending&&!Q.byClient)this.end(Q.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,Q){if(Q.trim())this.transcript.push({role:J,text:Q,at:Date.now()})}call(J,Q,$){let Z=IZ($);if(Q===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(Q);if(W)return void this.runTool(J,W,Z);switch(Q){case"stop_work":{let K=this.running;if(K)K.stopRequested=!0,K.handle?.stop({reason:"Stopped by voice."});let X=this.dropQueue();return this.answer(J,{stopped:Boolean(K),dropped:X})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((K)=>K.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(J,{status:"error",message:"There is no open question."});let K=typeof Z.answer==="string"?Z.answer:"",X=typeof Z.approve==="boolean"?Z.approve:void 0,Y=this.pending.map((V)=>wZ(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:Y},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${Q}.`})}}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 Q=new Set;await this.waitForThread(Q);let $=await this.latestBody();while(!J.stopRequested&&await this.waitForThread(Q));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:$,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(Q){J.record.status="done",this.complete(J,{status:"failed",message:Q instanceof Error?Q.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let Q=this.queue.shift();if(Q&&!this.ending)this.run(Q);else this.touch()}}async runTool(J,Q,$){let Z=Q.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let K={name:Z,status:"running"};this.toolCalls.push(K),this.toolsRunning+=1,this.pauseIdle();let X=new AbortController,Y=Q.timeoutMs??this.limits.toolTimeoutMs,V,G;try{let D=await Promise.race([Q.run($,{sessionId:this.sessionId,signal:X.signal}),new Promise((z,F)=>{V=setTimeout(()=>{F(new g(`"${Z}" took longer than ${Math.round(Y/1000)} s.`)),X.abort()},Y)})]);K.status="done",G={status:"done",output:this.clip(D)}}catch(D){if(D instanceof wJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let z=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=z,G={status:"failed",message:z}}finally{clearTimeout(V),K.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let H=this.info();if(this.hook(()=>this.params.onToolCall?.({...K},H)),!this.ending)this.answer(J,G)}clip(J){let Q;try{Q=JSON.stringify(J)}catch{return String(J)}if(Q===void 0||Q.length<=this.limits.toolOutputChars)return J;return`${Q.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${Q.length} characters in all)`}async waitForThread(J=new Set){let Q=this.params.liveRuns;if(!Q)return!1;let $=await Q.find({threadId:this.threadId}),Z=$&&!J.has($.runId)?Q.get($.runId):null;if(!$||!Z)return!1;return J.add($.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let Q=await J.get(this.sessionId).catch(()=>null);if(Q)this.body=Q.body;return this.body}async follow(J){let Q=this.params.progress??bZ();try{for await(let $ of J.run){let Z=Q($);if(Z)this.note(Z)}}catch{}}complete(J,Q){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,Q),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify(Q)}`);this.respond()}answer(J,Q){this.sideband.functionOutput(J,Q),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 Q of J)Q.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let Q=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if(Q<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),Q)}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(Q){if(Q instanceof wJ)this.end("usage",Q.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",Q),this.end("error",this.lines.error)}})}tampered(J){let Q=this.params.session;if(!Q||!J)return!1;if(Q.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==Q.instructions)return!0;if(Array.isArray(J.tools)){let $=new Set([...YJ(this.params.delegate),...Q.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if($.size!==Z.size||[...$].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,Q){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(),Q&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine(Q);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};IJ.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 Q;await Promise.race([this.sideband.closed,new Promise(($)=>Q=setTimeout($,this.limits.hangupGraceMs))]),clearTimeout(Q),this.sideband.close()}}async closingLine(J){await new Promise((Q)=>{let $=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",K,X=setTimeout(Y,this.limits.closingLineMs);function Y(){clearTimeout(X),Q()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:$,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(G)=>{let H=G;if(H.type==="sideband.closed")return Y();if(W==="cancelling"){if(H.type==="response.done"||H.type==="error"&&H.error?.event_id===Z)V();return}if(H.type==="error"&&H.error?.event_id===$)return Y();if(H.type==="response.created"&&!K){K=H.response?.id;return}let D=(z)=>!K||!z||z===K;if(H.type==="response.done"&&D(H.response?.id))W="playing";else if(H.type==="output_audio_buffer.stopped"&&W==="playing"&&D(H.response_id))Y()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function S8(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,Q])=>Q!==void 0))}function IZ(J){try{let Q=JSON.parse(J);return Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{}}catch{return{}}}function wZ(J,Q,$){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:Q};if(J.kind==="approval")return{...Z,approve:$===!0,...Q?{reason:Q}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function bZ(){let J=new Set;return(Q)=>{if(Q.type==="tool-call"){if(Q.part.partial||Q.resent||J.has(Q.part.toolCallId))return;return J.add(Q.part.toolCallId),`running ${String(Q.part.name)}`}if(Q.type==="tool-progress"){let $=Q.data;if(typeof $==="string")return $;if($&&typeof $==="object")for(let Z of["message","label","title"]){let W=$[Z];if(typeof W==="string"&&W)return W}}return}}var A8="http://gemi.internal/__gemi__/voice/mcp";async function IQ(J,Q){if(!Q.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:$}=J,Z=J.scopes??$.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:Q.user,via:"voice",id:`voice:${Q.sessionId}`,scopes:Z}});return(await $.available(W(R8()),J.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(Y,V)=>{let G=R8();return h.run(G,async()=>{return await J.authorize?.({name:X.name,input:Y,sessionId:V.sessionId}),$.execute(W(G),X.name,Y,void 0,{signal:V.signal})},{user:Q.user})}}))}function R8(){return new x(new Request(A8,{method:"POST"}),{},"api",new URL(A8).pathname)}class wQ{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 Q=this.records.get(J);return Q?structuredClone(Q):null}async update(J,Q){let $=this.records.get(J);if(!$)return;this.records.set(J,{...$,...structuredClone(Q),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[Q,$]of this.records)if($.endedAt!==void 0&&$.endedAt<J)this.records.delete(Q)}}var bQ=new wQ;class t extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,Q,$){super(`Frame ${Q} of run ${J} has been evicted; the oldest frame still buffered is ${$}. Reload the thread instead of resuming.`);this.runId=J;this.requested=Q;this.oldest=$}}class HJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class bJ{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,Q={}){let $={run:J,threadId:Q.threadId,owner:Q.owner??null,clientRunId:Q.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(Q.threadId,J.runId);if(Q.clientRunId)this.byClientRun.set(Q.clientRunId,J.runId);return this.scheduleExpiry($,Q.maxRunDurationMs),this.pump($,Q)}findByClientRunId(J){let Q=this.byClientRun.get(J);return Q&&this.runs.has(Q)?Q:null}async find(J){let Q=this.byThread.get(J.threadId);if(!Q)return null;let $=this.runs.get(Q);if(!$)return null;return{runId:Q,seq:$.lastSeq}}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,Q){let $=this.ownerOf(J);return $===null||$===Q}isRunning(J){let Q=this.runs.get(J);return!!Q&&!Q.ended&&!Q.evicted}replay(J,Q){let $=this.runs.get(J);if(!$)throw new HJ(J);if(Q!==void 0&&Q<$.lostBefore)throw new t(J,Q,$.lostBefore);let Z=$.frames[0]?.seq;return this.drain($,J,Q??Z??$.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,Q){let $=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let K=Q.onEvent;if(K)$=$.then(()=>K(Z.event)).catch((X)=>fQ(Q,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=Q.onEvent;if(W)$=$.then(()=>W(Z.event)).catch((K)=>fQ(Q,K))}}catch(Z){fQ(Q,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await $}}async*drain(J,Q,$){let Z=$;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new t(Q,Z,J.lostBefore);let K=J.frames,X=K[0]?.seq;if(X===void 0)break;let Y=Math.max(0,Z-X);if(Y>=K.length)break;let V=K[Y];yield V,Z=V.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,Q){if(J.version!==Q)return Promise.resolve();return new Promise(($)=>J.wake.add($))}notify(J){J.version++;let Q=Array.from(J.wake);J.wake.clear();for(let $ of Q)$()}scheduleEviction(J){if(J.evictAt)return;let Q=setTimeout(()=>{let $=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get($)===J)this.runs.delete($);if(J.threadId&&this.byThread.get(J.threadId)===$)this.byThread.delete(J.threadId);if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===$)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);Q.unref?.(),J.evictAt=Q}scheduleExpiry(J,Q){if(this.maxAgeMs===null||Q===null)return;let $=Q===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,Q+this.ttlMs);if(!Number.isFinite($)||$>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round($/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},$);Z.unref?.(),J.expireAt=Z}}var vQ=new bJ;function fQ(J,Q){try{J.onInternalError?.(Q)}catch{}}class fJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,Q){if(this.records.has(J))return;this.records.set(J,{...Q});while(this.records.size>this.maxEntries){let $=this.records.keys().next().value;if($===void 0)break;this.records.delete($)}}async get(J){let Q=this.records.get(J);return Q?{...Q}:null}}var yQ=new fJ;class uQ{now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,Q){let $=this.now();if(this.receipts.size>=this.sweepAt)this.sweep($);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>$)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:Q}),{status:"claimed"}}async complete(J,Q,$){this.receipts.set(J,{result:structuredClone(Q),expiresAt:$})}async release(J){let Q=this.receipts.get(J);if(Q&&!Q.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[Q,$]of this.receipts)if($.expiresAt<=J)this.receipts.delete(Q);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var T8="pending",hQ="done:",fZ=`
146
+ `)}}if(Q.length>0){let V=X(Q);if(V)yield V}let Y=K();if(Y)yield Y}async function*H8(J,Q={}){let $=new Map,Z=new Set,W,K=!1,X,Y=(V,G)=>({type:"finish",reason:V,usage:G,...X?{model:X}:{}});for await(let V of JZ(J)){if(V.data==="[DONE]")break;let G;try{G=JSON.parse(V.data)}catch{continue}let H=typeof G.type==="string"?G.type:V.event,D=G.response?.model;if(typeof D==="string"&&D)X=D;switch(H){case"response.output_text.delta":{let z=String(G.delta??"");if(!z)break;yield Q.structuredOutput?{type:"output-delta",delta:z}:{type:"text-delta",delta:z};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let z=String(G.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:G.item_id};break}case"response.output_item.added":{let z=G.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??G.item_id??z.call_id??"");$.set(F,{callId:String(z.call_id??F),name:String(z.name??""),namespace:typeof z.namespace==="string"&&z.namespace?z.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let z=$.get(String(G.item_id??""));if(!z)break;let F=String(G.delta??"");if(!F)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:F,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(G.item_id??""),F=$.get(z);if(!F)break;F.done=!0,yield{type:"tool-call",toolCallId:F.callId,name:F.name,args:String(G.arguments??""),...F.namespace?{namespace:F.namespace}:{}};break}case"response.output_item.done":{let z=G.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??G.item_id??z.call_id??""),O=$.get(F);if(O?.done)break;let N=(typeof z.namespace==="string"?z.namespace:"")||O?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??F),name:String(z.name??O?.name??""),args:String(z.arguments??""),...N?{namespace:N}:{}},O)O.done=!0;break}if(z.type==="tool_search_call"||z.type==="tool_search_output"){if(z.type==="tool_search_call"&&z.arguments!==void 0)W=z.arguments;let F=QZ(z);if(F.loaded.length===0&&F.namespaces.length===0)break;let O=String(z.tool_search_call_id??z.id??"");if(Z.has(O))break;Z.add(O);let N=W;W=void 0,yield{type:"tool-search",...F,...N!==void 0&&N!==null?{arguments:N}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(G.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{K=!0,yield Y("stop",UQ(G.response?.usage));break}case"response.incomplete":{K=!0;let z=UQ(G.response?.usage),F=G.response?.incomplete_details?.reason;if(F==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:$Z(G.response?.content_filters),retryable:!1}},yield Y("error",z);break}yield Y(F==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{K=!0;let z=G.response?.error??G.error??G;yield{type:"error",error:ZZ(z)},yield Y("error",UQ(G.response?.usage));break}}if(K)return}if(!K)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield Y("error",b())}function QZ(J){let Q=[],$=[];return z8(J.results??J.tools??J.loaded??J.output,Q,$,0),{loaded:CQ(Q),namespaces:CQ($)}}function z8(J,Q,$,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){Q.push(W);continue}if(!W||typeof W!=="object")continue;let K=W,X=typeof K.name==="string"?K.name:typeof K.tool_name==="string"?K.tool_name:"",Y=K.tools??K.functions;if(Array.isArray(Y)){if(X)$.push(X);z8(Y,Q,$,Z+1);continue}if(X)Q.push(X)}}function CQ(J){return J.filter((Q,$)=>J.indexOf(Q)===$)}function $Z(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let $=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,K=W.content_filter_results;if(!K||typeof K!=="object")continue;for(let[X,Y]of Object.entries(K))if(Y&&typeof Y==="object"&&Y.filtered===!0)$.push(`${X} (${String(W.source_type??"unknown")})`)}return $.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${CQ($).join(", ")}.`}function ZZ(J){let Q=typeof J?.message==="string"?J.message:"The provider stream failed.",$=String(J?.code??"").toLowerCase();if($==="rate_limit_exceeded")return{code:"rate_limited",message:Q,retryable:!0};if($==="context_length_exceeded")return{code:"context_length_exceeded",message:Q,retryable:!1};if($.includes("content_filter"))return{code:"content_filtered",message:Q,retryable:!1};return{code:"provider_error",message:Q,retryable:!0}}function b(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function UQ(J){if(!J)return b();let Q=Number(J.input_tokens??0),$=Number(J.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J.total_tokens??Q+$)},W=J.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let K=J.input_tokens_details?.cached_tokens;if(typeof K==="number")Z.cachedInputTokens=K;return Z}async function*D8(J){if(!J)return;let Q=J.getReader(),$=new TextDecoder;try{while(!0){let{done:W,value:K}=await Q.read();if(W)break;if(K)yield $.decode(K,{stream:!0})}let Z=$.decode();if(Z)yield Z}finally{Q.releaseLock()}}function _Q(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}async function*MQ(J,Q,$){let Z=Q,W=new Set,K=0,X=Math.max(0,J.maxRetries),Y=J.random??Math.random,V,G=(D)=>{if(!V)return D;let z=A(A(b(),V),D.usage);return V=void 0,{...D,usage:z}},H=()=>G({type:"finish",reason:"aborted",usage:b()});for(let D=0;;D++){let z;while(z===void 0)try{z=await c(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Z)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:$.signal,fetchImpl:J.fetchImpl,sleep:J.sleep,random:J.random})}catch(P){let B=K<G8?Y8(Z,P,$.files).filter((U)=>!W.has(U)):[];if(B.length>0){K++;let U=E(P).message;for(let j of B)W.add(j),yield{type:"file-rejected",fileId:j,message:U,...n(P)};Z=V8(Z,new Set(B),$.files);continue}let L=E(P);if(L.code==="aborted"){yield H();return}yield{type:"error",error:L,...n(P)},yield G({type:"finish",reason:"error",usage:b()});return}let F=[],O=!1,N;try{for await(let P of H8(D8(z.body),{structuredOutput:$.structuredOutput})){if(O){yield P.type==="finish"?G(P):P;continue}if(TJ(P)){O=!0,yield*F.splice(0),yield P;continue}if(P.type==="error")N=P.error;F.push(P)}}catch(P){let B=E(P);if(B.code==="aborted"||$.signal?.aborted){yield H();return}if(O){yield{type:"error",error:B},yield G({type:"finish",reason:"error",usage:b()});return}N=B,F.push({type:"error",error:B},{type:"finish",reason:"error",usage:b()})}if(O)return;if(N?.retryable&&D<X&&!$.signal?.aborted){for(let P of F)if(P.type==="finish")V=A(V??b(),P.usage);try{await zQ(SJ(D,Y),$.signal,J.sleep)}catch{yield H();return}continue}for(let P of F)yield P.type==="finish"?G(P):P;return}}async function SQ(J,Q,$="user_data"){let Z=new FormData;Z.set("purpose",$),Z.set("file",Q);let K=await(await c(J.filesUrl,{method:"POST",headers:await J.headers(),body:Z},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,fetchImpl:J.fetchImpl})).json();if(!K?.id)throw Error("The provider accepted the upload but returned no file id.");return K.id}function AQ(J){let Q=WZ(J);if(Q.startsWith("gpt-3.5")||Q.startsWith("text-")||Q.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let $=KZ(Q);if($?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:$.major>1,toolSearch:F8($)};if($?.kind==="gpt")return{reasoning:$.major>=5,structuredOutput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),fileInput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:F8($)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function F8(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function WZ(J){return J.trim().toLowerCase()}function KZ(J){let Q=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if(Q?.[1])return{kind:"gpt",major:Number(Q[1]),minor:Number(Q[2]??0)};let $=/^o(\d+)(?:[-.]|$)/.exec(J);if($?.[1])return{kind:"o",major:Number($[1]),minor:0};return null}var XZ={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function GZ(J){if(typeof J!=="string")return;let Q;try{Q=JSON.parse(J)}catch{return}if(!Q||typeof Q!=="object"||typeof Q.type!=="string")return;let $=XZ[Q.type];if($)Q.type=$;if(Q.type==="response.done"&&Q.response?.usage)Q.usage=EJ(Q.response.usage);if(Q.type==="conversation.item.input_audio_transcription.completed"&&Q.usage)if(Q.usage.type==="duration"){let Z=Number(Q.usage.seconds);if(Number.isFinite(Z))Q.transcriptionSeconds=Z}else Q.transcriptionUsage=EJ(Q.usage);return Q}var P8=1,YZ=500;function VZ(J,Q){let $=globalThis.WebSocket;if(!$)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new $(J,{headers:Q.headers})}class jJ{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(J){this.init=J,this.callId=J.callId,this.ready=new Promise((Q,$)=>{this.resolveReady=Q,this.rejectReady=$}),this.ready.catch(()=>{}),this.closed=new Promise((Q)=>this.resolveClosed=Q),this.open()}send(J){if(this.finished||this.closing)return;let Q=JSON.stringify(J);if(this.socket?.readyState===P8)this.socket.send(Q);else this.outbox.push(Q)}updateSession(J){this.send({type:"session.update",session:kJ(J)})}addItem(J){this.send({type:"conversation.item.create",item:J})}addNote(J){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:J}]})}functionOutput(J,Q){this.addItem({type:"function_call_output",call_id:J,output:typeof Q==="string"?Q:JSON.stringify(Q)})}createResponse(J={}){let Q={};if(J.instructions!==void 0)Q.instructions=J.instructions;if(J.toolChoice!==void 0)Q.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};if(J.outputModalities)Q.output_modalities=J.outputModalities;if(J.conversation)Q.conversation=J.conversation;if(J.metadata)Q.metadata=J.metadata;Object.assign(Q,J.vendor),this.send(Object.keys(Q).length?{type:"response.create",response:Q}:{type:"response.create"})}cancelResponse(J){this.send(J?{type:"response.cancel",response_id:J}:{type:"response.cancel"})}on(J){return this.listeners.add(J),()=>this.listeners.delete(J)}[Symbol.asyncIterator](){let J={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(J),{next:async()=>{for(;;){let $=J.queue.shift();if($)return{value:$,done:!1};if(J.done)return this.subscribers.delete(J),{value:void 0,done:!0};await new Promise((Z)=>J.wake=Z),J.wake=void 0}},return:async()=>{return J.done=!0,J.queue.length=0,this.subscribers.delete(J),{value:void 0,done:!0}}}}close(J=1000,Q="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=P8)this.socket.close(J,Q);else this.finish(J,Q,!0)}async hangup(){try{await this.init.hangup()}catch(J){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw J}this.close(1000,"hangup")}async open(){let J;try{let $=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);J=(this.init.webSocket??VZ)(this.init.url,{headers:$})}catch($){return this.dropped(1006,$ instanceof Error?$.message:String($),!1)}this.socket=J;let Q=!1;J.addEventListener("open",()=>{Q=!0;let $=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let W of this.outbox.splice(0))J.send(W);if(this.resolveReady(),$)this.emit({type:"sideband.reconnected",attempt:Z})}),J.addEventListener("message",($)=>{let Z=GZ($.data);if(Z)this.emit(Z)}),J.addEventListener("close",($)=>{if(this.socket!==J)return;this.dropped($.code??1006,$.reason??"",Q)}),J.addEventListener("error",()=>{})}dropped(J,Q,$){if(this.socket=void 0,this.closing)return this.finish(J,Q,!0);let Z=this.init.reconnect?.attempts??3;if(!((J!==1000||!$)&&this.failures<Z))return this.finish(J,Q,!1);this.failures+=1;let K=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),K)}finish(J,Q,$){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:J,reason:Q,byClient:$};this.finalEvent=Z,this.emit(Z);for(let W of this.subscribers)W.done=!0,W.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${J} ${Q}).`));this.resolveClosed(Z)}emit(J){if(this.backlog){if(this.backlog.push(J),this.backlog.length>YZ)this.backlog.shift()}for(let Q of this.subscribers){if(Q.done)continue;Q.queue.push(J),Q.wake?.()}for(let Q of this.listeners)try{Q(J)}catch{}}}var RQ=30000,B8=10,N8=7200,HZ=600,L8="gpt-live-transcribe";function zZ(J){return J.type==="transcription"}function DZ(J){if(J.language!==void 0&&J.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let W of J.keywords??[])if(/[<>\r\n]/.test(W))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(W)}.`);let Q={model:J.model??L8};if(J.prompt!==void 0)Q.prompt=J.prompt;if(J.keywords?.length)Q.keywords=J.keywords;if(J.languages?.length)Q.languages=J.languages;if(J.language!==void 0)Q.language=J.language;if(J.delay!==void 0)Q.delay=J.delay;let $={transcription:Q,turn_detection:J.turnDetection?U8(J.turnDetection):null};if(J.noiseReduction!==void 0)$.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let Z={type:"transcription",audio:{input:$}};if(J.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...J.vendor}}function FZ(J){if(!J)return{type:"object",properties:{}};return O8(J)?J.toJSONSchema():J}function kJ(J,Q){if(zZ(J))return DZ(J);let $={type:"realtime"},Z=J.model??Q;if(Z)$.model=Z;if(J.instructions!==void 0)$.instructions=J.instructions;if(J.outputModalities)$.output_modalities=J.outputModalities;if(J.maxOutputTokens!==void 0)$.max_output_tokens=J.maxOutputTokens;if(J.truncation!==void 0)$.truncation=J.truncation;if(J.tools)$.tools=J.tools.map((X)=>({type:"function",name:X.name,...X.description?{description:X.description}:{},parameters:FZ(X.parameters)}));if(J.toolChoice!==void 0)$.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};let W={};if(J.turnDetection!==void 0)W.turn_detection=J.turnDetection&&U8(J.turnDetection);if(J.transcription!==void 0)W.transcription=J.transcription;if(J.noiseReduction!==void 0)W.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let K={};if(J.voice!==void 0)K.voice=J.voice;if(J.speed!==void 0)K.speed=J.speed;if(Object.keys(W).length||Object.keys(K).length)$.audio={...Object.keys(W).length?{input:W}:{},...Object.keys(K).length?{output:K}:{}};return{...$,...J.vendor}}function U8(J){let Q={type:J.type};if(J.createResponse!==void 0)Q.create_response=J.createResponse;if(J.interruptResponse!==void 0)Q.interrupt_response=J.interruptResponse;if(J.type==="semantic_vad"){if(J.eagerness!==void 0)Q.eagerness=J.eagerness}else{if(J.threshold!==void 0)Q.threshold=J.threshold;if(J.prefixPaddingMs!==void 0)Q.prefix_padding_ms=J.prefixPaddingMs;if(J.silenceDurationMs!==void 0)Q.silence_duration_ms=J.silenceDurationMs;if(J.idleTimeoutMs!==void 0)Q.idle_timeout_ms=J.idleTimeoutMs}return Q}function EJ(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J?.total_tokens??Q+$)},W=J?.input_token_details??J?.input_tokens_details,K=J?.output_token_details??J?.output_tokens_details;if(typeof W?.cached_tokens==="number")Z.cachedInputTokens=W.cached_tokens;if(typeof W?.audio_tokens==="number")Z.audioInputTokens=W.audio_tokens;let X=W?.cached_tokens_details?.audio_tokens;if(typeof X==="number")Z.cachedAudioInputTokens=X;if(typeof W?.image_tokens==="number"&&W.image_tokens>0)Z.imageInputTokens=W.image_tokens;if(typeof K?.audio_tokens==="number")Z.audioOutputTokens=K.audio_tokens;return Z}class f extends Error{code;retryable;status;constructor(J,Q={}){super(J.message,{cause:Q.cause});if(this.name="RealtimeRequestError",this.code=J.code,this.retryable=J.retryable,Q.status!==void 0)this.status=Q.status}}var PZ=60;class XJ{model;target;options;constructor(J,Q){this.target=J,this.options=Q,this.model=Q.model}url(J){return`${this.target.base}/realtime${J}${this.target.query}`}sidebandUrl(J){let Q=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),$=this.target.query?`${this.target.query}&`:"?";return`${Q}/realtime${$}call_id=${encodeURIComponent(J)}`}async createCall(J){let Q=J.flow??this.options.callFlow??"unified",$,Z;if(Q==="ephemeral")$={authorization:`Bearer ${(await this.clientSecret({session:J.session,ttlSeconds:PZ,signal:J.signal})).value}`,"content-type":"application/sdp"},Z=J.sdp;else{let V=new FormData;V.set("sdp",J.sdp),V.set("session",JSON.stringify(kJ(J.session??{},this.model))),$=await this.target.headers(),Z=V}if(J.safetyIdentifier)$["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=this.url("/calls"),K=await this.request(J.webrtcFilter?`${W}${W.includes("?")?"&":"?"}webrtcfilter=on`:W,{method:"POST",headers:$,body:Z},J.signal),X=await K.text(),Y=BZ(K);if(!Y)throw new f({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:X,callId:Y}}async clientSecret(J={}){let Q=J.ttlSeconds??HZ;if(!Number.isInteger(Q)||Q<B8||Q>N8)throw RangeError(`ttlSeconds must be a whole number from ${B8} to ${N8}, got ${Q}.`);let $={...await this.target.headers(),"content-type":"application/json"};if(J.safetyIdentifier)$["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:$,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:Q},session:kJ(J.session??{},this.model)})},J.signal)).json();if(typeof W?.value!=="string")throw new f({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:W.value,expiresAt:Number(W.expires_at??0),session:W.session,callsUrl:this.url("/calls")}}async hangup(J,Q={}){try{await this.request(this.url(`/calls/${encodeURIComponent(J)}/hangup`),{method:"POST",headers:await this.target.headers()},Q.signal)}catch($){if(C8($,J))return;throw $}}sideband(J,Q={}){return new jJ({...Q,callId:J,url:this.sidebandUrl(J),headers:this.target.headers,webSocket:Q.webSocket??this.options.webSocket,hangup:()=>this.hangup(J)})}async request(J,Q,$){try{return await c(J,Q,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:$,fetchImpl:this.options.fetchImpl})}catch(Z){if($?.aborted)throw Z;throw new f(E(Z),{cause:Z,...Z instanceof w?{status:Z.status}:{}})}}}function C8(J,Q){if(!(J instanceof f)||J.status!==404)return!1;let $=J.cause instanceof w?J.cause.body:void 0,Z=$?.error??$,W=String(Z?.code??"").toLowerCase(),K=String(Z?.message??"").toLowerCase();if(W.includes("call"))return!0;if(K.includes(Q.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function BZ(J){let Q=J.headers.get("location");if(!Q)return;let $=Q.split("?")[0].replace(/\/+$/,""),Z=$.slice($.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function EQ(J,Q){let{capabilities:$}=Q,Z={model:Q.model,input:NZ(J.messages,$,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=TZ(J.tools,$);if(W.length>0){if(Z.tools=W,!$.parallelToolCalls)Z.parallel_tool_calls=!1}if(J.output)Z.text={format:{type:"json_schema",name:J.output.name,schema:J.output.schema,strict:J.output.strict}};if(J.reasoning&&$.reasoning)Z.reasoning=J.reasoning==="none"?{effort:"none"}:{effort:J.reasoning,summary:"auto"};if(typeof J.temperature==="number")Z.temperature=J.temperature;if(typeof J.maxOutputTokens==="number")Z.max_output_tokens=J.maxOutputTokens;return Z}function NZ(J,Q,$){let Z=[],W=new Map;if(Q.toolSearch){for(let K of $??[])if(qJ(K))W.set(K.name,K)}for(let K of J){let X=K.role,Y=[],V=()=>{if(Y.length===0)return;Z.push({type:"message",role:X,content:Y}),Y=[]};for(let G of K.content??[])switch(G.type){case"text":{if(!G.text)break;Y.push(o(X,G.text));break}case"output":{if(G.partial)break;Y.push(o(X,JSON.stringify(G.value)));break}case"file":{if(X==="assistant")break;let H=UZ(G);if(!Q.fileInput){if(H)Y.push(o(X,TQ(G,!1)));break}if(G.fileId?.startsWith(m))throw Error(`FilePart.fileId holds a gemi attachment id (${G.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!G.fileId&&!H)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(G.providerRejected){if(H)Y.push(o(X,TQ(G,!1)));Y.push(o(X,OQ(G.name)));break}if(H)Y.push(o(X,TQ(G,!!G.fileId)));if(G.fileId)Y.push(CZ(G));break}case"reasoning":{V();let H=SZ(G);if(H)Z.push(H);break}case"tool-call":{if(G.partial)break;if(V(),Q.toolSearch&&Array.isArray(G.toolSearches))for(let D of G.toolSearches)Z.push(...RZ(D,$??[]));let H={type:"function_call",call_id:G.toolCallId,name:String(G.name),arguments:JSON.stringify(G.input??{})};if(G.namespace&&W.has(G.namespace))H.namespace=G.namespace;Z.push(H);break}case"tool-result":{V(),Z.push({type:"function_call_output",call_id:G.toolCallId,output:AZ(G)});break}}V()}return LZ(Z)}var OZ="No result was recorded for this tool call. Assume it did not complete.";function LZ(J){let Q=new Set,$=new Set,Z=[];for(let K of J){if(K.type==="function_call"){let X=String(K.call_id);if(Q.has(X))continue;Q.add(X)}else if(K.type==="function_call_output"){let X=String(K.call_id);if(!Q.has(X)||$.has(X))continue;$.add(X)}Z.push(K)}if($.size===Q.size)return Z;let W=[];for(let K of Z){if(W.push(K),K.type!=="function_call")continue;let X=String(K.call_id);if($.has(X))continue;$.add(X),W.push({type:"function_call_output",call_id:X,output:OZ})}return W}function o(J,Q){return{type:J==="assistant"?"output_text":"input_text",text:Q}}function UZ(J){let Q=J.attachmentId;return typeof Q==="string"&&Q.startsWith(m)?Q:void 0}function TQ(J,Q){let $=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)$.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)$.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${$.join(" ")}`;return Q?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function CZ(J){let Q=J.mimeType?.trim().toLowerCase()??"";return{type:(Q?Q.startsWith("image/")&&Q!=="image/svg+xml":_Z(J.name))?"input_image":"input_file",file_id:J.fileId}}function _Z(J){let Q=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return Q?.[1]!==void 0&&MZ.has(Q[1])}var MZ=new Set(["jpeg","jpg","png","gif","webp"]);function SZ(J){if(!J.id)return null;let Q={type:"reasoning",id:J.id};return Q.summary=J.text?[{type:"summary_text",text:J.text}]:[],Q}function AZ(J){if(J.status==="ok")return typeof J.output==="string"?J.output:JSON.stringify(J.output??null);if(J.status==="running"){let Q=J.job?.summary===void 0?"":` Started with: ${JSON.stringify(J.job.summary)}.`;return`Started background job ${J.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${Q}`}if(J.status==="denied"){let Q=J.reason?` Reason given: ${J.reason}`:"";if(J.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${Q}`;if(J.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${Q}`;return`The user declined this tool call, so it did not run.${Q}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function RZ(J,Q){let $=new Set(_8(J?.loaded)),Z=_8(J?.namespaces),W=new Set(Z),K=[];for(let Y of Q)if(qJ(Y)){if(!W.has(Y.name))continue;let V=Y.tools.filter((G)=>$.size===0||$.has(G.name));if(V.length===0)continue;K.push({type:"namespace",name:Y.name,description:Y.description,tools:V.map((G)=>s(G,!0))})}else if(Y.deferred&&$.has(Y.name))K.push(s(Y,!0));if(K.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:J.arguments&&typeof J.arguments==="object"?J.arguments:{paths:Z.length>0?Z:[...$]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function _8(J){return Array.isArray(J)?J.filter((Q)=>typeof Q==="string"):[]}function qJ(J){return Array.isArray(J.tools)}function TZ(J,Q){if(!J||J.length===0)return[];if(!Q.toolSearch){let W=[];for(let K of J)if(qJ(K))for(let X of K.tools)W.push(s(X,!1));else W.push(s(K,!1));return W}let $=[],Z=!1;for(let W of J)if(qJ(W)){let K=W.tools.map((X)=>{if(X.deferred)Z=!0;return s(X,!0)});$.push({type:"namespace",name:W.name,description:W.description,tools:K})}else{if(W.deferred)Z=!0;$.push(s(W,!0))}if(Z)$.push({type:"tool_search"});return $}function s(J,Q){let $={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if(Q&&J.deferred)$.defer_loading=!0;return $}class a{static models(){return[]}normalizeError(J){return E(J)}}var M8=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class jQ extends a{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=AQ(J),this.config=Q}static model(J,Q){return new jQ(J,Q)}static models(){return M8}stream(J){let Q=EQ(J,{model:this.model,capabilities:this.capabilities});return MQ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:NQ(J.messages)})}upload(J){return SQ(this.endpoint(),J)}endpoint(){return _Q(WJ(this.config))}get realtime(){return new XJ(WJ(this.config,{timeoutMs:RQ}),{model:this.model})}}class kQ extends a{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=AQ(J),this.config=Q}static model(J,Q){return new kQ(J,Q)}static models(){return M8}stream(J){let Q=EQ(J,{model:this.deployment(),capabilities:this.capabilities});return MQ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:NQ(J.messages)})}upload(J){return SQ(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return _Q(KJ(this.config))}get realtime(){return new XJ(a$(this.config,{timeoutMs:RQ}),{model:this.deployment(),callFlow:"ephemeral"})}}class xJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,Q){let $=this.entries.get(J);if($?.openUntil===void 0)return!0;let Z=this.now();if(Z<$.openUntil)return!1;if($.probeUntil!==void 0&&Z<$.probeUntil)return!1;return $.probeUntil=Z+Q.cooldownMs,!0}record(J,Q,$){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if(Q==="success")return this.entries.delete(J),W?"closed":void 0;if(Q==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=$.failures)return Z.openUntil=this.now()+$.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return"closed";return this.now()<Q.openUntil?"open":"half-open"}}var S8=Symbol("timed-out");class GJ extends a{model;capabilities;entries;options;circuit;constructor(J,Q={}){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($){let Z=$.failures??3,W=$.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let K=new Set;for(let Y of J){let V=qQ(Y);if(K.has(V))throw Error(`FallbackProvider: two legs share the circuit key "${V}". Give one of them a \`circuitKey\`.`);K.add(V)}let X=$.store??new xJ;this.options={...Q,circuit:{...$,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...$.onStateChange?{onStateChange:$.onStateChange}:{}}}else this.options=Q,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=EZ(J.map((Z)=>Z.provider.capabilities))}static chain(J,Q){return new GJ(J,Q)}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 Q=this.from(J).entries[0];return new GJ([Q],this.options)}upload(J){return this.entries[0].provider.upload(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let Q,$=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let K=this.entries[W],X=W===this.entries.length-1,Y=K.provider.model;if(this.circuit&&!X&&!await this.allow(K))continue;Z+=1;let V=!1,G=async(_)=>{if(V)return;V=!0,await this.record(W,K,_)},H=new AbortController,D=()=>H.abort($?.reason);if($?.aborted)H.abort($.reason);else $?.addEventListener("abort",D,{once:!0});let z=[],F=!1,O=!1,N,P,B,L=!1,U,j=!1,k=(_)=>{let R=Q?A(A(S(),Q),_.usage):_.usage;return Q=void 0,{..._,usage:R}};try{U=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let _=!0;for(;;){let R=_&&K.timeoutMs!==void 0?await jZ(U.next(),K.timeoutMs):await U.next();if(R===S8){L=!0,B={error:{code:"provider_error",message:`${Y} sent nothing within ${K.timeoutMs}ms.`,retryable:!0}};break}if(_=!1,R.done){j=!0;break}let C=R.value;if(C.type==="finish"&&C.model)P=C.model;if(F){if(C.type==="finish")N=A(N??S(),C.usage),O=!0,yield k(C);else{if(C.type==="error")B={error:C.error};yield C}continue}if(TJ(C)){F=!0,await G("success"),yield*z.splice(0),yield C;continue}if(C.type==="error")B={error:C.error,...C.status!==void 0?{status:C.status}:{},...C.requestId!==void 0?{requestId:C.requestId}:{}};else if(C.type==="finish"){if(N=A(N??S(),C.usage),C.reason==="error"&&!B)B={error:{code:"provider_error",message:`${Y} ended the call with an error and did not say which.`,retryable:!1}}}z.push(C)}}catch(_){let R=K.provider.normalizeError(_);if(F){if(R.code!=="aborted")yield{type:"error",error:R,...n(_)};this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:xQ(R),error:R}),yield k({type:"finish",reason:R.code==="aborted"?"aborted":"error",usage:S(),...P?{model:P}:{}});return}B={error:R,...n(_)}}finally{if($?.removeEventListener("abort",D),!j)H.abort(),U?.return?.()?.catch(()=>{})}if(F){if(!O&&Q)yield{type:"finish",reason:B?"error":"stop",usage:Q},Q=void 0;this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:B?xQ(B.error):"ok",...B?{error:B.error}:{}});return}if($?.aborted){await G("none"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:"aborted"}),yield k({type:"finish",reason:"aborted",usage:N??S(),...P?{model:P}:{}});return}if(!B){await G("success"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:"ok"});for(let _ of z)yield _.type==="finish"?k(_):_;return}let I=!X&&B.error.code!=="aborted"&&this.shouldFallBack(B.error,{index:W,model:Y,timedOut:L,...B.status!==void 0?{status:B.status}:{},...B.requestId!==void 0?{requestId:B.requestId}:{}});if(await G(I?"failure":"none"),this.report({index:W,model:Y,responseModel:P,attempt:Z,usage:N,outcome:I?"fallback":xQ(B.error),error:B.error}),I){if(N)Q=A(Q??S(),N);continue}let q=!1,d;for(let _ of z){if(_.type==="finish"){d=_;continue}if(_.type==="error")q=!0;yield _}if(!q&&B.error.code!=="aborted")yield{type:"error",error:B.error,...B.status!==void 0?{status:B.status}:{},...B.requestId!==void 0?{requestId:B.requestId}:{}};yield k({type:"finish",reason:B.error.code==="aborted"?"aborted":d?.reason??"error",usage:N??S(),...P?{model:P}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(qQ(J),this.circuit.policy)}catch{return!0}}async record(J,Q,$){if(!this.circuit)return;let Z=qQ(Q),W;try{W=await this.circuit.store.record(Z,$,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:Q.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,Q){let $=this.options.fallbackOn??((Z)=>Z.retryable);try{return $(J,Q)}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 qQ(J){return J.circuitKey??J.provider.model}function xQ(J){return J.code==="aborted"?"aborted":"failed"}function EZ(J){return{reasoning:J.every((Q)=>Q.reasoning),structuredOutput:J.every((Q)=>Q.structuredOutput),fileInput:J.every((Q)=>Q.fileInput),parallelToolCalls:J.every((Q)=>Q.parallelToolCalls),toolSearch:J.every((Q)=>Q.toolSearch)}}function jZ(J,Q){let $,Z=new Promise((W)=>{$=setTimeout(()=>W(S8),Q)});return Promise.race([J,Z]).finally(()=>clearTimeout($))}async function kZ(J,Q,$={}){let Z=$.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let K=0;K<J.entries.length;K++){let X=J.leg(K),Y={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{Y.results.push(await Q(X,{index:K,sample:V}))}catch(G){Y.errors.push({sample:V,error:G})}W.push(Y)}return W}class wJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var VJ="ask_agent",qZ={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},xZ={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 IJ=new Map;class p{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=S();transcription={usage:S(),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 p(J)}static get(J){return IJ.get(J)}static async endAll(J){await Promise.all([...IJ.values()].map((Q)=>Q.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...qZ,...A8(J.limits)},this.lines={...xZ,...A8(J.lines)},this.delegateName=J.delegate?.name??VJ;let Q=new Set(YJ(J.delegate).map(($)=>$.name));for(let $ of J.tools??[]){if(Q.has($.tool.name)||this.toolHandlers.has($.tool.name))throw Error(`VoiceBridge: two tools are named "${$.tool.name}".`);this.toolHandlers.set($.tool.name,$)}if("realtime"in J.call){let{realtime:$,callId:Z}=J.call;this.callId=Z,this.sideband=$.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(($)=>this.resolveEnded=$),IJ.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 Q=this.params.contextNote?.(J);if(Q)this.sideband.addNote(Q)}end(J="hangup",Q){return this.ending??=this.finish(J,Q??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 Q=J.usage;if(Q){this.usage=A(this.usage,Q);let $=this.info();this.hook(()=>this.params.onUsage?.(Q,$))}return}case"conversation.item.input_audio_transcription.completed":{let Q=J;if(this.say("user",String(Q.transcript??"")),Q.transcriptionUsage||Q.transcriptionSeconds!==void 0){this.transcription={usage:Q.transcriptionUsage?A(this.transcription.usage,Q.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+(Q.transcriptionSeconds??0)};let $=this.info(),Z={...Q.transcriptionUsage?{usage:Q.transcriptionUsage}:{},...Q.transcriptionSeconds!==void 0?{seconds:Q.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,$))}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 Q=J;if(this.touch(),!this.ending)this.call(Q.call_id,Q.name,Q.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let Q=J.error;if(this.errors.push({code:Q?.code,message:String(Q?.message??"")}),this.pendingCreate&&Q?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,Q.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let Q=J;if(!this.ending&&!Q.byClient)this.end(Q.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,Q){if(Q.trim())this.transcript.push({role:J,text:Q,at:Date.now()})}call(J,Q,$){let Z=IZ($);if(Q===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(Q);if(W)return void this.runTool(J,W,Z);switch(Q){case"stop_work":{let K=this.running;if(K)K.stopRequested=!0,K.handle?.stop({reason:"Stopped by voice."});let X=this.dropQueue();return this.answer(J,{stopped:Boolean(K),dropped:X})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((K)=>K.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(J,{status:"error",message:"There is no open question."});let K=typeof Z.answer==="string"?Z.answer:"",X=typeof Z.approve==="boolean"?Z.approve:void 0,Y=this.pending.map((V)=>wZ(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:Y},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${Q}.`})}}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 Q=new Set;await this.waitForThread(Q);let $=await this.latestBody();while(!J.stopRequested&&await this.waitForThread(Q));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:$,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(Q){J.record.status="done",this.complete(J,{status:"failed",message:Q instanceof Error?Q.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let Q=this.queue.shift();if(Q&&!this.ending)this.run(Q);else this.touch()}}async runTool(J,Q,$){let Z=Q.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let K={name:Z,status:"running"};this.toolCalls.push(K),this.toolsRunning+=1,this.pauseIdle();let X=new AbortController,Y=Q.timeoutMs??this.limits.toolTimeoutMs,V,G;try{let D=await Promise.race([Q.run($,{sessionId:this.sessionId,signal:X.signal}),new Promise((z,F)=>{V=setTimeout(()=>{F(new g(`"${Z}" took longer than ${Math.round(Y/1000)} s.`)),X.abort()},Y)})]);K.status="done",G={status:"done",output:this.clip(D)}}catch(D){if(D instanceof wJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let z=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=z,G={status:"failed",message:z}}finally{clearTimeout(V),K.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let H=this.info();if(this.hook(()=>this.params.onToolCall?.({...K},H)),!this.ending)this.answer(J,G)}clip(J){let Q;try{Q=JSON.stringify(J)}catch{return String(J)}if(Q===void 0||Q.length<=this.limits.toolOutputChars)return J;return`${Q.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${Q.length} characters in all)`}async waitForThread(J=new Set){let Q=this.params.liveRuns;if(!Q)return!1;let $=await Q.find({threadId:this.threadId}),Z=$&&!J.has($.runId)?Q.get($.runId):null;if(!$||!Z)return!1;return J.add($.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let Q=await J.get(this.sessionId).catch(()=>null);if(Q)this.body=Q.body;return this.body}async follow(J){let Q=this.params.progress??bZ();try{for await(let $ of J.run){let Z=Q($);if(Z)this.note(Z)}}catch{}}complete(J,Q){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,Q),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify(Q)}`);this.respond()}answer(J,Q){this.sideband.functionOutput(J,Q),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 Q of J)Q.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let Q=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if(Q<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),Q)}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(Q){if(Q instanceof wJ)this.end("usage",Q.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",Q),this.end("error",this.lines.error)}})}tampered(J){let Q=this.params.session;if(!Q||!J)return!1;if(Q.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==Q.instructions)return!0;if(Array.isArray(J.tools)){let $=new Set([...YJ(this.params.delegate),...Q.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if($.size!==Z.size||[...$].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,Q){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(),Q&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine(Q);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};IJ.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 Q;await Promise.race([this.sideband.closed,new Promise(($)=>Q=setTimeout($,this.limits.hangupGraceMs))]),clearTimeout(Q),this.sideband.close()}}async closingLine(J){await new Promise((Q)=>{let $=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",K,X=setTimeout(Y,this.limits.closingLineMs);function Y(){clearTimeout(X),Q()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:$,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(G)=>{let H=G;if(H.type==="sideband.closed")return Y();if(W==="cancelling"){if(H.type==="response.done"||H.type==="error"&&H.error?.event_id===Z)V();return}if(H.type==="error"&&H.error?.event_id===$)return Y();if(H.type==="response.created"&&!K){K=H.response?.id;return}let D=(z)=>!K||!z||z===K;if(H.type==="response.done"&&D(H.response?.id))W="playing";else if(H.type==="output_audio_buffer.stopped"&&W==="playing"&&D(H.response_id))Y()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function A8(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,Q])=>Q!==void 0))}function IZ(J){try{let Q=JSON.parse(J);return Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{}}catch{return{}}}function wZ(J,Q,$){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:Q};if(J.kind==="approval")return{...Z,approve:$===!0,...Q?{reason:Q}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function bZ(){let J=new Set;return(Q)=>{if(Q.type==="tool-call"){if(Q.part.partial||Q.resent||J.has(Q.part.toolCallId))return;return J.add(Q.part.toolCallId),`running ${String(Q.part.name)}`}if(Q.type==="tool-progress"){let $=Q.data;if(typeof $==="string")return $;if($&&typeof $==="object")for(let Z of["message","label","title"]){let W=$[Z];if(typeof W==="string"&&W)return W}}return}}var R8="http://gemi.internal/__gemi__/voice/mcp";async function IQ(J,Q){if(!Q.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:$}=J,Z=J.scopes??$.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:Q.user,via:"voice",id:`voice:${Q.sessionId}`,scopes:Z}});return(await $.available(W(T8()),J.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(Y,V)=>{let G=T8();return h.run(G,async()=>{return await J.authorize?.({name:X.name,input:Y,sessionId:V.sessionId}),$.execute(W(G),X.name,Y,void 0,{signal:V.signal})},{user:Q.user})}}))}function T8(){return new x(new Request(R8,{method:"POST"}),{},"api",new URL(R8).pathname)}class wQ{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 Q=this.records.get(J);return Q?structuredClone(Q):null}async update(J,Q){let $=this.records.get(J);if(!$)return;this.records.set(J,{...$,...structuredClone(Q),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[Q,$]of this.records)if($.endedAt!==void 0&&$.endedAt<J)this.records.delete(Q)}}var bQ=new wQ;class t extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,Q,$){super(`Frame ${Q} of run ${J} has been evicted; the oldest frame still buffered is ${$}. Reload the thread instead of resuming.`);this.runId=J;this.requested=Q;this.oldest=$}}class HJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class bJ{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,Q={}){let $={run:J,threadId:Q.threadId,owner:Q.owner??null,clientRunId:Q.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(Q.threadId,J.runId);if(Q.clientRunId)this.byClientRun.set(Q.clientRunId,J.runId);return this.scheduleExpiry($,Q.maxRunDurationMs),this.pump($,Q)}findByClientRunId(J){let Q=this.byClientRun.get(J);return Q&&this.runs.has(Q)?Q:null}async find(J){let Q=this.byThread.get(J.threadId);if(!Q)return null;let $=this.runs.get(Q);if(!$)return null;return{runId:Q,seq:$.lastSeq}}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,Q){let $=this.ownerOf(J);return $===null||$===Q}isRunning(J){let Q=this.runs.get(J);return!!Q&&!Q.ended&&!Q.evicted}replay(J,Q){let $=this.runs.get(J);if(!$)throw new HJ(J);if(Q!==void 0&&Q<$.lostBefore)throw new t(J,Q,$.lostBefore);let Z=$.frames[0]?.seq;return this.drain($,J,Q??Z??$.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,Q){let $=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let K=Q.onEvent;if(K)$=$.then(()=>K(Z.event)).catch((X)=>fQ(Q,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=Q.onEvent;if(W)$=$.then(()=>W(Z.event)).catch((K)=>fQ(Q,K))}}catch(Z){fQ(Q,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await $}}async*drain(J,Q,$){let Z=$;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new t(Q,Z,J.lostBefore);let K=J.frames,X=K[0]?.seq;if(X===void 0)break;let Y=Math.max(0,Z-X);if(Y>=K.length)break;let V=K[Y];yield V,Z=V.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,Q){if(J.version!==Q)return Promise.resolve();return new Promise(($)=>J.wake.add($))}notify(J){J.version++;let Q=Array.from(J.wake);J.wake.clear();for(let $ of Q)$()}scheduleEviction(J){if(J.evictAt)return;let Q=setTimeout(()=>{let $=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get($)===J)this.runs.delete($);if(J.threadId&&this.byThread.get(J.threadId)===$)this.byThread.delete(J.threadId);if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===$)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);Q.unref?.(),J.evictAt=Q}scheduleExpiry(J,Q){if(this.maxAgeMs===null||Q===null)return;let $=Q===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,Q+this.ttlMs);if(!Number.isFinite($)||$>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round($/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},$);Z.unref?.(),J.expireAt=Z}}var vQ=new bJ;function fQ(J,Q){try{J.onInternalError?.(Q)}catch{}}class fJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,Q){if(this.records.has(J))return;this.records.set(J,{...Q});while(this.records.size>this.maxEntries){let $=this.records.keys().next().value;if($===void 0)break;this.records.delete($)}}async get(J){let Q=this.records.get(J);return Q?{...Q}:null}}var yQ=new fJ;class uQ{now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,Q){let $=this.now();if(this.receipts.size>=this.sweepAt)this.sweep($);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>$)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:Q}),{status:"claimed"}}async complete(J,Q,$){this.receipts.set(J,{result:structuredClone(Q),expiresAt:$})}async release(J){let Q=this.receipts.get(J);if(Q&&!Q.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[Q,$]of this.receipts)if($.expiresAt<=J)this.receipts.delete(Q);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var E8="pending",hQ="done:",fZ=`
147
147
  if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
148
148
  local held = redis.call('GET', KEYS[1])
149
149
  if not held then return ARGV[1] end
150
150
  return held`,vZ=`
151
151
  if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
152
- return 0`;class cQ{injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,Q){let $=await this.client.send("EVAL",[fZ,"1",this.key(J),T8,E8(Q)]);if($==="claimed")return{status:"claimed"};let Z=String($??"");if(Z.startsWith(hQ))return{status:"replay",result:JSON.parse(Z.slice(hQ.length))};return{status:"blocked"}}async complete(J,Q,$){await this.client.send("SET",[this.key(J),hQ+JSON.stringify(Q),"PX",E8($)])}async release(J){await this.client.send("EVAL",[vZ,"1",this.key(J),T8])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=j8(),Q=J.bound(gQ)?J.make(gQ).client:void 0;if(!Q)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return Q}}function E8(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var yZ=86400000,hZ=60000;class vJ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??yZ,this.clientOwnedIds=J.clientOwnedIds??!1}async createThread(J){let Q=crypto.randomUUID();return this.threads.set(Q,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:Q}}async loadThread(J){this.sweep();let Q=this.threads.get(J);if(!Q)return this.clientOwnedIds?[]:null;return Q.touchedAt=Date.now(),Q.messages.slice()}async appendMessages(J,Q){this.sweep();let $=this.threads.get(J);if(!$){if(!this.clientOwnedIds)throw Error(`Thread ${J} does not exist here, or has expired.`);$={messages:[],touchedAt:Date.now()},this.threads.set(J,$)}for(let Z of Q){let W=$.messages.findIndex((K)=>K.id===Z.id);if(W===-1)$.messages.push(Z);else $.messages[W]=Z}$.touchedAt=Date.now()}async removeMessages(J,Q){this.sweep();let $=this.threads.get(J);if(!$)return;let Z=new Set(Q);$.messages=$.messages.filter((W)=>!Z.has(W.id)),$.touchedAt=Date.now()}async loadSummaries(J){return this.threads.get(J)?.summaries?.slice()??[]}async saveSummary(J,Q){let $=this.threads.get(J);if(!$)return;$.summaries=mQ($.summaries??[],Q)}delete(J){this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<hZ)return;this.lastSweep=J;for(let[Q,$]of this.threads)if(J-$.touchedAt>this.ttlMs)this.threads.delete(Q)}}var pQ=new vJ;function I8(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 w8(J,Q,$=new Date().toISOString()){if(!(Q.event.type==="run-start"&&Q.event.runId!==J.cursorRunId)&&Q.seq<=J.seq)return J;return{...b8(J,Q.event,$),seq:Q.seq}}function b8(J,Q,$){switch(Q.type){case"run-start":return{...J,messages:gZ(J.messages,Q.runId),runId:Q.runId,cursorRunId:Q.runId,threadId:Q.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return l(J,Q.messageId,$,(Z)=>({...Z,role:Q.role}));case"text-delta":if(q8(J,Q.messageId))return J;return l(J,Q.messageId,$,(Z)=>({...Z,content:lZ(Z.content,Q.delta)}));case"reasoning-delta":if(q8(J,Q.messageId))return J;return l(J,Q.messageId,$,(Z)=>({...Z,content:dZ(Z.content,Q.delta,Q.id)}));case"output-delta":return l(J,Q.messageId,$,(Z)=>({...Z,content:x8(Z.content,{type:"output",value:Q.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return l(J,Q.messageId,$,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===Q.part.toolCallId),K=W===-1?void 0:Z.content[W],X=Q.part.progress??K?.progress,Y=Q.part.nested??K?.nested,V=Q.part.attachments??K?.attachments,G={...Q.part,...X?{progress:X}:{},...Y?{nested:Y}:{},...V?{attachments:V}:{}},H=Z.content.slice();if(W===-1)H.push(G);else H[W]=G;return{...Z,content:H}});case"tool-search":{let Z=Q.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return k8(J,Q.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],Q.data]}));case"nested-event":{let Z=Q;return k8(J,Q.toolCallId,(W)=>{let K=W.nested??[],X=K.findIndex((H)=>H.runId===Z.runId),Y=K[X]??{runId:Z.runId,agent:Z.agent,messages:[]},V=mZ(Y,Z,$),G=X===-1?[...K,V]:K.map((H,D)=>D===X?V:H);return{...W,nested:G}})}case"tool-result":{let Z=l(J,Q.messageId,$,(W)=>({...W,content:x8(W.content,Q.part,(K)=>K.type==="tool-result"&&K.toolCallId===Q.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==Q.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((X)=>X.id===Q.message.id),W=J.messages.slice();if(Z===-1)W.push(Q.message);else W[Z]=Q.message;let K=J.runMessageIds.includes(Q.message.id)?J.runMessageIds:[...J.runMessageIds,Q.message.id];return{...J,messages:W,runMessageIds:K}}case"message-id":{let Z=J.messages.findIndex((Y)=>Y.id===Q.localId);if(Z===-1){if(!Q.message||J.messages.some((Y)=>Y.id===Q.messageId))return J;return{...J,messages:[...J.messages,Q.message]}}let W=J.messages[Z],K={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},X=J.messages.some((Y)=>Y.id===Q.messageId)?J.messages.filter((Y,V)=>V!==Z).map((Y)=>Y.id===Q.messageId?{...Y,...K}:Y):J.messages.map((Y,V)=>V===Z?{...Y,...K,id:Q.messageId}:Y);return{...J,messages:X}}case"awaiting-input":return{...J,runId:Q.runId,pending:[...Q.pending]};case"message-end":return l(J,Q.messageId,$,(Z)=>({...Z,finishReason:Q.finishReason,...Q.outputTruncated?{outputTruncated:!0}:{},...Q.usage?{usage:Q.usage}:{},content:Q.outputTruncated||Q.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:Q.usage};case"error":return{...J,error:Q.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:Q.finishReason,messages:f8(J,Q.finishReason)};default:return J}}function gZ(J,Q){if(!J.some(($)=>$.runId===Q&&$.finishReason===void 0))return J;return J.map(($)=>{if($.runId!==Q||$.finishReason!==void 0)return $;let{runId:Z,...W}=$;return{...W,content:[]}})}function f8(J,Q){return J.messages.map(($)=>$.role==="assistant"&&J.runMessageIds.includes($.id)?uZ($,Q):$)}function uZ(J,Q){let $=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?cZ(K,Q):K)}:W);if(J.finishReason===void 0)return{...J,finishReason:Q,content:$};return $.some((W,K)=>W!==J.content[K])?{...J,content:$}:J}function cZ(J,Q){let $={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:Q,messages:f8($,Q)}}function k8(J,Q,$){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],K=W.content.findIndex((G)=>G.type==="tool-call"&&G.toolCallId===Q);if(K===-1)continue;if(W.finishReason!==void 0&&!pZ(J,W,Q))return J;let X=W.content.slice();X[K]=$(X[K]);let Y=J.messages.slice();Y[Z]={...W,content:X};let V=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:V,messages:Y}}return J}function mZ(J,Q,$){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((K)=>K.id),loadedTools:[],finishReason:J.finishReason},W=b8(Z,Q.event,$);return{...J,...Q.label!==void 0?{label:Q.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function pZ(J,Q,$){if(Q.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===$))}function q8(J,Q){let $=J.messages.find((Z)=>Z.id===Q);return $!==void 0&&$.finishReason!==void 0}function l(J,Q,$,Z){let W=J.messages.findIndex((Y)=>Y.id===Q),K=J.runMessageIds.includes(Q)?J.runMessageIds:[...J.runMessageIds,Q];if(W===-1){let Y={id:Q,role:"assistant",content:[],createdAt:$};return{...J,runMessageIds:K,messages:[...J.messages,Z(Y)]}}let X=J.messages.slice();return X[W]=Z(X[W]),{...J,runMessageIds:K,messages:X}}function lZ(J,Q){let $=J[J.length-1];if($&&$.type==="text")return[...J.slice(0,-1),{type:"text",text:$.text+Q}];return[...J,{type:"text",text:Q}]}function dZ(J,Q,$){let Z=J[J.length-1];if(Z&&Z.type==="reasoning"&&Z.id===$)return[...J.slice(0,-1),{...Z,text:(Z.text??"")+Q}];return[...J,$?{type:"reasoning",id:$,text:Q}:{type:"reasoning",text:Q}]}function x8(J,Q,$){let Z=J.findIndex($);if(Z===-1)return[...J,Q];let W=J.slice();return W[Z]=Q,W}class dQ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,Q,$,Z){this.store=J;this.threadId=Q;this.report=Z;this.state=I8({messages:$})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[lQ(J)])}frame(J){if(this.closed)return;let Q=J.event;if(Q.type==="run-start")this.runId=Q.runId;switch(this.state=w8(this.state,J),Q.type){case"message":this.write(()=>[lQ(Q.message)]);return;case"tool-call":if(Q.part.partial)return;this.checkpoint(Q.messageId);return;case"message-start":case"tool-result":this.checkpoint(Q.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let Q of J)this.done.add(Q.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let Q=this.state.messages.find((Z)=>Z.id===J);if(!Q)return;let $=this.runId;this.write(()=>{let Z=lQ(Q);if(Z.finishReason===void 0&&$)Z.runId=$;return[Z]})}write(J){let Q;try{Q=J()}catch($){this.report($);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,Q)).catch(($)=>this.report($))}}function lQ(J){return structuredClone(J)}async function v8(J,Q){let $=[],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 Q(X.runId))continue;Z??=new Set(J.flatMap((G)=>G.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let Y=X.content.map((G)=>G.type==="tool-call"?y8(G):G);for(let G of X.content){if(G.type!=="tool-call"||Z.has(G.toolCallId))continue;let H={type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"interrupted"};Y.push(H)}let V={...X,content:Y,finishReason:"interrupted"};W[K]=V,$.push(V)}return{messages:W,settled:$}}function y8(J){let{partial:Q,...$}=J;if(!$.nested?.some((Z)=>Z.finishReason===void 0))return $;return{...$,nested:$.nested.map(iZ)}}function iZ(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map((Q)=>Q.role==="assistant"&&Q.finishReason===void 0?{...Q,finishReason:"interrupted",content:Q.content.map(($)=>$.type==="tool-call"?y8($):$)}:Q)}}var nZ=50,oZ=["running","ok","error"];async function u8(J,Q){let{store:$,threadId:Z}=Q,W=Math.max(nZ,Q.scan??0),K=await $.listForThread(Z,{limit:W}),X,Y=async(F)=>{if(F.state!=="running")return F;if(X??=await h8($),F.deadlineAt>X)return F;return await g8($,F),await $.get(F.id)??F};for(let F=0;F<K.length;F++)K[F]=await Y(K[F]);let V=new Map(K.map((F)=>[F.id,F])),G=J.slice(),H=[],D=new Set;for(let F=0;F<G.length;F++){let U=G[F],N=null;for(let P=0;P<U.content.length;P++){let B=U.content[P];if(B.type==="tool-call")D.add(B.toolCallId);if(B.type!=="tool-result"||B.status!=="running")continue;let L=B.job?.id,O=L?V.get(L):void 0;if(L&&O===void 0){let j=await $.get(L);if(O=j?await Y(j):void 0,O)V.set(L,O)}if(O?.state==="running")continue;N??=U.content.slice(),N[P]=sZ(B,O,Q.outputSchemaFor)}if(N){let P={...U,content:N};G[F]=P,H.push(P)}}let z=[];for(let F of K){if(F.orphaned||D.has(F.toolCallId))continue;if(await Q.isRunLive(F.runId))continue;z.push(F)}return{messages:G,settled:H,orphans:z,jobs:K}}async function c8(J,Q,$){for(let Z of Q)try{await J.transition(Z.id,oZ,{orphaned:!0})}catch(W){$(W)}}function sZ(J,Q,$){let Z={type:"tool-result",toolCallId:J.toolCallId,name:J.name};if(!Q)return{...Z,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 W={id:Q.id,...Q.summary!==void 0?{summary:Q.summary}:{},...Q.usage?{usage:Q.usage}:{}};if(Q.state==="error")return{...Z,status:"error",job:W,error:Q.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let K=$?.(String(J.name));if(K){let X=K.safeParse(Q.output);if(X.ok===!1)return{...Z,status:"error",job:W,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: ${X.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return{...Z,status:"ok",job:W,output:X.value}}return{...Z,status:"ok",job:W,output:Q.output}}class iJ extends Error{status;code;kind;constructor(J,Q){super(J);this.name="AgentTurnError",this.status=Q.status,this.code=Q.code,this.kind=Q.kind}static async from(J){let Q={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")Q=Z.error}catch{}let $=(Z)=>typeof Q[Z]==="string"?Q[Z]:void 0;return new iJ($("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:$("code"),kind:$("kind")})}}function aZ(J){for(let Q=J.length-1;Q>=0;Q--){let $=J[Q];if($.role!=="assistant")continue;return $.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var tZ=r8,yJ=new Map,m8=new WeakMap,zJ=new WeakMap,p8="http://gemi.internal/__gemi/agent-turn",hJ=new Map,rZ=4194304,eZ=1000,J0=5,gJ=65536,uJ=()=>{};class D9{byKey=new Map;take(J,Q,$){let Z=this.byKey.get(J);if(!Z?.has(Q)&&(Z?.size??0)>=$)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set(Q,(Z.get(Q)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let K=this.byKey.get(J),X=(K?.get(Q)??1)-1;if(!K)return;if(X>0)K.set(Q,X);else if(K.delete(Q),K.size===0)this.byKey.delete(J)}}}var l8=new WeakMap;function Q0(J){let Q=l8.get(J);if(!Q)Q=new D9,l8.set(J,Q);return Q}function $0(J){return J}class Q$ extends tZ{static kind="agent-controller";hooks;store=pQ;liveRuns=vQ;voice;voiceStore=bQ;attachments=dJ;attachmentStorage=Q9;fileOwners=yQ;nonces=rQ;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,Q){return this.hooks?.instructions?.(J,Q)}reasoning(J,Q){return this.hooks?.reasoning?.(J,Q)}skills(J,Q){return this.hooks?.skills?.(J,Q)}context(J,Q){let $=this.hooks?.context;if($)return $(J,Q);return{}}memoryScopes(J,Q){let $=this.hooks?.memoryScopes;if($)return $(J,Q);return{}}memoryMaxTokens=void 0;requireThread=!1;maxBodyBytes=rZ;maxHistoryMessages=eZ;contextWindow=void 0;prepareStep(J,Q){return this.hooks?.prepareStep?.(J,Q)}maxConcurrentRuns=J0;runLimitKey(J,Q){let $=this.hooks?.runLimitKey;if($)return $(J,Q);return Q.owner}authorizeRequest(J,Q){let $=this.hooks?.authorizeRequest;if($)return $(J,Q);return this.resource?.authorize(J,Q)}resource;runOwner(J){let Q=this.hooks?.runOwner;if(Q)return Q(J);let $=J.ctx?.()?.user,Z=$?.id??$?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(J){let{threadId:Q}=J;if(typeof Q!=="string"||Q==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let $={...J.turn,...J.text!==void 0?{text:J.text}:{}},Z={...J.body,threadId:Q,turn:$},W=new x(new Request(p8,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)}),{},"api",new URL(p8).pathname),K=new this;zJ.set(W,null);let X=await h.run(W,()=>K.stream(W),{user:J.user??null}),Y=zJ.get(W);if(!Y)throw await iJ.from(X);zJ.delete(W),X.body?.cancel().catch(uJ);let{run:V,hooks:G}=Y,H=[],D=(async()=>{for await(let F of V)if(F.type==="awaiting-input")H=F.pending})().catch(uJ),z;return{runId:V.runId,threadId:Q,run:V,stop:(F)=>V.stop(F),result:()=>z??=(async()=>{let F=await V.result();await Promise.all([G,D]);let U=F.messages;return{...F,threadId:Q,text:aZ(U),pending:F.finishReason==="awaiting-input"?H:[]}})()}}async stream(J=new x){let Q=await DJ(J,this.maxBodyBytes);if(Q.error)return r(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:void 0,W=H0($);if(W.error)return r({body:{},error:W.error});let K=W.turn,X=Z!==void 0&&$.regenerate===!0,Y=typeof $.clientRunId==="string"?$.clientRunId:void 0,V=cJ($);if(this.requireThread&&!Z)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(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($.messages)&&$.messages.length>this.maxHistoryMessages)return aQ(413,"history_too_long",`The conversation has ${$.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let G=await this.runOwner(J),H=Y?{cancelled:!1,owner:G}:null;if(H)hJ.set(Y,H);let D=null,z=[],F=async()=>{try{return await U()}finally{if(Z&&z.length>0&&D===null)await this.store.appendMessages(Z,z).catch((N)=>this.reportHookFailure(N))}},U=async()=>{let N,P=null;if(Z){let T=await this.store.loadThread(Z);if(!T)return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let i=await this.settleThread(Z,T,{write:!0});if(N=i.messages,P=this.jobsBlock(i.jobs),X){let e=P0(N);if(!e)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});z=N.slice(e.index),await this.store.removeMessages(Z,z.map((U9)=>U9.id)),N=N.slice(0,e.index),K=K?.localId?{...e.turn,localId:K.localId}:e.turn}}else N=Array.isArray($.messages)?$.messages:[],M0(this.nonces);let B=[await this.instructions(J,{body:V})||void 0,P??void 0].filter(Boolean).join(`
152
+ return 0`;class cQ{injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,Q){let $=await this.client.send("EVAL",[fZ,"1",this.key(J),E8,j8(Q)]);if($==="claimed")return{status:"claimed"};let Z=String($??"");if(Z.startsWith(hQ))return{status:"replay",result:JSON.parse(Z.slice(hQ.length))};return{status:"blocked"}}async complete(J,Q,$){await this.client.send("SET",[this.key(J),hQ+JSON.stringify(Q),"PX",j8($)])}async release(J){await this.client.send("EVAL",[vZ,"1",this.key(J),E8])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=k8(),Q=J.bound(gQ)?J.make(gQ).client:void 0;if(!Q)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return Q}}function j8(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var yZ=86400000,hZ=60000;class vJ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??yZ,this.clientOwnedIds=J.clientOwnedIds??!1}async createThread(J){let Q=crypto.randomUUID();return this.threads.set(Q,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:Q}}async loadThread(J){this.sweep();let Q=this.threads.get(J);if(!Q)return this.clientOwnedIds?[]:null;return Q.touchedAt=Date.now(),Q.messages.slice()}async appendMessages(J,Q){this.sweep();let $=this.threads.get(J);if(!$){if(!this.clientOwnedIds)throw Error(`Thread ${J} does not exist here, or has expired.`);$={messages:[],touchedAt:Date.now()},this.threads.set(J,$)}for(let Z of Q){let W=$.messages.findIndex((K)=>K.id===Z.id);if(W===-1)$.messages.push(Z);else $.messages[W]=Z}$.touchedAt=Date.now()}async removeMessages(J,Q){this.sweep();let $=this.threads.get(J);if(!$)return;let Z=new Set(Q);$.messages=$.messages.filter((W)=>!Z.has(W.id)),$.touchedAt=Date.now()}async loadSummaries(J){return this.threads.get(J)?.summaries?.slice()??[]}async saveSummary(J,Q){let $=this.threads.get(J);if(!$)return;$.summaries=mQ($.summaries??[],Q)}delete(J){this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<hZ)return;this.lastSweep=J;for(let[Q,$]of this.threads)if(J-$.touchedAt>this.ttlMs)this.threads.delete(Q)}}var pQ=new vJ;function w8(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 b8(J,Q,$=new Date().toISOString()){if(!(Q.event.type==="run-start"&&Q.event.runId!==J.cursorRunId)&&Q.seq<=J.seq)return J;return{...f8(J,Q.event,$),seq:Q.seq}}function f8(J,Q,$){switch(Q.type){case"run-start":return{...J,messages:gZ(J.messages,Q.runId),runId:Q.runId,cursorRunId:Q.runId,threadId:Q.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return l(J,Q.messageId,$,(Z)=>({...Z,role:Q.role}));case"text-delta":if(x8(J,Q.messageId))return J;return l(J,Q.messageId,$,(Z)=>({...Z,content:lZ(Z.content,Q.delta)}));case"reasoning-delta":if(x8(J,Q.messageId))return J;return l(J,Q.messageId,$,(Z)=>({...Z,content:dZ(Z.content,Q.delta,Q.id)}));case"output-delta":return l(J,Q.messageId,$,(Z)=>({...Z,content:I8(Z.content,{type:"output",value:Q.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return l(J,Q.messageId,$,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===Q.part.toolCallId),K=W===-1?void 0:Z.content[W],X=Q.part.progress??K?.progress,Y=Q.part.nested??K?.nested,V=Q.part.attachments??K?.attachments,G={...Q.part,...X?{progress:X}:{},...Y?{nested:Y}:{},...V?{attachments:V}:{}},H=Z.content.slice();if(W===-1)H.push(G);else H[W]=G;return{...Z,content:H}});case"tool-search":{let Z=Q.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return q8(J,Q.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],Q.data]}));case"nested-event":{let Z=Q;return q8(J,Q.toolCallId,(W)=>{let K=W.nested??[],X=K.findIndex((H)=>H.runId===Z.runId),Y=K[X]??{runId:Z.runId,agent:Z.agent,messages:[]},V=mZ(Y,Z,$),G=X===-1?[...K,V]:K.map((H,D)=>D===X?V:H);return{...W,nested:G}})}case"tool-result":{let Z=l(J,Q.messageId,$,(W)=>({...W,content:I8(W.content,Q.part,(K)=>K.type==="tool-result"&&K.toolCallId===Q.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==Q.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((X)=>X.id===Q.message.id),W=J.messages.slice();if(Z===-1)W.push(Q.message);else W[Z]=Q.message;let K=J.runMessageIds.includes(Q.message.id)?J.runMessageIds:[...J.runMessageIds,Q.message.id];return{...J,messages:W,runMessageIds:K}}case"message-id":{let Z=J.messages.findIndex((Y)=>Y.id===Q.localId);if(Z===-1){if(!Q.message||J.messages.some((Y)=>Y.id===Q.messageId))return J;return{...J,messages:[...J.messages,Q.message]}}let W=J.messages[Z],K={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},X=J.messages.some((Y)=>Y.id===Q.messageId)?J.messages.filter((Y,V)=>V!==Z).map((Y)=>Y.id===Q.messageId?{...Y,...K}:Y):J.messages.map((Y,V)=>V===Z?{...Y,...K,id:Q.messageId}:Y);return{...J,messages:X}}case"awaiting-input":return{...J,runId:Q.runId,pending:[...Q.pending]};case"message-end":return l(J,Q.messageId,$,(Z)=>({...Z,finishReason:Q.finishReason,...Q.outputTruncated?{outputTruncated:!0}:{},...Q.usage?{usage:Q.usage}:{},content:Q.outputTruncated||Q.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:Q.usage};case"error":return{...J,error:Q.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:Q.finishReason,messages:v8(J,Q.finishReason)};default:return J}}function gZ(J,Q){if(!J.some(($)=>$.runId===Q&&$.finishReason===void 0))return J;return J.map(($)=>{if($.runId!==Q||$.finishReason!==void 0)return $;let{runId:Z,...W}=$;return{...W,content:[]}})}function v8(J,Q){return J.messages.map(($)=>$.role==="assistant"&&J.runMessageIds.includes($.id)?uZ($,Q):$)}function uZ(J,Q){let $=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?cZ(K,Q):K)}:W);if(J.finishReason===void 0)return{...J,finishReason:Q,content:$};return $.some((W,K)=>W!==J.content[K])?{...J,content:$}:J}function cZ(J,Q){let $={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:Q,messages:v8($,Q)}}function q8(J,Q,$){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],K=W.content.findIndex((G)=>G.type==="tool-call"&&G.toolCallId===Q);if(K===-1)continue;if(W.finishReason!==void 0&&!pZ(J,W,Q))return J;let X=W.content.slice();X[K]=$(X[K]);let Y=J.messages.slice();Y[Z]={...W,content:X};let V=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:V,messages:Y}}return J}function mZ(J,Q,$){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((K)=>K.id),loadedTools:[],finishReason:J.finishReason},W=f8(Z,Q.event,$);return{...J,...Q.label!==void 0?{label:Q.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function pZ(J,Q,$){if(Q.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===$))}function x8(J,Q){let $=J.messages.find((Z)=>Z.id===Q);return $!==void 0&&$.finishReason!==void 0}function l(J,Q,$,Z){let W=J.messages.findIndex((Y)=>Y.id===Q),K=J.runMessageIds.includes(Q)?J.runMessageIds:[...J.runMessageIds,Q];if(W===-1){let Y={id:Q,role:"assistant",content:[],createdAt:$};return{...J,runMessageIds:K,messages:[...J.messages,Z(Y)]}}let X=J.messages.slice();return X[W]=Z(X[W]),{...J,runMessageIds:K,messages:X}}function lZ(J,Q){let $=J[J.length-1];if($&&$.type==="text")return[...J.slice(0,-1),{type:"text",text:$.text+Q}];return[...J,{type:"text",text:Q}]}function dZ(J,Q,$){let Z=J[J.length-1];if(Z&&Z.type==="reasoning"&&Z.id===$)return[...J.slice(0,-1),{...Z,text:(Z.text??"")+Q}];return[...J,$?{type:"reasoning",id:$,text:Q}:{type:"reasoning",text:Q}]}function I8(J,Q,$){let Z=J.findIndex($);if(Z===-1)return[...J,Q];let W=J.slice();return W[Z]=Q,W}class dQ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,Q,$,Z){this.store=J;this.threadId=Q;this.report=Z;this.state=w8({messages:$})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[lQ(J)])}frame(J){if(this.closed)return;let Q=J.event;if(Q.type==="run-start")this.runId=Q.runId;switch(this.state=b8(this.state,J),Q.type){case"message":this.write(()=>[lQ(Q.message)]);return;case"tool-call":if(Q.part.partial)return;this.checkpoint(Q.messageId);return;case"message-start":case"tool-result":this.checkpoint(Q.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let Q of J)this.done.add(Q.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let Q=this.state.messages.find((Z)=>Z.id===J);if(!Q)return;let $=this.runId;this.write(()=>{let Z=lQ(Q);if(Z.finishReason===void 0&&$)Z.runId=$;return[Z]})}write(J){let Q;try{Q=J()}catch($){this.report($);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,Q)).catch(($)=>this.report($))}}function lQ(J){return structuredClone(J)}async function y8(J,Q){let $=[],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 Q(X.runId))continue;Z??=new Set(J.flatMap((G)=>G.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let Y=X.content.map((G)=>G.type==="tool-call"?h8(G):G);for(let G of X.content){if(G.type!=="tool-call"||Z.has(G.toolCallId))continue;let H={type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"interrupted"};Y.push(H)}let V={...X,content:Y,finishReason:"interrupted"};W[K]=V,$.push(V)}return{messages:W,settled:$}}function h8(J){let{partial:Q,...$}=J;if(!$.nested?.some((Z)=>Z.finishReason===void 0))return $;return{...$,nested:$.nested.map(iZ)}}function iZ(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map((Q)=>Q.role==="assistant"&&Q.finishReason===void 0?{...Q,finishReason:"interrupted",content:Q.content.map(($)=>$.type==="tool-call"?h8($):$)}:Q)}}var nZ=50,oZ=["running","ok","error"];async function c8(J,Q){let{store:$,threadId:Z}=Q,W=Math.max(nZ,Q.scan??0),K=await $.listForThread(Z,{limit:W}),X,Y=async(F)=>{if(F.state!=="running")return F;if(X??=await g8($),F.deadlineAt>X)return F;return await u8($,F),await $.get(F.id)??F};for(let F=0;F<K.length;F++)K[F]=await Y(K[F]);let V=new Map(K.map((F)=>[F.id,F])),G=J.slice(),H=[],D=new Set;for(let F=0;F<G.length;F++){let O=G[F],N=null;for(let P=0;P<O.content.length;P++){let B=O.content[P];if(B.type==="tool-call")D.add(B.toolCallId);if(B.type!=="tool-result"||B.status!=="running")continue;let L=B.job?.id,U=L?V.get(L):void 0;if(L&&U===void 0){let j=await $.get(L);if(U=j?await Y(j):void 0,U)V.set(L,U)}if(U?.state==="running")continue;N??=O.content.slice(),N[P]=sZ(B,U,Q.outputSchemaFor)}if(N){let P={...O,content:N};G[F]=P,H.push(P)}}let z=[];for(let F of K){if(F.orphaned||D.has(F.toolCallId))continue;if(await Q.isRunLive(F.runId))continue;z.push(F)}return{messages:G,settled:H,orphans:z,jobs:K}}async function m8(J,Q,$){for(let Z of Q)try{await J.transition(Z.id,oZ,{orphaned:!0})}catch(W){$(W)}}function sZ(J,Q,$){let Z={type:"tool-result",toolCallId:J.toolCallId,name:J.name};if(!Q)return{...Z,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 W={id:Q.id,...Q.summary!==void 0?{summary:Q.summary}:{},...Q.usage?{usage:Q.usage}:{}};if(Q.state==="error")return{...Z,status:"error",job:W,error:Q.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let K=$?.(String(J.name));if(K){let X=K.safeParse(Q.output);if(X.ok===!1)return{...Z,status:"error",job:W,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: ${X.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return{...Z,status:"ok",job:W,output:X.value}}return{...Z,status:"ok",job:W,output:Q.output}}class iJ extends Error{status;code;kind;constructor(J,Q){super(J);this.name="AgentTurnError",this.status=Q.status,this.code=Q.code,this.kind=Q.kind}static async from(J){let Q={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")Q=Z.error}catch{}let $=(Z)=>typeof Q[Z]==="string"?Q[Z]:void 0;return new iJ($("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:$("code"),kind:$("kind")})}}function aZ(J){for(let Q=J.length-1;Q>=0;Q--){let $=J[Q];if($.role!=="assistant")continue;return $.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var tZ=e8,yJ=new Map,p8=new WeakMap,zJ=new WeakMap,l8="http://gemi.internal/__gemi/agent-turn",hJ=new Map,rZ=4194304,eZ=1000,J0=5,gJ=65536,uJ=()=>{};class F9{byKey=new Map;take(J,Q,$){let Z=this.byKey.get(J);if(!Z?.has(Q)&&(Z?.size??0)>=$)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set(Q,(Z.get(Q)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let K=this.byKey.get(J),X=(K?.get(Q)??1)-1;if(!K)return;if(X>0)K.set(Q,X);else if(K.delete(Q),K.size===0)this.byKey.delete(J)}}}var d8=new WeakMap;function Q0(J){let Q=d8.get(J);if(!Q)Q=new F9,d8.set(J,Q);return Q}function $0(J){return J}class Q$ extends tZ{static kind="agent-controller";hooks;store=pQ;liveRuns=vQ;voice;voiceStore=bQ;attachments=dJ;attachmentStorage=$9;fileOwners=yQ;nonces=rQ;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,Q){return this.hooks?.instructions?.(J,Q)}reasoning(J,Q){return this.hooks?.reasoning?.(J,Q)}skills(J,Q){return this.hooks?.skills?.(J,Q)}context(J,Q){let $=this.hooks?.context;if($)return $(J,Q);return{}}memoryScopes(J,Q){let $=this.hooks?.memoryScopes;if($)return $(J,Q);return{}}memoryMaxTokens=void 0;requireThread=!1;maxBodyBytes=rZ;maxHistoryMessages=eZ;contextWindow=void 0;prepareStep(J,Q){return this.hooks?.prepareStep?.(J,Q)}maxConcurrentRuns=J0;runLimitKey(J,Q){let $=this.hooks?.runLimitKey;if($)return $(J,Q);return Q.owner}authorizeRequest(J,Q){let $=this.hooks?.authorizeRequest;if($)return $(J,Q);return this.resource?.authorize(J,Q)}resource;runOwner(J){let Q=this.hooks?.runOwner;if(Q)return Q(J);let $=J.ctx?.()?.user,Z=$?.id??$?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(J){let{threadId:Q}=J;if(typeof Q!=="string"||Q==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let $={...J.turn,...J.text!==void 0?{text:J.text}:{}},Z={...J.body,threadId:Q,turn:$},W=new x(new Request(l8,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)}),{},"api",new URL(l8).pathname),K=new this;zJ.set(W,null);let X=await h.run(W,()=>K.stream(W),{user:J.user??null}),Y=zJ.get(W);if(!Y)throw await iJ.from(X);zJ.delete(W),X.body?.cancel().catch(uJ);let{run:V,hooks:G}=Y,H=[],D=(async()=>{for await(let F of V)if(F.type==="awaiting-input")H=F.pending})().catch(uJ),z;return{runId:V.runId,threadId:Q,run:V,stop:(F)=>V.stop(F),result:()=>z??=(async()=>{let F=await V.result();await Promise.all([G,D]);let O=F.messages;return{...F,threadId:Q,text:aZ(O),pending:F.finishReason==="awaiting-input"?H:[]}})()}}async stream(J=new x){let Q=await DJ(J,this.maxBodyBytes);if(Q.error)return r(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:void 0,W=H0($);if(W.error)return r({body:{},error:W.error});let K=W.turn,X=Z!==void 0&&$.regenerate===!0,Y=typeof $.clientRunId==="string"?$.clientRunId:void 0,V=cJ($);if(this.requireThread&&!Z)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(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($.messages)&&$.messages.length>this.maxHistoryMessages)return aQ(413,"history_too_long",`The conversation has ${$.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let G=await this.runOwner(J),H=Y?{cancelled:!1,owner:G}:null;if(H)hJ.set(Y,H);let D=null,z=[],F=async()=>{try{return await O()}finally{if(Z&&z.length>0&&D===null)await this.store.appendMessages(Z,z).catch((N)=>this.reportHookFailure(N))}},O=async()=>{let N,P=null;if(Z){let T=await this.store.loadThread(Z);if(!T)return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let i=await this.settleThread(Z,T,{write:!0});if(N=i.messages,P=this.jobsBlock(i.jobs),X){let e=P0(N);if(!e)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});z=N.slice(e.index),await this.store.removeMessages(Z,z.map((L9)=>L9.id)),N=N.slice(0,e.index),K=K?.localId?{...e.turn,localId:K.localId}:e.turn}}else N=Array.isArray($.messages)?$.messages:[],M0(this.nonces);let B=[await this.instructions(J,{body:V})||void 0,P??void 0].filter(Boolean).join(`
153
153
 
154
- `)||void 0,L=await this.context(J,{body:V}),O=await this.reasoning(J,{body:V})||void 0,j=await this.skills(J,{body:V})||void 0,k=await this.attachmentsFor(J,Z,{body:V}),I=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(H?.cancelled)return s8();let q=Z?new dQ(this.store,Z,N,(T)=>this.reportHookFailure(T)):null,d=`run_${crypto.randomUUID()}`,_={req:J,runId:d,threadId:Z},R={id:null,notified:Promise.resolve()},C=this.agent.stream({runId:d,messages:N,turn:K,threadId:Z,...q?{onMessage:(T)=>q.finish(T)}:{},onTurn:(T)=>{if(R.id!==null)return;R.id=T.id;let i=q?q.settled():Promise.resolve();R.notified=i.then(()=>this.safely(()=>this.onMessage(T,_)))},instructions:B,...O?{reasoning:O}:{},...j&&j.length>0?{skills:j}:{},context:L,attachments:k,body:V,redactError:(T,i)=>this.redactError(T,i,_),nonces:this.nonces,receipts:this.receipts,subject:G,...I?{memory:{scopes:I,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:G}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&z9(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==Q$.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(T)=>this.prepareStep(T,_)}:{}}),B9=this.liveRuns.register(C,{threadId:Z,owner:G,clientRunId:Y,onEvent:(T)=>this.dispatchEvent(T,_),onInternalError:(T)=>this.reportHookFailure(T),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=C,q)this.follow(C,q);let{stored:N9,hooks:$$}=this.persistRun(C,_,B9,q,R);if(m8.set(C,N9),zJ.has(J))zJ.set(J,{run:C,hooks:$$});return J.ctx?.()?.waitUntil($$),C.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let N=await this.foreignFile([...K?.files??[],...Z?[]:N0($.messages)],G);if(N)return N;if(H?.cancelled)return s8();let P=await this.runLimitKey(J,{owner:G,threadId:Z}),B=P===null?uJ:Q0(this.liveRuns).take(P,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!B)return aQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return Z?await this.withThread(Z,G,F):await F()}finally{let L=D;if(L)L.result().then(B,B);else B()}}finally{if(H&&hJ.get(Y)===H)hJ.delete(Y)}}async withThread(J,Q,$){let Z=yJ.get(J)??Promise.resolve(),W,K=new Promise((Y)=>{W=Y}),X=Z.then(()=>K);yJ.set(J,X),await Z;try{let Y=await this.liveRuns.find({threadId:J});if(Y&&this.liveRuns.isRunning(Y.runId)&&!this.liveRuns.mayAccess(Y.runId,Q))return FJ();let V=Y?this.liveRuns.get(Y.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await m8.get(V);return await $()}finally{if(W(),yJ.get(J)===X)yJ.delete(J)}}async attach(J=new x){let Q=await DJ(J,gJ);if(Q.error)return r(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:F0(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=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(J)))return FJ();if(!W)return M(404,{code:"no_live_run",message:`No run in progress for thread ${Z} in this process.`});let K=typeof $.runId==="string"?$.runId:void 0,X=K&&K!==W.runId?void 0:D0(J,$);try{return $9(this.liveRuns.replay(W.runId,X))}catch(Y){if(Y instanceof t)return M(410,{code:Y.code,message:Y.message,oldestSeq:Y.oldest});if(Y instanceof HJ)return M(404,{code:Y.code,message:Y.message});throw Y}}async stop(J=new x){let Q=await DJ(J,gJ);if(Q.error)return r(Q);let $=Q.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof $.threadId==="string"?$.threadId:void 0});let Z=await this.runOwner(J),W=typeof $.runId==="string"?$.runId:void 0;if(!W&&typeof $.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId($.clientRunId)??void 0,!W){let X=hJ.get($.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return FJ();return X.cancelled=!0,{stopped:!0}}}}if(!W&&typeof $.threadId==="string")W=(await this.liveRuns.find({threadId:$.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 $.reason==="string"?$.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(Q)return{key:`thread:${Q}`};return null}attachmentLimits(J){let Q=this.hooks?.attachmentLimits;if(Q)return Q(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 lJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new x){let Q=this.voice;if(!Q)return iQ();let $=await DJ(J,gJ);if($.error)return r($);let{sdp:Z,threadId:W,pushToTalk:K}=$.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=cJ($.body,U0),Y=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:Y,body:X});let V=J.ctx?.()?.user??null,G=await Q.start({req:J,body:X,threadId:Y,user:V,pushToTalk:K===!0}),H=Date.now(),D,z=async(L)=>{if(L!==void 0)console.error("[gemi/ai] a voice session could not start.",L);if(D)await Q.realtime.hangup(D).catch((O)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",O)});try{await G.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:G.threadId??Y??"",reason:"start_failed",startedAt:H,endedAt:Date.now(),durationMs:0,seconds:0,usage:S(),transcription:{usage:S(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(O){console.error("[gemi/ai] a voice session's onEnd threw.",O)}},F=G.threadId??Y;if(!F)return await z(void 0),M(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(F!==Y)await this.authorizeRequest(J,{route:"stream",threadId:F,body:X})}catch(L){throw await z(void 0),L}let U=crypto.randomUUID(),N=G.tools??[];try{if(G.mcp)N=[...N,...await IQ(G.mcp,{user:V,sessionId:U})]}catch(L){return await z(L),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...G.session,tools:[...YJ(Q.delegate),...G.session?.tools??[],...N.map((L)=>L.tool)],...K===!0?{turnDetection:null}:{}},B;try{B=await Q.realtime.createCall({sdp:Z,session:P,safetyIdentifier:G.safetyIdentifier})}catch(L){await z(L);let O=L instanceof f&&L.code==="rate_limited";return M(O?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=B.callId;try{await this.voiceStore.create({id:U,callId:B.callId,threadId:F,owner:await this.runOwner(J),body:X,startedAt:H});let{threadId:L,session:O,safetyIdentifier:j,mcp:k,tools:I,...q}=G;return{sessionId:p.start({...q,tools:N,controller:this.constructor,threadId:F,user:V,body:X,call:{realtime:Q.realtime,callId:B.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:Q.delegate,session:P}).sessionId,sdp:B.sdpAnswer,threadId:F,delegate:Q.delegate?.name??VJ,endsAt:H+(G.limits?.maxDurationMs??900000)}}catch(L){return await z(L),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new x){if(!this.voice)return iQ();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;let $=await DJ(J,gJ);if($.error)return r($);let Z=cJ($.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Z}),Q.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update(Q.id,{body:Z}),p.get(Q.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new x){let Q=this.voice;if(!Q)return iQ();let $=await this.voiceSession(J);if($ instanceof Response)return $;if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:$.body}),$.endedAt!==void 0)return{ended:!1};let Z=p.get($.id);if(Z)await Z.end("hangup");else await Q.realtime.hangup($.callId),await this.voiceStore.update($.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let Q=J.params?.sessionId,$=typeof Q==="string"&&Q?await this.voiceStore.get(Q):null;if(!$)return M(404,{code:"voice_not_found",message:"No such voice session."});if($.owner!==null&&$.owner!==await this.runOwner(J))return FJ();return $}async upload(J=new x){let Q=await J.rawRequest.formData(),$=Q.get("file");if(!($ instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=$ instanceof File&&$.name?$.name:"upload",W=$.type||"application/octet-stream",K=W0(Q.get("body")),X=Q.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:K});let Y=X0(await this.attachmentLimits(J),$,Z,W);if(Y)throw new sQ(Y.code,Y.message);let V=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,G=await this.runOwner(J),H=(k)=>this.fileOwners.record(k,{owner:G,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString()}),D={body:K,threadId:V},z=await this.checkUpload({name:Z,size:$.size,mimeType:W},J,D);if(z)throw new sQ(z.code||"upload_refused",z.message);let F=await this.attachmentDestination($,J,D),U=L0(F,Q.get("destination")),N=await this.attachmentScope(J,V,{body:K}),P=U!=="provider"&&!N;if(P){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()`.');O0()}if(U==="provider"||!N){let k=await d8(this.agent.provider,$);await H(k);let I={fileId:k,name:Z,mimeType:W,size:$.size,destination:"provider"};if(P)I.downgraded="no_scope";return I}let B=Y9(),L=await this.attachmentStorage.put({name:V9(B,Z),body:$,contentType:W}),O=U==="both"?await d8(this.agent.provider,$):void 0;if(O)await H(O);let j={id:B,scopeKey:N.key,fileId:O,objectName:L,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString(),destination:U};return await this.attachments.put(N,j),{fileId:O,attachmentId:B,name:Z,mimeType:W,size:$.size,destination:U}}async foreignFile(J,Q){let $=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of $){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==Q:this.requireKnownFiles)return B0()}return null}onMessage(J,Q){return this.hooks?.onMessage?.(J,Q)}onToolCall(J,Q){return this.hooks?.onToolCall?.(J,Q)}onAwaitingInput(J,Q){return this.hooks?.onAwaitingInput?.(J,Q)}redactError(J,Q,$){let Z=this.hooks?.redactError;if(Z)return Z(J,Q,$);return eQ(J,Q)}onError(J,Q){return this.hooks?.onError?.(J,Q)}onStreamComplete(J,Q){return this.hooks?.onStreamComplete?.(J,Q)}reportHookFailure(J){let Q=this.hooks?.reportHookFailure;if(Q)try{return Q(J)}catch($){console.error("[gemi/ai] reportHookFailure hook failed",$)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,Q){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},Q);return;case"awaiting-input":await this.onAwaitingInput(J.pending,Q);return;case"error":await this.onError(K9(J.error),Q);return;default:return}}async readThread(J){let Q=await this.store.loadThread(J);return Q?(await this.settleThread(J,Q,{write:!1})).messages:null}isRunLive(J,Q){return this.liveRuns.get(J)!==null}async settleThread(J,Q,{write:$}){let Z=(V)=>this.isRunLive(V,J),W=await v8(Q,Z),K=W.messages,X=[],Y=new Map(W.settled.map((V)=>[V.id,V]));if(S0(K)||$)try{let V=await u8(K,{threadId:J,store:v.store,isRunLive:Z,outputSchemaFor:(G)=>this.toolOutputSchema(G),scan:this.jobsBlockMax()});K=V.messages,X=V.jobs;for(let G of V.settled)Y.set(G.id,G);if($&&V.orphans.length>0){await c8(v.store,V.orphans,(H)=>this.reportHookFailure(H));let G=new Set(V.orphans.map((H)=>H.id));X=X.map((H)=>G.has(H.id)?{...H,orphaned:!0}:H)}}catch(V){this.reportHookFailure(V)}if($&&Y.size>0)try{await this.store.appendMessages(J,[...Y.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:X}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??BJ}jobsBlock(J){return V$(J,this.jobsBlockMax())}toolOutputSchema(J){let Q=($)=>{for(let Z of $){let W=Z;if(Array.isArray(W.tools)){let K=Q(W.tools);if(K)return K}else if(W.name===J)return W.outputSchema}return};return Q(this.agent.tools??[])}follow(J,Q){(async()=>{try{for await(let $ of J.frames())Q.frame($)}catch($){this.reportHookFailure($)}})()}persistRun(J,Q,$,Z=null,W={id:null,notified:Promise.resolve()}){let K=Promise.resolve(),X=(async()=>{let V;try{V=await J.result()}catch(H){Z?.close(),await Z?.settled(),K=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},Q)));return}let G=V.messages;if(Z?.close(G),await Z?.settled(),Q.threadId&&G.length>0)try{await this.store.appendMessages(Q.threadId,G)}catch(H){this.reportHookFailure(H)}K=this.notifyRun(V,G,Q,W)})(),Y=X.then(()=>_0(Promise.all([K,$]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:Y}}async notifyRun(J,Q,$,Z){await Z.notified;for(let W of Q){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,$))}await this.safely(()=>this.onStreamComplete(J,$))}async safely(J){try{await J()}catch(Q){this.reportHookFailure(Q)}}}var nQ=["turn","clientRunId","threadId","messages","regenerate"],Z0=["text","files","toolResults"];function cJ(J,Q=P9(J)?nQ:[...nQ,...Z0]){let $={};for(let[Z,W]of Object.entries(J)){if(Q.includes(Z))continue;Object.defineProperty($,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return $}function W0(J){if(J===null)return{};let Q;if(typeof J==="string")try{Q=JSON.parse(J)}catch{throw new oQ("The upload's `body` field is not valid JSON.")}if(Q===null||typeof Q!=="object"||Array.isArray(Q))throw new oQ("The upload's `body` field must be a JSON object.");return cJ(Q,nQ)}class oQ extends mJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function d8(J,Q){try{return await J.upload(Q)}catch($){if($ instanceof w&&K0.has($.status))throw new F9(E($).message);throw $}}var K0=new Set([400,413,415,422]);class sQ extends mJ{constructor(J,Q){super(Q);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:Q}}},view:{}}}}function X0(J,Q,$,Z){if(!J)return null;let{maxBytes:W,accept:K}=J;if(typeof W==="number"&&Q.size>W)return{code:"file_too_large",message:`${JSON.stringify($)} is ${i8(Q.size)}; the limit is ${i8(W)}.`};if(K&&K.length>0&&!K.some((X)=>G0(X,$,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify($)} is not a type this chat accepts. Accepted: ${K.join(", ")}.`};return null}function G0(J,Q,$){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return Q.toLowerCase().endsWith(Z);let W=$.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function i8(J){if(J<1024)return`${J} B`;let Q=["KB","MB","GB"],$=J/1024,Z=0;while($>=1024&&Z<Q.length-1)$/=1024,Z++;return`${Math.round($*10)/10} ${Q[Z]}`}class F9 extends mJ{constructor(J){super(J);this.name="RejectedUploadError";let Q=/(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:Q,message:J}}},view:{}}}}async function DJ(J,Q){let $=J?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!Y0($.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($.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>Q)return n8(Q);let W;try{let X=await V0($,Q);if(X===null)return n8(Q);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 Y0(J){return J9(J)==="application/json"}async function V0(J,Q){if(!Number.isFinite(Q)||!J.body)return await J.text();let $=J.body.getReader(),Z=[],W=0;for(;;){let{done:Y,value:V}=await $.read();if(Y)break;if(W+=V.byteLength,W>Q)return await $.cancel().catch(uJ),null;Z.push(V)}let K=new Uint8Array(W),X=0;for(let Y of Z)K.set(Y,X),X+=Y.byteLength;return new TextDecoder().decode(K)}function n8(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function aQ(J,Q,$){return M(J,{...pJ(e8(J),$,J),code:Q})}function r(J){if(J.status===413)return aQ(413,J.code??"body_too_large",J.error??"");return M(J.status??400,{code:J.code??"invalid_request",message:J.error})}function P9(J){return Boolean(J.turn)&&typeof J.turn==="object"}function H0(J){let Q=P9(J)?J.turn:J,$={};if(typeof Q.text==="string")$.text=Q.text;if(Array.isArray(Q.files)){let Z=z0(Q.files);if(typeof Z==="string")return{error:Z};$.files=Z}if(Array.isArray(Q.toolResults))$.toolResults=Q.toolResults;if(Object.keys($).length===0)return{};if(Q===J.turn&&Q.localId!==void 0&&Q.localId!==null&&Q.localId!==""){let{localId:Z}=Q;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>o8)return{error:`turn.localId is longer than ${o8} characters.`};$.localId=Z}return{turn:$}}var o8=200;function z0(J){let Q=[];for(let[$,Z]of J.entries()){let W=`turn.files[${$}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let K={};for(let H of["fileId","attachmentId","name","mimeType"]){let D=Z[H];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${H} must be a string.`;K[H]=D}let{fileId:X,attachmentId:Y,name:V,mimeType:G}=K;if(X?.startsWith(m))return`${W}.fileId holds a gemi attachment id (${X}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(Y!==void 0&&!Y.startsWith(m))return`${W}.attachmentId is not a gemi attachment id: it must start with "${m}".`;if(!X&&!Y)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;Q.push({...X?{fileId:X}:{},...Y?{attachmentId:Y}:{},...V!==void 0?{name:V}:{},...G!==void 0?{mimeType:G}:{}})}return Q}function D0(J,Q){if(typeof Q.from==="number"&&Number.isFinite(Q.from))return Math.max(0,Math.floor(Q.from));if(typeof Q.cursor==="number"&&Number.isFinite(Q.cursor)){let Z=Math.floor(Q.cursor);if(Z>=0)return Z+1;return}let $=J?.rawRequest?.headers?.get("Last-Event-ID");if($){let Z=Number.parseInt($,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function F0(J,Q){let $=J?.search?.get(Q);return typeof $==="string"?$:void 0}function P0(J){let Q=J$(J);for(let $=J.length-1;$>=0;$--){let Z=J[$];if(Z.role!=="user"||Q.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:$,turn:{...W?{text:W}:{},...K.length>0?{files:K}:{}}}}return null}function s8(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function FJ(){return M(403,pJ("permission","This run belongs to someone else.",403))}function B0(){return M(403,pJ("permission","A file in this turn was uploaded by someone else.",403))}function N0(J){if(!Array.isArray(J))return[];let Q=[];for(let $ of J){let Z=$?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")Q.push({fileId:W.fileId})}return Q}var U0=["sdp","threadId","pushToTalk"];function iQ(){return M(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function M(J,Q){return new Response(JSON.stringify({error:Q}),{status:J,headers:{"Content-Type":"application/json"}})}function L0(J,Q){if(typeof Q!=="string"||Q.length===0)return J;if(Q!=="both"&&Q!=="provider"&&Q!=="storage")throw Error(`Unknown attachment destination "${Q}". Expected "both", "provider" or "storage".`);if(Q===J||J==="both"&&Q==="storage")return Q;if(J==="both"&&Q==="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 "${Q}" 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 a8=!1;function O0(){if(a8)return;a8=!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 C0=2147483647;function _0(J,Q){let $=J.then(()=>{},()=>{});if(!(Q<=C0))return $;let Z,W=new Promise((K)=>{Z=setTimeout(K,Q)});return Promise.race([$,W]).finally(()=>clearTimeout(Z))}var t8=!1;function M0(J){if(t8||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof tQ))return;t8=!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 S0(J){return J.some((Q)=>Q.content.some(($)=>$.type==="tool-result"&&$.status==="running"))}export{I0 as windowMessages,YJ as voiceTools,E0 as turnStarts,EJ as toRealtimeUsage,f9 as toAgentTools,T0 as supportsStrict,j0 as splitTurns,g0 as settleSummaries,R0 as s,eQ as redactError,k0 as messageSize,ZJ as measureUsage,IQ as mcpVoiceTools,vQ as liveRuns,mQ as keepSummary,O8 as isCallNotFound,J$ as injectedMessageIds,GQ as generate,kZ as evalChain,$0 as defineAgentHooks,bQ as defaultVoiceStore,h0 as defaultSummaryStore,rQ as defaultNonceStore,yQ as defaultFileOwners,dJ as defaultAttachmentStore,pQ as defaultAgentStore,wJ as VoiceHangup,p as VoiceBridge,VQ as ToolNamespace,g as ToolError,c0 as Skill,lJ as ScopedAttachments,m0 as SKILLS_NAMESPACE,cQ as RedisReceiptStore,Z9 as RedisNonceStore,jJ as RealtimeSideband,f as RealtimeRequestError,XJ as RealtimeClient,X$ as Prompt,W9 as PrismaNonceStore,u0 as PendingEscalation,jQ as OpenAIProvider,PQ as OpenAIImageProvider,wQ as MemoryVoiceSessionStore,y0 as MemorySummaryStore,uQ as MemoryReceiptStore,tQ as MemoryNonceStore,bJ as MemoryLiveRuns,fJ as MemoryFileOwners,xJ as MemoryCircuitStore,H9 as MemoryAttachmentStore,vJ as MemoryAgentStore,F$ as MemoryAgentJobStore,q$ as MEMORY_NAMESPACE,HJ as LiveRunNotFoundError,B$ as JobsRequireThreadError,P$ as JobHandle,A0 as JSONSchemaError,G9 as InvalidAttachmentScopeError,A$ as InMemoryAgentMemoryStore,AJ as ImageRequestError,RJ as ImageProvider,HQ as ImageModel,t as FrameCursorEvictedError,GJ as FallbackProvider,j$ as FakeAgentMemoryStore,_J as Eval,QQ as DatabaseAgentMemoryStore,eJ as DatabaseAgentJobStore,U8 as DEFAULT_TRANSCRIPTION_MODEL,S$ as DEFAULT_MEMORY_MAX_TOKENS,k$ as DEFAULT_MEMORY_LIMITS,w0 as DEFAULT_MAX_SUMMARY_TOKENS,p0 as DEFAULT_MAX_RUN_DURATION_MS,N$ as DEFAULT_JOB_DEADLINE_MS,BJ as DEFAULT_JOBS_CONTEXT_MAX,VJ as DEFAULT_DELEGATE_NAME,q0 as DEFAULT_CONTEXT_WINDOW_STEP,x0 as DEFAULT_CONTEXT_WINDOW_NOTE,b0 as DEFAULT_COMPACT_TRIGGER_TOKENS,f0 as DEFAULT_COMPACT_INSTRUCTIONS,v0 as COMPACT_SUMMARY_HEADER,kQ as AzureOpenAIProvider,BQ as AzureOpenAIImageProvider,X9 as AttachmentNotFoundError,iJ as AgentTurnError,MJ as AgentTool,l0 as AgentRunError,a as AgentProvider,R$ as AgentMemoryRefusedError,T$ as AgentMemoryConflictError,E$ as AgentMemories,v as AgentJobs,aJ as AgentJobDeadlineSweep,U$ as AgentJob,Q$ as AgentController,d0 as Agent};
154
+ `)||void 0,L=await this.context(J,{body:V}),U=await this.reasoning(J,{body:V})||void 0,j=await this.skills(J,{body:V})||void 0,k=await this.attachmentsFor(J,Z,{body:V}),I=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(H?.cancelled)return a8();let q=Z?new dQ(this.store,Z,N,(T)=>this.reportHookFailure(T)):null,d=`run_${crypto.randomUUID()}`,_={req:J,runId:d,threadId:Z},R={id:null,notified:Promise.resolve()},C=this.agent.stream({runId:d,messages:N,turn:K,threadId:Z,...q?{onMessage:(T)=>q.finish(T)}:{},onTurn:(T)=>{if(R.id!==null)return;R.id=T.id;let i=q?q.settled():Promise.resolve();R.notified=i.then(()=>this.safely(()=>this.onMessage(T,_)))},instructions:B,...U?{reasoning:U}:{},...j&&j.length>0?{skills:j}:{},context:L,attachments:k,body:V,redactError:(T,i)=>this.redactError(T,i,_),nonces:this.nonces,receipts:this.receipts,subject:G,...I?{memory:{scopes:I,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:G}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&D9(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==Q$.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(T)=>this.prepareStep(T,_)}:{}}),N9=this.liveRuns.register(C,{threadId:Z,owner:G,clientRunId:Y,onEvent:(T)=>this.dispatchEvent(T,_),onInternalError:(T)=>this.reportHookFailure(T),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=C,q)this.follow(C,q);let{stored:O9,hooks:$$}=this.persistRun(C,_,N9,q,R);if(p8.set(C,O9),zJ.has(J))zJ.set(J,{run:C,hooks:$$});return J.ctx?.()?.waitUntil($$),C.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let N=await this.foreignFile([...K?.files??[],...Z?[]:N0($.messages)],G);if(N)return N;if(H?.cancelled)return a8();let P=await this.runLimitKey(J,{owner:G,threadId:Z}),B=P===null?uJ:Q0(this.liveRuns).take(P,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!B)return aQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return Z?await this.withThread(Z,G,F):await F()}finally{let L=D;if(L)L.result().then(B,B);else B()}}finally{if(H&&hJ.get(Y)===H)hJ.delete(Y)}}async withThread(J,Q,$){let Z=yJ.get(J)??Promise.resolve(),W,K=new Promise((Y)=>{W=Y}),X=Z.then(()=>K);yJ.set(J,X),await Z;try{let Y=await this.liveRuns.find({threadId:J});if(Y&&this.liveRuns.isRunning(Y.runId)&&!this.liveRuns.mayAccess(Y.runId,Q))return FJ();let V=Y?this.liveRuns.get(Y.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await p8.get(V);return await $()}finally{if(W(),yJ.get(J)===X)yJ.delete(J)}}async attach(J=new x){let Q=await DJ(J,gJ);if(Q.error)return r(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:F0(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=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(J)))return FJ();if(!W)return M(404,{code:"no_live_run",message:`No run in progress for thread ${Z} in this process.`});let K=typeof $.runId==="string"?$.runId:void 0,X=K&&K!==W.runId?void 0:D0(J,$);try{return Z9(this.liveRuns.replay(W.runId,X))}catch(Y){if(Y instanceof t)return M(410,{code:Y.code,message:Y.message,oldestSeq:Y.oldest});if(Y instanceof HJ)return M(404,{code:Y.code,message:Y.message});throw Y}}async stop(J=new x){let Q=await DJ(J,gJ);if(Q.error)return r(Q);let $=Q.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof $.threadId==="string"?$.threadId:void 0});let Z=await this.runOwner(J),W=typeof $.runId==="string"?$.runId:void 0;if(!W&&typeof $.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId($.clientRunId)??void 0,!W){let X=hJ.get($.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return FJ();return X.cancelled=!0,{stopped:!0}}}}if(!W&&typeof $.threadId==="string")W=(await this.liveRuns.find({threadId:$.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 $.reason==="string"?$.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(Q)return{key:`thread:${Q}`};return null}attachmentLimits(J){let Q=this.hooks?.attachmentLimits;if(Q)return Q(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 lJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new x){let Q=this.voice;if(!Q)return iQ();let $=await DJ(J,gJ);if($.error)return r($);let{sdp:Z,threadId:W,pushToTalk:K}=$.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=cJ($.body,O0),Y=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:Y,body:X});let V=J.ctx?.()?.user??null,G=await Q.start({req:J,body:X,threadId:Y,user:V,pushToTalk:K===!0}),H=Date.now(),D,z=async(L)=>{if(L!==void 0)console.error("[gemi/ai] a voice session could not start.",L);if(D)await Q.realtime.hangup(D).catch((U)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",U)});try{await G.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:G.threadId??Y??"",reason:"start_failed",startedAt:H,endedAt:Date.now(),durationMs:0,seconds:0,usage:S(),transcription:{usage:S(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(U){console.error("[gemi/ai] a voice session's onEnd threw.",U)}},F=G.threadId??Y;if(!F)return await z(void 0),M(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(F!==Y)await this.authorizeRequest(J,{route:"stream",threadId:F,body:X})}catch(L){throw await z(void 0),L}let O=crypto.randomUUID(),N=G.tools??[];try{if(G.mcp)N=[...N,...await IQ(G.mcp,{user:V,sessionId:O})]}catch(L){return await z(L),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...G.session,tools:[...YJ(Q.delegate),...G.session?.tools??[],...N.map((L)=>L.tool)],...K===!0?{turnDetection:null}:{}},B;try{B=await Q.realtime.createCall({sdp:Z,session:P,safetyIdentifier:G.safetyIdentifier})}catch(L){await z(L);let U=L instanceof f&&L.code==="rate_limited";return M(U?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=B.callId;try{await this.voiceStore.create({id:O,callId:B.callId,threadId:F,owner:await this.runOwner(J),body:X,startedAt:H});let{threadId:L,session:U,safetyIdentifier:j,mcp:k,tools:I,...q}=G;return{sessionId:p.start({...q,tools:N,controller:this.constructor,threadId:F,user:V,body:X,call:{realtime:Q.realtime,callId:B.callId},sessionId:O,store:this.voiceStore,liveRuns:this.liveRuns,delegate:Q.delegate,session:P}).sessionId,sdp:B.sdpAnswer,threadId:F,delegate:Q.delegate?.name??VJ,endsAt:H+(G.limits?.maxDurationMs??900000)}}catch(L){return await z(L),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new x){if(!this.voice)return iQ();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;let $=await DJ(J,gJ);if($.error)return r($);let Z=cJ($.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Z}),Q.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update(Q.id,{body:Z}),p.get(Q.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new x){let Q=this.voice;if(!Q)return iQ();let $=await this.voiceSession(J);if($ instanceof Response)return $;if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:$.body}),$.endedAt!==void 0)return{ended:!1};let Z=p.get($.id);if(Z)await Z.end("hangup");else await Q.realtime.hangup($.callId),await this.voiceStore.update($.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let Q=J.params?.sessionId,$=typeof Q==="string"&&Q?await this.voiceStore.get(Q):null;if(!$)return M(404,{code:"voice_not_found",message:"No such voice session."});if($.owner!==null&&$.owner!==await this.runOwner(J))return FJ();return $}async upload(J=new x){let Q=await J.rawRequest.formData(),$=Q.get("file");if(!($ instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=$ instanceof File&&$.name?$.name:"upload",W=$.type||"application/octet-stream",K=W0(Q.get("body")),X=Q.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:K});let Y=X0(await this.attachmentLimits(J),$,Z,W);if(Y)throw new sQ(Y.code,Y.message);let V=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,G=await this.runOwner(J),H=(k)=>this.fileOwners.record(k,{owner:G,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString()}),D={body:K,threadId:V},z=await this.checkUpload({name:Z,size:$.size,mimeType:W},J,D);if(z)throw new sQ(z.code||"upload_refused",z.message);let F=await this.attachmentDestination($,J,D),O=L0(F,Q.get("destination")),N=await this.attachmentScope(J,V,{body:K}),P=O!=="provider"&&!N;if(P){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()`.');U0()}if(O==="provider"||!N){let k=await i8(this.agent.provider,$);await H(k);let I={fileId:k,name:Z,mimeType:W,size:$.size,destination:"provider"};if(P)I.downgraded="no_scope";return I}let B=V9(),L=await this.attachmentStorage.put({name:H9(B,Z),body:$,contentType:W}),U=O==="both"?await i8(this.agent.provider,$):void 0;if(U)await H(U);let j={id:B,scopeKey:N.key,fileId:U,objectName:L,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString(),destination:O};return await this.attachments.put(N,j),{fileId:U,attachmentId:B,name:Z,mimeType:W,size:$.size,destination:O}}async foreignFile(J,Q){let $=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of $){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==Q:this.requireKnownFiles)return B0()}return null}onMessage(J,Q){return this.hooks?.onMessage?.(J,Q)}onToolCall(J,Q){return this.hooks?.onToolCall?.(J,Q)}onAwaitingInput(J,Q){return this.hooks?.onAwaitingInput?.(J,Q)}redactError(J,Q,$){let Z=this.hooks?.redactError;if(Z)return Z(J,Q,$);return eQ(J,Q)}onError(J,Q){return this.hooks?.onError?.(J,Q)}onStreamComplete(J,Q){return this.hooks?.onStreamComplete?.(J,Q)}reportHookFailure(J){let Q=this.hooks?.reportHookFailure;if(Q)try{return Q(J)}catch($){console.error("[gemi/ai] reportHookFailure hook failed",$)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,Q){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},Q);return;case"awaiting-input":await this.onAwaitingInput(J.pending,Q);return;case"error":await this.onError(X9(J.error),Q);return;default:return}}async readThread(J){let Q=await this.store.loadThread(J);return Q?(await this.settleThread(J,Q,{write:!1})).messages:null}isRunLive(J,Q){return this.liveRuns.get(J)!==null}async settleThread(J,Q,{write:$}){let Z=(V)=>this.isRunLive(V,J),W=await y8(Q,Z),K=W.messages,X=[],Y=new Map(W.settled.map((V)=>[V.id,V]));if(S0(K)||$)try{let V=await c8(K,{threadId:J,store:v.store,isRunLive:Z,outputSchemaFor:(G)=>this.toolOutputSchema(G),scan:this.jobsBlockMax()});K=V.messages,X=V.jobs;for(let G of V.settled)Y.set(G.id,G);if($&&V.orphans.length>0){await m8(v.store,V.orphans,(H)=>this.reportHookFailure(H));let G=new Set(V.orphans.map((H)=>H.id));X=X.map((H)=>G.has(H.id)?{...H,orphaned:!0}:H)}}catch(V){this.reportHookFailure(V)}if($&&Y.size>0)try{await this.store.appendMessages(J,[...Y.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:X}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??BJ}jobsBlock(J){return V$(J,this.jobsBlockMax())}toolOutputSchema(J){let Q=($)=>{for(let Z of $){let W=Z;if(Array.isArray(W.tools)){let K=Q(W.tools);if(K)return K}else if(W.name===J)return W.outputSchema}return};return Q(this.agent.tools??[])}follow(J,Q){(async()=>{try{for await(let $ of J.frames())Q.frame($)}catch($){this.reportHookFailure($)}})()}persistRun(J,Q,$,Z=null,W={id:null,notified:Promise.resolve()}){let K=Promise.resolve(),X=(async()=>{let V;try{V=await J.result()}catch(H){Z?.close(),await Z?.settled(),K=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},Q)));return}let G=V.messages;if(Z?.close(G),await Z?.settled(),Q.threadId&&G.length>0)try{await this.store.appendMessages(Q.threadId,G)}catch(H){this.reportHookFailure(H)}K=this.notifyRun(V,G,Q,W)})(),Y=X.then(()=>_0(Promise.all([K,$]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:Y}}async notifyRun(J,Q,$,Z){await Z.notified;for(let W of Q){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,$))}await this.safely(()=>this.onStreamComplete(J,$))}async safely(J){try{await J()}catch(Q){this.reportHookFailure(Q)}}}var nQ=["turn","clientRunId","threadId","messages","regenerate"],Z0=["text","files","toolResults"];function cJ(J,Q=B9(J)?nQ:[...nQ,...Z0]){let $={};for(let[Z,W]of Object.entries(J)){if(Q.includes(Z))continue;Object.defineProperty($,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return $}function W0(J){if(J===null)return{};let Q;if(typeof J==="string")try{Q=JSON.parse(J)}catch{throw new oQ("The upload's `body` field is not valid JSON.")}if(Q===null||typeof Q!=="object"||Array.isArray(Q))throw new oQ("The upload's `body` field must be a JSON object.");return cJ(Q,nQ)}class oQ extends mJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function i8(J,Q){try{return await J.upload(Q)}catch($){if($ instanceof w&&K0.has($.status))throw new P9(E($).message);throw $}}var K0=new Set([400,413,415,422]);class sQ extends mJ{constructor(J,Q){super(Q);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:Q}}},view:{}}}}function X0(J,Q,$,Z){if(!J)return null;let{maxBytes:W,accept:K}=J;if(typeof W==="number"&&Q.size>W)return{code:"file_too_large",message:`${JSON.stringify($)} is ${n8(Q.size)}; the limit is ${n8(W)}.`};if(K&&K.length>0&&!K.some((X)=>G0(X,$,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify($)} is not a type this chat accepts. Accepted: ${K.join(", ")}.`};return null}function G0(J,Q,$){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return Q.toLowerCase().endsWith(Z);let W=$.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function n8(J){if(J<1024)return`${J} B`;let Q=["KB","MB","GB"],$=J/1024,Z=0;while($>=1024&&Z<Q.length-1)$/=1024,Z++;return`${Math.round($*10)/10} ${Q[Z]}`}class P9 extends mJ{constructor(J){super(J);this.name="RejectedUploadError";let Q=/(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:Q,message:J}}},view:{}}}}async function DJ(J,Q){let $=J?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!Y0($.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($.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>Q)return o8(Q);let W;try{let X=await V0($,Q);if(X===null)return o8(Q);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 Y0(J){return Q9(J)==="application/json"}async function V0(J,Q){if(!Number.isFinite(Q)||!J.body)return await J.text();let $=J.body.getReader(),Z=[],W=0;for(;;){let{done:Y,value:V}=await $.read();if(Y)break;if(W+=V.byteLength,W>Q)return await $.cancel().catch(uJ),null;Z.push(V)}let K=new Uint8Array(W),X=0;for(let Y of Z)K.set(Y,X),X+=Y.byteLength;return new TextDecoder().decode(K)}function o8(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function aQ(J,Q,$){return M(J,{...pJ(J9(J),$,J),code:Q})}function r(J){if(J.status===413)return aQ(413,J.code??"body_too_large",J.error??"");return M(J.status??400,{code:J.code??"invalid_request",message:J.error})}function B9(J){return Boolean(J.turn)&&typeof J.turn==="object"}function H0(J){let Q=B9(J)?J.turn:J,$={};if(typeof Q.text==="string")$.text=Q.text;if(Array.isArray(Q.files)){let Z=z0(Q.files);if(typeof Z==="string")return{error:Z};$.files=Z}if(Array.isArray(Q.toolResults))$.toolResults=Q.toolResults;if(Object.keys($).length===0)return{};if(Q===J.turn&&Q.localId!==void 0&&Q.localId!==null&&Q.localId!==""){let{localId:Z}=Q;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>s8)return{error:`turn.localId is longer than ${s8} characters.`};$.localId=Z}return{turn:$}}var s8=200;function z0(J){let Q=[];for(let[$,Z]of J.entries()){let W=`turn.files[${$}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let K={};for(let H of["fileId","attachmentId","name","mimeType"]){let D=Z[H];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${H} must be a string.`;K[H]=D}let{fileId:X,attachmentId:Y,name:V,mimeType:G}=K;if(X?.startsWith(m))return`${W}.fileId holds a gemi attachment id (${X}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(Y!==void 0&&!Y.startsWith(m))return`${W}.attachmentId is not a gemi attachment id: it must start with "${m}".`;if(!X&&!Y)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;Q.push({...X?{fileId:X}:{},...Y?{attachmentId:Y}:{},...V!==void 0?{name:V}:{},...G!==void 0?{mimeType:G}:{}})}return Q}function D0(J,Q){if(typeof Q.from==="number"&&Number.isFinite(Q.from))return Math.max(0,Math.floor(Q.from));if(typeof Q.cursor==="number"&&Number.isFinite(Q.cursor)){let Z=Math.floor(Q.cursor);if(Z>=0)return Z+1;return}let $=J?.rawRequest?.headers?.get("Last-Event-ID");if($){let Z=Number.parseInt($,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function F0(J,Q){let $=J?.search?.get(Q);return typeof $==="string"?$:void 0}function P0(J){let Q=J$(J);for(let $=J.length-1;$>=0;$--){let Z=J[$];if(Z.role!=="user"||Q.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:$,turn:{...W?{text:W}:{},...K.length>0?{files:K}:{}}}}return null}function a8(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function FJ(){return M(403,pJ("permission","This run belongs to someone else.",403))}function B0(){return M(403,pJ("permission","A file in this turn was uploaded by someone else.",403))}function N0(J){if(!Array.isArray(J))return[];let Q=[];for(let $ of J){let Z=$?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")Q.push({fileId:W.fileId})}return Q}var O0=["sdp","threadId","pushToTalk"];function iQ(){return M(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function M(J,Q){return new Response(JSON.stringify({error:Q}),{status:J,headers:{"Content-Type":"application/json"}})}function L0(J,Q){if(typeof Q!=="string"||Q.length===0)return J;if(Q!=="both"&&Q!=="provider"&&Q!=="storage")throw Error(`Unknown attachment destination "${Q}". Expected "both", "provider" or "storage".`);if(Q===J||J==="both"&&Q==="storage")return Q;if(J==="both"&&Q==="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 "${Q}" 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 t8=!1;function U0(){if(t8)return;t8=!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 C0=2147483647;function _0(J,Q){let $=J.then(()=>{},()=>{});if(!(Q<=C0))return $;let Z,W=new Promise((K)=>{Z=setTimeout(K,Q)});return Promise.race([$,W]).finally(()=>clearTimeout(Z))}var r8=!1;function M0(J){if(r8||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof tQ))return;r8=!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 S0(J){return J.some((Q)=>Q.content.some(($)=>$.type==="tool-result"&&$.status==="running"))}export{w0 as windowMessages,YJ as voiceTools,j0 as turnStarts,EJ as toRealtimeUsage,f9 as toAgentTools,T0 as supportsStrict,k0 as splitTurns,u0 as settleSummaries,R0 as s,eQ as redactError,q0 as messageSize,ZJ as measureUsage,IQ as mcpVoiceTools,vQ as liveRuns,mQ as keepSummary,C8 as isCallNotFound,J$ as injectedMessageIds,GQ as generate,kZ as evalChain,$0 as defineAgentHooks,bQ as defaultVoiceStore,g0 as defaultSummaryStore,rQ as defaultNonceStore,yQ as defaultFileOwners,dJ as defaultAttachmentStore,pQ as defaultAgentStore,wJ as VoiceHangup,p as VoiceBridge,E0 as Usage,VQ as ToolNamespace,g as ToolError,m0 as Skill,lJ as ScopedAttachments,p0 as SKILLS_NAMESPACE,cQ as RedisReceiptStore,W9 as RedisNonceStore,jJ as RealtimeSideband,f as RealtimeRequestError,XJ as RealtimeClient,X$ as Prompt,K9 as PrismaNonceStore,c0 as PendingEscalation,jQ as OpenAIProvider,PQ as OpenAIImageProvider,wQ as MemoryVoiceSessionStore,h0 as MemorySummaryStore,uQ as MemoryReceiptStore,tQ as MemoryNonceStore,bJ as MemoryLiveRuns,fJ as MemoryFileOwners,xJ as MemoryCircuitStore,z9 as MemoryAttachmentStore,vJ as MemoryAgentStore,F$ as MemoryAgentJobStore,q$ as MEMORY_NAMESPACE,HJ as LiveRunNotFoundError,B$ as JobsRequireThreadError,P$ as JobHandle,A0 as JSONSchemaError,Y9 as InvalidAttachmentScopeError,A$ as InMemoryAgentMemoryStore,AJ as ImageRequestError,RJ as ImageProvider,HQ as ImageModel,t as FrameCursorEvictedError,GJ as FallbackProvider,j$ as FakeAgentMemoryStore,_J as Eval,QQ as DatabaseAgentMemoryStore,eJ as DatabaseAgentJobStore,L8 as DEFAULT_TRANSCRIPTION_MODEL,S$ as DEFAULT_MEMORY_MAX_TOKENS,k$ as DEFAULT_MEMORY_LIMITS,b0 as DEFAULT_MAX_SUMMARY_TOKENS,l0 as DEFAULT_MAX_RUN_DURATION_MS,N$ as DEFAULT_JOB_DEADLINE_MS,BJ as DEFAULT_JOBS_CONTEXT_MAX,VJ as DEFAULT_DELEGATE_NAME,x0 as DEFAULT_CONTEXT_WINDOW_STEP,I0 as DEFAULT_CONTEXT_WINDOW_NOTE,f0 as DEFAULT_COMPACT_TRIGGER_TOKENS,v0 as DEFAULT_COMPACT_INSTRUCTIONS,y0 as COMPACT_SUMMARY_HEADER,kQ as AzureOpenAIProvider,BQ as AzureOpenAIImageProvider,G9 as AttachmentNotFoundError,iJ as AgentTurnError,MJ as AgentTool,d0 as AgentRunError,a as AgentProvider,R$ as AgentMemoryRefusedError,T$ as AgentMemoryConflictError,E$ as AgentMemories,v as AgentJobs,aJ as AgentJobDeadlineSweep,O$ as AgentJob,Q$ as AgentController,i0 as Agent};
155
155
 
156
- //# debugId=AFBFC63CA51B55C764756E2164756E21
156
+ //# debugId=4B9F6089DE2A57DC64756E2164756E21