gemi 0.236.1 → 0.237.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/dist/ai/Agent.d.ts +2 -1
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts.map +1 -1
  4. package/dist/ai/AgentProvider.d.ts +22 -0
  5. package/dist/ai/AgentProvider.d.ts.map +1 -1
  6. package/dist/ai/FallbackProvider.d.ts +6 -0
  7. package/dist/ai/FallbackProvider.d.ts.map +1 -1
  8. package/dist/ai/ImageModel.d.ts.map +1 -1
  9. package/dist/ai/contextCompaction.d.ts.map +1 -1
  10. package/dist/ai/generate.d.ts.map +1 -1
  11. package/dist/ai/index.d.ts +1 -1
  12. package/dist/ai/index.d.ts.map +1 -1
  13. package/dist/ai/index.js +40 -40
  14. package/dist/ai/index.js.map +5 -5
  15. package/dist/ai/runtime.d.ts +8 -0
  16. package/dist/ai/runtime.d.ts.map +1 -1
  17. package/dist/ai/testing/index.js +2 -2
  18. package/dist/ai/testing/index.js.map +1 -1
  19. package/dist/ai/types.d.ts +13 -0
  20. package/dist/ai/types.d.ts.map +1 -1
  21. package/dist/ai/usageLimits.d.ts +12 -1
  22. package/dist/ai/usageLimits.d.ts.map +1 -1
  23. package/dist/ai/usageMeter.d.ts +67 -10
  24. package/dist/ai/usageMeter.d.ts.map +1 -1
  25. package/dist/app/index.js +1 -1
  26. package/dist/bun/plugin.js +1 -1
  27. package/dist/bun/preload.js +1 -1
  28. package/dist/{chunk-0e5sq42y.js → chunk-07fy1618.js} +2 -2
  29. package/dist/{chunk-0e5sq42y.js.map → chunk-07fy1618.js.map} +1 -1
  30. package/dist/{chunk-ca5kp6cn.js → chunk-0kjcd94c.js} +2 -2
  31. package/dist/{chunk-ca5kp6cn.js.map → chunk-0kjcd94c.js.map} +1 -1
  32. package/dist/{chunk-naj8bmj5.js → chunk-0xmk4jyj.js} +2 -2
  33. package/dist/{chunk-naj8bmj5.js.map → chunk-0xmk4jyj.js.map} +1 -1
  34. package/dist/{chunk-hprgj13q.js → chunk-185k67yf.js} +2 -2
  35. package/dist/{chunk-hprgj13q.js.map → chunk-185k67yf.js.map} +1 -1
  36. package/dist/{chunk-hy54f691.js → chunk-2d757e1s.js} +2 -2
  37. package/dist/{chunk-hy54f691.js.map → chunk-2d757e1s.js.map} +1 -1
  38. package/dist/{chunk-h1wmpa03.js → chunk-2g1h9ktj.js} +2 -2
  39. package/dist/{chunk-h1wmpa03.js.map → chunk-2g1h9ktj.js.map} +1 -1
  40. package/dist/{chunk-4vn8gyzy.js → chunk-2gj2nhve.js} +2 -2
  41. package/dist/{chunk-4vn8gyzy.js.map → chunk-2gj2nhve.js.map} +1 -1
  42. package/dist/{chunk-x6a5qxpa.js → chunk-2h1ta6cv.js} +2 -2
  43. package/dist/{chunk-x6a5qxpa.js.map → chunk-2h1ta6cv.js.map} +1 -1
  44. package/dist/chunk-2mjtssv3.js +5 -0
  45. package/dist/{chunk-0hy5dsbt.js.map → chunk-2mjtssv3.js.map} +1 -1
  46. package/dist/{chunk-m3fbewhz.js → chunk-3jr6d0cb.js} +3 -3
  47. package/dist/{chunk-m3fbewhz.js.map → chunk-3jr6d0cb.js.map} +1 -1
  48. package/dist/{chunk-17bva6b1.js → chunk-3p4wdpag.js} +2 -2
  49. package/dist/{chunk-17bva6b1.js.map → chunk-3p4wdpag.js.map} +1 -1
  50. package/dist/{chunk-wbj4jh1h.js → chunk-5c538k7m.js} +2 -2
  51. package/dist/{chunk-wbj4jh1h.js.map → chunk-5c538k7m.js.map} +1 -1
  52. package/dist/{chunk-3y1h3ncf.js → chunk-5fxdjmgd.js} +2 -2
  53. package/dist/{chunk-3y1h3ncf.js.map → chunk-5fxdjmgd.js.map} +1 -1
  54. package/dist/{chunk-9sbhqscs.js → chunk-5kjnbmwp.js} +3 -3
  55. package/dist/{chunk-9sbhqscs.js.map → chunk-5kjnbmwp.js.map} +1 -1
  56. package/dist/{chunk-sh2bd09k.js → chunk-5nn0pgxg.js} +2 -2
  57. package/dist/{chunk-sh2bd09k.js.map → chunk-5nn0pgxg.js.map} +1 -1
  58. package/dist/{chunk-qvn0w2rt.js → chunk-5pbjc6tm.js} +2 -2
  59. package/dist/{chunk-qvn0w2rt.js.map → chunk-5pbjc6tm.js.map} +1 -1
  60. package/dist/{chunk-x2dmgge8.js → chunk-6wv3k8ap.js} +2 -2
  61. package/dist/{chunk-x2dmgge8.js.map → chunk-6wv3k8ap.js.map} +1 -1
  62. package/dist/{chunk-px9h2qgv.js → chunk-7159w4qq.js} +3 -3
  63. package/dist/{chunk-px9h2qgv.js.map → chunk-7159w4qq.js.map} +1 -1
  64. package/dist/{chunk-jssjfvsz.js → chunk-768yza4f.js} +2 -2
  65. package/dist/{chunk-jssjfvsz.js.map → chunk-768yza4f.js.map} +1 -1
  66. package/dist/{chunk-fbk79z21.js → chunk-7b4tsj9x.js} +2 -2
  67. package/dist/{chunk-fbk79z21.js.map → chunk-7b4tsj9x.js.map} +1 -1
  68. package/dist/{chunk-kak3vc71.js → chunk-8591j0cj.js} +2 -2
  69. package/dist/{chunk-kak3vc71.js.map → chunk-8591j0cj.js.map} +1 -1
  70. package/dist/{chunk-1mb7kaxs.js → chunk-89jc9yg9.js} +3 -3
  71. package/dist/{chunk-1mb7kaxs.js.map → chunk-89jc9yg9.js.map} +1 -1
  72. package/dist/{chunk-1w6ra6jc.js → chunk-9447c20x.js} +1 -1
  73. package/dist/{chunk-np6vee9d.js → chunk-96v1bwg4.js} +3 -3
  74. package/dist/{chunk-np6vee9d.js.map → chunk-96v1bwg4.js.map} +1 -1
  75. package/dist/{chunk-a119av2z.js → chunk-9a3wbbr6.js} +2 -2
  76. package/dist/{chunk-a119av2z.js.map → chunk-9a3wbbr6.js.map} +1 -1
  77. package/dist/{chunk-n4kz9vft.js → chunk-9ey725pw.js} +1 -1
  78. package/dist/chunk-a3s6cp49.js +48 -0
  79. package/dist/chunk-a3s6cp49.js.map +26 -0
  80. package/dist/{chunk-yahabnz4.js → chunk-a9p3djqm.js} +3 -3
  81. package/dist/{chunk-yahabnz4.js.map → chunk-a9p3djqm.js.map} +1 -1
  82. package/dist/{chunk-ka8dzc6q.js → chunk-ack021d9.js} +2 -2
  83. package/dist/{chunk-ka8dzc6q.js.map → chunk-ack021d9.js.map} +1 -1
  84. package/dist/{chunk-4n3jva4e.js → chunk-b9gf8sqq.js} +2 -2
  85. package/dist/{chunk-4n3jva4e.js.map → chunk-b9gf8sqq.js.map} +1 -1
  86. package/dist/{chunk-73541m4t.js → chunk-bcb1dwhb.js} +4 -4
  87. package/dist/{chunk-73541m4t.js.map → chunk-bcb1dwhb.js.map} +1 -1
  88. package/dist/{chunk-4800w7qx.js → chunk-bg0da5pd.js} +3 -3
  89. package/dist/{chunk-4800w7qx.js.map → chunk-bg0da5pd.js.map} +3 -3
  90. package/dist/{chunk-9kt24ctk.js → chunk-bhycdjcv.js} +2 -2
  91. package/dist/{chunk-9kt24ctk.js.map → chunk-bhycdjcv.js.map} +1 -1
  92. package/dist/{chunk-2kzysesp.js → chunk-c3c37k46.js} +3 -3
  93. package/dist/{chunk-2kzysesp.js.map → chunk-c3c37k46.js.map} +1 -1
  94. package/dist/{chunk-t6x1r5n6.js → chunk-c6zpn9yp.js} +3 -3
  95. package/dist/{chunk-t6x1r5n6.js.map → chunk-c6zpn9yp.js.map} +1 -1
  96. package/dist/{chunk-y2vayxcd.js → chunk-dj5d9wcc.js} +2 -2
  97. package/dist/{chunk-y2vayxcd.js.map → chunk-dj5d9wcc.js.map} +1 -1
  98. package/dist/{chunk-5exrgw07.js → chunk-dmzgw2d8.js} +3 -3
  99. package/dist/{chunk-5exrgw07.js.map → chunk-dmzgw2d8.js.map} +1 -1
  100. package/dist/chunk-ejf6sz1d.js +5 -0
  101. package/dist/{chunk-gvr7cwxn.js.map → chunk-ejf6sz1d.js.map} +3 -3
  102. package/dist/{chunk-74dzzd64.js → chunk-fb0bazw9.js} +2 -2
  103. package/dist/{chunk-74dzzd64.js.map → chunk-fb0bazw9.js.map} +1 -1
  104. package/dist/{chunk-8476xvk9.js → chunk-fgnpyj44.js} +2 -2
  105. package/dist/{chunk-8476xvk9.js.map → chunk-fgnpyj44.js.map} +1 -1
  106. package/dist/{chunk-1xz206e1.js → chunk-fp31t0ey.js} +3 -3
  107. package/dist/{chunk-1xz206e1.js.map → chunk-fp31t0ey.js.map} +1 -1
  108. package/dist/{chunk-8yb9jrj5.js → chunk-fp6mxxkq.js} +2 -2
  109. package/dist/{chunk-8yb9jrj5.js.map → chunk-fp6mxxkq.js.map} +1 -1
  110. package/dist/{chunk-hgwkxn0g.js → chunk-fx45rbbn.js} +2 -2
  111. package/dist/{chunk-hgwkxn0g.js.map → chunk-fx45rbbn.js.map} +1 -1
  112. package/dist/{chunk-ts75gcfd.js → chunk-g29wz7h7.js} +2 -2
  113. package/dist/{chunk-k2mpxwh2.js.map → chunk-g29wz7h7.js.map} +1 -1
  114. package/dist/{chunk-byv7b79h.js → chunk-gakdsme3.js} +2 -2
  115. package/dist/{chunk-byv7b79h.js.map → chunk-gakdsme3.js.map} +1 -1
  116. package/dist/{chunk-28yb0q82.js → chunk-gj4hg8xk.js} +2 -2
  117. package/dist/{chunk-28yb0q82.js.map → chunk-gj4hg8xk.js.map} +1 -1
  118. package/dist/{chunk-h0dch3vh.js → chunk-h6z5k6yh.js} +2 -2
  119. package/dist/{chunk-h0dch3vh.js.map → chunk-h6z5k6yh.js.map} +1 -1
  120. package/dist/{chunk-fqndtpwm.js → chunk-jfqfvx3t.js} +3 -3
  121. package/dist/{chunk-fqndtpwm.js.map → chunk-jfqfvx3t.js.map} +1 -1
  122. package/dist/{chunk-at82qczv.js → chunk-jwh7t982.js} +3 -3
  123. package/dist/{chunk-at82qczv.js.map → chunk-jwh7t982.js.map} +1 -1
  124. package/dist/{chunk-2ver7cdt.js → chunk-k2jxxdj1.js} +1 -1
  125. package/dist/{chunk-t2p5n8fe.js → chunk-k9devrb5.js} +2 -2
  126. package/dist/{chunk-t2p5n8fe.js.map → chunk-k9devrb5.js.map} +1 -1
  127. package/dist/{chunk-sv2mv2q2.js → chunk-kpbm4mbc.js} +2 -2
  128. package/dist/{chunk-sv2mv2q2.js.map → chunk-kpbm4mbc.js.map} +1 -1
  129. package/dist/{chunk-gt9ftnhn.js → chunk-krfz1rzm.js} +2 -2
  130. package/dist/{chunk-gt9ftnhn.js.map → chunk-krfz1rzm.js.map} +1 -1
  131. package/dist/{chunk-zt4hybgg.js → chunk-mwe7hpbd.js} +2 -2
  132. package/dist/{chunk-zt4hybgg.js.map → chunk-mwe7hpbd.js.map} +1 -1
  133. package/dist/{chunk-x185900b.js → chunk-n78b8pp5.js} +3 -3
  134. package/dist/{chunk-x185900b.js.map → chunk-n78b8pp5.js.map} +1 -1
  135. package/dist/{chunk-fs94x6ef.js → chunk-nznkpf8r.js} +3 -3
  136. package/dist/{chunk-fs94x6ef.js.map → chunk-nznkpf8r.js.map} +1 -1
  137. package/dist/{chunk-2j45vbs2.js → chunk-p91yn1b8.js} +2 -2
  138. package/dist/{chunk-2j45vbs2.js.map → chunk-p91yn1b8.js.map} +1 -1
  139. package/dist/{chunk-h5wjk91m.js → chunk-pqaha4f1.js} +2 -2
  140. package/dist/{chunk-h5wjk91m.js.map → chunk-pqaha4f1.js.map} +1 -1
  141. package/dist/{chunk-8gz07168.js → chunk-q4b79hjb.js} +4 -4
  142. package/dist/{chunk-8gz07168.js.map → chunk-q4b79hjb.js.map} +1 -1
  143. package/dist/{chunk-ezea9fpd.js → chunk-qj2r0v7w.js} +2 -2
  144. package/dist/{chunk-ezea9fpd.js.map → chunk-qj2r0v7w.js.map} +1 -1
  145. package/dist/{chunk-8jc8x9tc.js → chunk-rmwhvgvg.js} +2 -2
  146. package/dist/{chunk-8jc8x9tc.js.map → chunk-rmwhvgvg.js.map} +1 -1
  147. package/dist/{chunk-4mha212g.js → chunk-sxtg2qha.js} +1 -1
  148. package/dist/{chunk-t60krz4g.js → chunk-t4yx1jqb.js} +2 -2
  149. package/dist/{chunk-t60krz4g.js.map → chunk-t4yx1jqb.js.map} +1 -1
  150. package/dist/{chunk-yknc5rgh.js → chunk-t6xe3jr4.js} +2 -2
  151. package/dist/{chunk-yknc5rgh.js.map → chunk-t6xe3jr4.js.map} +1 -1
  152. package/dist/{chunk-kvtvx64t.js → chunk-tmpfcx0v.js} +2 -2
  153. package/dist/{chunk-kvtvx64t.js.map → chunk-tmpfcx0v.js.map} +1 -1
  154. package/dist/{chunk-8n40a2sn.js → chunk-trbwk80g.js} +2 -2
  155. package/dist/{chunk-8n40a2sn.js.map → chunk-trbwk80g.js.map} +1 -1
  156. package/dist/{chunk-aj9atkwk.js → chunk-va2p7e59.js} +1 -1
  157. package/dist/{chunk-17ewxwga.js → chunk-vbmtyxr4.js} +3 -3
  158. package/dist/{chunk-17ewxwga.js.map → chunk-vbmtyxr4.js.map} +1 -1
  159. package/dist/{chunk-406ef17s.js → chunk-vc7ny5zs.js} +2 -2
  160. package/dist/{chunk-406ef17s.js.map → chunk-vc7ny5zs.js.map} +1 -1
  161. package/dist/{chunk-zm6b938z.js → chunk-vcmwp7pv.js} +3 -3
  162. package/dist/{chunk-zm6b938z.js.map → chunk-vcmwp7pv.js.map} +1 -1
  163. package/dist/{chunk-8mpptpn5.js → chunk-vrp3zzz4.js} +3 -3
  164. package/dist/{chunk-8mpptpn5.js.map → chunk-vrp3zzz4.js.map} +1 -1
  165. package/dist/{chunk-y56xd7sv.js → chunk-w7rgnjt5.js} +2 -2
  166. package/dist/{chunk-y56xd7sv.js.map → chunk-w7rgnjt5.js.map} +1 -1
  167. package/dist/{chunk-g7hz0dmk.js → chunk-w9v8bbp8.js} +2 -2
  168. package/dist/{chunk-g7hz0dmk.js.map → chunk-w9v8bbp8.js.map} +1 -1
  169. package/dist/{chunk-k2mpxwh2.js → chunk-x8pk6qqs.js} +2 -2
  170. package/dist/{chunk-ts75gcfd.js.map → chunk-x8pk6qqs.js.map} +1 -1
  171. package/dist/{chunk-9jt5qj1b.js → chunk-xj3ebwrj.js} +2 -2
  172. package/dist/{chunk-9jt5qj1b.js.map → chunk-xj3ebwrj.js.map} +1 -1
  173. package/dist/{chunk-6v1fbe70.js → chunk-y9efbqmp.js} +2 -2
  174. package/dist/{chunk-6v1fbe70.js.map → chunk-y9efbqmp.js.map} +1 -1
  175. package/dist/{chunk-7fbnw7e2.js → chunk-yb7yw0cp.js} +1 -1
  176. package/dist/{chunk-z3tk66vh.js → chunk-yca8nznt.js} +2 -2
  177. package/dist/{chunk-z3tk66vh.js.map → chunk-yca8nznt.js.map} +1 -1
  178. package/dist/{chunk-pfkbhqp7.js → chunk-z0xmyrjb.js} +2 -2
  179. package/dist/{chunk-pfkbhqp7.js.map → chunk-z0xmyrjb.js.map} +1 -1
  180. package/dist/{chunk-ehtj7zs2.js → chunk-z55c52fm.js} +2 -2
  181. package/dist/{chunk-ehtj7zs2.js.map → chunk-z55c52fm.js.map} +1 -1
  182. package/dist/config/index.js +1 -1
  183. package/dist/console/run.js +2 -2
  184. package/dist/console/run.js.map +1 -1
  185. package/dist/container/index.js +2 -2
  186. package/dist/container/index.js.map +1 -1
  187. package/dist/database/index.js +2 -2
  188. package/dist/database/index.js.map +1 -1
  189. package/dist/email/index.js +2 -2
  190. package/dist/email/index.js.map +1 -1
  191. package/dist/facades/index.js +2 -2
  192. package/dist/facades/index.js.map +1 -1
  193. package/dist/foundation/index.js +2 -2
  194. package/dist/foundation/index.js.map +1 -1
  195. package/dist/http/index.js +2 -2
  196. package/dist/http/index.js.map +1 -1
  197. package/dist/i18n/dictionaryRuntime.js +2 -2
  198. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  199. package/dist/i18n/index.js +2 -2
  200. package/dist/i18n/index.js.map +1 -1
  201. package/dist/kernel/index.js +2 -2
  202. package/dist/kernel/index.js.map +1 -1
  203. package/dist/orm/index.js +2 -2
  204. package/dist/orm/index.js.map +1 -1
  205. package/dist/probe/index.js +2 -2
  206. package/dist/probe/index.js.map +1 -1
  207. package/dist/server/index.js +2 -2
  208. package/dist/server/index.js.map +1 -1
  209. package/dist/services/index.js +2 -2
  210. package/dist/services/index.js.map +1 -1
  211. package/dist/services/queue/work.js +2 -2
  212. package/dist/services/queue/work.js.map +1 -1
  213. package/dist/stats/route-table.js +1 -1
  214. package/dist/support/index.js +2 -2
  215. package/dist/support/index.js.map +1 -1
  216. package/dist/vitest/index.js +1 -1
  217. package/package.json +1 -1
  218. package/dist/chunk-0hy5dsbt.js +0 -5
  219. package/dist/chunk-dav7mv8t.js +0 -48
  220. package/dist/chunk-dav7mv8t.js.map +0 -26
  221. package/dist/chunk-gvr7cwxn.js +0 -5
  222. /package/dist/{chunk-1w6ra6jc.js.map → chunk-9447c20x.js.map} +0 -0
  223. /package/dist/{chunk-n4kz9vft.js.map → chunk-9ey725pw.js.map} +0 -0
  224. /package/dist/{chunk-2ver7cdt.js.map → chunk-k2jxxdj1.js.map} +0 -0
  225. /package/dist/{chunk-4mha212g.js.map → chunk-sxtg2qha.js.map} +0 -0
  226. /package/dist/{chunk-aj9atkwk.js.map → chunk-va2p7e59.js.map} +0 -0
  227. /package/dist/{chunk-7fbnw7e2.js.map → chunk-yb7yw0cp.js.map} +0 -0
package/dist/ai/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,ka as Q0,la as M$,ma as Z0,na as W0,oa as X0,pa as K0}from"../chunk-4800w7qx.js";import{$c as u6,Ac as wZ,Bc as fZ,Cc as BQ,Ec as MQ,Fc as TQ,Gc as RQ,Hc as EQ,Ic as kQ,Jc as jQ,Kc as xQ,Lc as IQ,Mc as wQ,Nc as fQ,Oc as qQ,Pc as bQ,Rc as q6,Sc as b6,Tc as v6,Uc as y6,Vc as h6,Wc as CJ,Xc as g6,Yc as B8,Zc as c6,_c as M8,ad as m6,bd as p6,cd as vJ,dd as N$,ed as l6,fd as i6,gd as S8,hd as d6,id as n6,jc as t$,jd as o6,kc as H8,kd as s6,lc as P8,ld as a6,mc as r$,md as A8,nd as t6,od as H$,qc as rQ,rc as dQ,sc as PJ,tc as k6,uc as g,vc as _Q,wc as OQ,yc as LQ,zc as i}from"../chunk-dav7mv8t.js";import{$d as j6,Bd as o,Cd as e$,Fd as N8,Gd as F8,Hd as U8,Id as iJ,Jd as C8,Kd as tJ,Ld as dJ,Md as l$,Nd as _8,Od as O8,Pd as rJ,Qd as L8,Wd as XJ,Yd as WJ,Zd as JQ,_d as T6,ae as x6,be as I6,ce as w6,de as f6,sd as KZ,td as S,ud as T}from"../chunk-gvr7cwxn.js";import{ue as HQ}from"../chunk-g7hz0dmk.js";import"../chunk-x185900b.js";import{Si as w,qi as X8,ti as G8,yj as V8,zj as I$}from"../chunk-fqndtpwm.js";import{Aj as K8,Cj as sJ,Dj as aJ}from"../chunk-h1wmpa03.js";import{Gj as A6,Hj as R6,Ij as E6}from"../chunk-t6x1r5n6.js";import{Vj as n}from"../chunk-naj8bmj5.js";import"../chunk-jssjfvsz.js";import{al as z8,bl as Y8,cl as D8,dl as p$}from"../chunk-m3fbewhz.js";import"../chunk-x2dmgge8.js";import{jl as QJ,kl as ZJ,zl as fJ}from"../chunk-fs94x6ef.js";import"../chunk-8476xvk9.js";import"../chunk-9jt5qj1b.js";import{qm as LZ}from"../chunk-17ewxwga.js";import"../chunk-sv2mv2q2.js";import"../chunk-qvn0w2rt.js";import{Nm as Q$}from"../chunk-ka8dzc6q.js";import"../chunk-ts75gcfd.js";import{existsSync as f8,readdirSync as V0,readFileSync as zQ}from"fs";import{isAbsolute as q8,join as kJ,relative as b8,sep as v8}from"path";var YQ="prompts.json",y8=/\{\{>\s*([\w./-]+)\s*\}\}/g,KQ=/\{\{(\w+)\}\}/g,h8=/^[\w-]+(\/[\w-]+)*$/,GQ={dir:"app/agents",shared:"prompts"},jJ={},J$=new Map,TJ;function g8(){if(TJ===void 0){let J=kJ(Q$(),"dist","server",YQ);TJ=f8(J)?JSON.parse(zQ(J,"utf8")):null}return TJ??null}function c8(J){return J.replace(/\r?\n$/,"")}function VQ(){return jJ.cache??Bun.env.NODE_ENV==="production"}function u8(J,$){if(!h8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??jJ.dir??GQ.dir,Z=q8(Q)?Q:kJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:kJ($.shared??jJ.shared??GQ.shared,`${J}.md`);return kJ(Z,W)}function m8(J,$){let Q=u8(J,$),Z=VQ()?J$.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let K=g8()?.[b8(Q$(),Q).split(v8).join("/")];if(K!==void 0)return K}let X;try{X=c8(zQ(Q,"utf8"))}catch(K){if(K.code==="ENOENT"){let G=W?` or in dist/server/${YQ}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw K}if(VQ())J$.set(Q,X);return X}function $$(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return m8(J,Q).replace(y8,(Z,W)=>$$(W,[...$,J],Q))}class DQ{static configure(J){jJ={...J},J$.clear(),TJ=void 0}static render(J,$={},Q={}){return $$(J,[],Q).replace(KQ,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...$$(J,[],$).matchAll(KQ)].map((Z)=>Z[1]);return[...new Set(Q)]}}class Z$ extends HQ{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await i.sweep({limit:100})===100);}}var IJ=20,p8=300,l8=200;function NQ(J,$){if($<=0||J.length===0)return null;let Q=(X,K)=>K.createdAt-X.createdAt||(X.id<K.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((X)=>!g(X.state)).sort(Q),...J.filter((X)=>g(X.state)).sort(Q)].slice(0,$).map((X)=>{let K=[`- ${X.id} (${X.toolName})`];if(X.state==="waiting")K.push(`waiting for ${(X.after??[]).join(", ")} since ${xJ(X.createdAt)}`);else if(X.state==="running")K.push(`running since ${xJ(X.createdAt)}`);else if(X.state==="ok")K.push(`finished at ${xJ(X.settledAt??X.updatedAt)}`);else{let G=X.error?`${X.error.code}: ${PQ(X.error.message,l8)}`:"failed";K.push(`failed at ${xJ(X.settledAt??X.updatedAt)} (${G})`)}if(X.summary!==void 0)K.push(`summary: ${PQ(JSON.stringify(X.summary),p8)}`);if(X.orphaned)K.push("its tool call was lost when the turn that started it was cut short");return K.join("; ")}),"</jobs>"].join(`
3
- `)}function xJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function PQ(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}var FQ=["after_jobs","batch_key","queued","inbox","job_checkpoint"],UQ=20;class W${table;sql;dialect;connection;later;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of i8(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return fJ(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=J.after!==void 0||J.batch!==void 0||J.queued!==void 0;if($)await this.requireLaterColumns("A job with `after` or `batch`");let Q=this.q(),Z=this.clock(Q),W=J.state??"running";if($)await Q`
2
+ import{ca as JZ,da as WZ,ea as XZ,fa as e6,ga as J0,ha as $0,ia as WQ,ja as Q0,ka as Z0,la as R$,ma as W0,na as X0,oa as K0,pa as G0}from"../chunk-bg0da5pd.js";import{$c as M8,Ac as i,Bc as fZ,Cc as qZ,Dc as BQ,Fc as SQ,Gc as TQ,Hc as RQ,Ic as EQ,Jc as kQ,Kc as jQ,Lc as xQ,Mc as IQ,Nc as wQ,Oc as fQ,Pc as qQ,Qc as bQ,Sc as b6,Tc as v6,Uc as y6,Vc as h6,Wc as g6,Xc as OJ,Yc as c6,Zc as S8,_c as u6,ad as m6,bd as p6,cd as l6,dd as gJ,ed as U$,fd as i6,gd as d6,hd as A8,id as n6,jc as JQ,jd as o6,kc as P8,kd as s6,lc as N8,ld as a6,mc as $Q,md as t6,nd as R8,od as r6,pd as F$,qc as rQ,rc as eQ,sc as dQ,tc as FJ,uc as T6,vc as g,wc as _Q,xc as OQ,zc as LQ}from"../chunk-a3s6cp49.js";import{$d as XJ,Ed as o,Fd as QQ,Id as F8,Jd as C8,Kd as U8,Ld as oJ,Md as _8,Nd as J$,Od as sJ,Pd as n$,Qd as O8,Rd as L8,Sd as $$,Td as B8,Zd as KJ,ae as ZQ,be as j6,ce as x6,de as I6,ee as w6,fe as f6,ge as q6,td as GZ,ud as S,vd as k}from"../chunk-ejf6sz1d.js";import{xe as HQ}from"../chunk-w9v8bbp8.js";import"../chunk-n78b8pp5.js";import{Bj as z8,Cj as q$,Vi as w,ti as K8,wi as V8}from"../chunk-jfqfvx3t.js";import{Dj as G8,Fj as rJ,Gj as eJ}from"../chunk-2g1h9ktj.js";import{Jj as R6,Kj as E6,Lj as k6}from"../chunk-c6zpn9yp.js";import{Yj as n}from"../chunk-0xmk4jyj.js";import"../chunk-768yza4f.js";import{dl as Y8,el as D8,fl as H8,gl as d$}from"../chunk-3jr6d0cb.js";import"../chunk-6wv3k8ap.js";import{Cl as vJ,ml as ZJ,nl as WJ}from"../chunk-nznkpf8r.js";import"../chunk-fgnpyj44.js";import"../chunk-xj3ebwrj.js";import{tm as BZ}from"../chunk-vbmtyxr4.js";import"../chunk-kpbm4mbc.js";import"../chunk-5pbjc6tm.js";import{Qm as X$}from"../chunk-ack021d9.js";import"../chunk-g29wz7h7.js";import{existsSync as q8,readdirSync as z0,readFileSync as zQ}from"fs";import{isAbsolute as b8,join as xJ,relative as v8,sep as y8}from"path";var YQ="prompts.json",h8=/\{\{>\s*([\w./-]+)\s*\}\}/g,KQ=/\{\{(\w+)\}\}/g,g8=/^[\w-]+(\/[\w-]+)*$/,GQ={dir:"app/agents",shared:"prompts"},wJ={},Z$=new Map,IJ;function c8(){if(IJ===void 0){let J=xJ(X$(),"dist","server",YQ);IJ=q8(J)?JSON.parse(zQ(J,"utf8")):null}return IJ??null}function u8(J){return J.replace(/\r?\n$/,"")}function VQ(){return wJ.cache??Bun.env.NODE_ENV==="production"}function m8(J,$){if(!g8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??wJ.dir??GQ.dir,Z=b8(Q)?Q:xJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:xJ($.shared??wJ.shared??GQ.shared,`${J}.md`);return xJ(Z,W)}function p8(J,$){let Q=m8(J,$),Z=VQ()?Z$.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let K=c8()?.[v8(X$(),Q).split(y8).join("/")];if(K!==void 0)return K}let X;try{X=u8(zQ(Q,"utf8"))}catch(K){if(K.code==="ENOENT"){let G=W?` or in dist/server/${YQ}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw K}if(VQ())Z$.set(Q,X);return X}function W$(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return p8(J,Q).replace(h8,(Z,W)=>W$(W,[...$,J],Q))}class DQ{static configure(J){wJ={...J},Z$.clear(),IJ=void 0}static render(J,$={},Q={}){return W$(J,[],Q).replace(KQ,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...W$(J,[],$).matchAll(KQ)].map((Z)=>Z[1]);return[...new Set(Q)]}}class K$ extends HQ{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await i.sweep({limit:100})===100);}}var qJ=20,l8=300,i8=200;function NQ(J,$){if($<=0||J.length===0)return null;let Q=(X,K)=>K.createdAt-X.createdAt||(X.id<K.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((X)=>!g(X.state)).sort(Q),...J.filter((X)=>g(X.state)).sort(Q)].slice(0,$).map((X)=>{let K=[`- ${X.id} (${X.toolName})`];if(X.state==="waiting")K.push(`waiting for ${(X.after??[]).join(", ")} since ${fJ(X.createdAt)}`);else if(X.state==="running")K.push(`running since ${fJ(X.createdAt)}`);else if(X.state==="ok")K.push(`finished at ${fJ(X.settledAt??X.updatedAt)}`);else{let G=X.error?`${X.error.code}: ${PQ(X.error.message,i8)}`:"failed";K.push(`failed at ${fJ(X.settledAt??X.updatedAt)} (${G})`)}if(X.summary!==void 0)K.push(`summary: ${PQ(JSON.stringify(X.summary),l8)}`);if(X.orphaned)K.push("its tool call was lost when the turn that started it was cut short");return K.join("; ")}),"</jobs>"].join(`
3
+ `)}function fJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function PQ(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}var FQ=["after_jobs","batch_key","queued","inbox","job_checkpoint"],CQ=20;class G${table;sql;dialect;connection;later;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of d8(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return vJ(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=J.after!==void 0||J.batch!==void 0||J.queued!==void 0;if($)await this.requireLaterColumns("A job with `after` or `batch`");let Q=this.q(),Z=this.clock(Q),W=J.state??"running";if($)await Q`
4
4
  INSERT INTO ${this.name(Q)}
5
5
  (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
6
6
  orphaned, attachment_scope, created_at, updated_at, deadline_at,
@@ -18,7 +18,7 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
18
18
  (${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
19
19
  ${J.owner}, ${J.job}, ${c(J.summary)}, ${W}, 0, ${J.attachmentScope},
20
20
  ${Z}, ${Z}, ${Z} + ${this.ms(Q,J.deadlineMs)})
21
- `;let X=await this.get(J.id);if(!X)throw Error(`The background job ${J.id} was not found after it was written.`);return X}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?$J(Q[0]):null}async listForThread(J,$={}){let Q=this.q(),Z=$.states===void 0?Q`1 = 1`:$.states.length===0?Q`1 = 0`:Q`state IN (${CQ(Q,$.states)})`;return($.limit===void 0?await Q`
21
+ `;let X=await this.get(J.id);if(!X)throw Error(`The background job ${J.id} was not found after it was written.`);return X}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?QJ(Q[0]):null}async listForThread(J,$={}){let Q=this.q(),Z=$.states===void 0?Q`1 = 1`:$.states.length===0?Q`1 = 0`:Q`state IN (${UQ(Q,$.states)})`;return($.limit===void 0?await Q`
22
22
  SELECT * FROM ${this.name(Q)}
23
23
  WHERE thread_id = ${J} AND ${Z}
24
24
  ORDER BY created_at DESC, id DESC
@@ -27,36 +27,36 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
27
27
  WHERE thread_id = ${J} AND ${Z}
28
28
  ORDER BY created_at DESC, id DESC
29
29
  LIMIT ${Math.max(0,Math.floor($.limit))}
30
- `).map($J)}async transition(J,$,Q){if($.length===0)return!1;if("checkpoint"in Q)await this.requireLaterColumns("`job.checkpoint`");let Z=this.q(),W=this.clock(Z),X=[Z`updated_at = ${W}`];if(Q.deadlineMs!==void 0)X.push(Z`deadline_at = ${W} + ${this.ms(Z,Q.deadlineMs)}`);if("checkpoint"in Q)X.push(Z`job_checkpoint = ${c(Q.checkpoint)}`);if(Q.state!==void 0)X.push(Z`state = ${Q.state}`);if("output"in Q)X.push(Z`output = ${c(Q.output)}`);if("error"in Q)X.push(Z`error = ${c(Q.error)}`);if("usage"in Q)X.push(Z`${this.column(Z,"usage")} = ${c(Q.usage)}`);if("orphaned"in Q)X.push(Z`orphaned = ${Q.orphaned?1:0}`);if(Q.state!==void 0&&g(Q.state))X.push(Q.settledAt!==void 0?Z`settled_at = COALESCE(settled_at, ${this.ms(Z,Q.settledAt)})`:Z`settled_at = COALESCE(settled_at, ${W})`);let K=X.reduce((z,V)=>Z`${z}, ${V}`),G=await Z`
30
+ `).map(QJ)}async transition(J,$,Q){if($.length===0)return!1;if("checkpoint"in Q)await this.requireLaterColumns("`job.checkpoint`");let Z=this.q(),W=this.clock(Z),X=[Z`updated_at = ${W}`];if(Q.deadlineMs!==void 0)X.push(Z`deadline_at = ${W} + ${this.ms(Z,Q.deadlineMs)}`);if("checkpoint"in Q)X.push(Z`job_checkpoint = ${c(Q.checkpoint)}`);if(Q.state!==void 0)X.push(Z`state = ${Q.state}`);if("output"in Q)X.push(Z`output = ${c(Q.output)}`);if("error"in Q)X.push(Z`error = ${c(Q.error)}`);if("usage"in Q)X.push(Z`${this.column(Z,"usage")} = ${c(Q.usage)}`);if("orphaned"in Q)X.push(Z`orphaned = ${Q.orphaned?1:0}`);if(Q.state!==void 0&&g(Q.state))X.push(Q.settledAt!==void 0?Z`settled_at = COALESCE(settled_at, ${this.ms(Z,Q.settledAt)})`:Z`settled_at = COALESCE(settled_at, ${W})`);let K=X.reduce((z,V)=>Z`${z}, ${V}`),G=await Z`
31
31
  UPDATE ${this.name(Z)} SET ${K}
32
- WHERE id = ${J} AND state IN (${CQ(Z,$)})
33
- `;return wJ(G)>0}async overdue(J,$){let Q=this.q();return(await Q`
32
+ WHERE id = ${J} AND state IN (${UQ(Z,$)})
33
+ `;return bJ(G)>0}async overdue(J,$){let Q=this.q();return(await Q`
34
34
  SELECT * FROM ${this.name(Q)}
35
35
  WHERE state = 'running' AND deadline_at <= ${this.ms(Q,J)}
36
36
  ORDER BY deadline_at, id
37
37
  LIMIT ${Math.max(0,Math.floor($))}
38
- `).map($J)}async waitingOn(J){if(!await this.columns())return[];let $=this.q();return(await $`
38
+ `).map(QJ)}async waitingOn(J){if(!await this.columns())return[];let $=this.q();return(await $`
39
39
  SELECT * FROM ${this.name($)}
40
40
  WHERE state = 'waiting' AND after_jobs LIKE ${`%${JSON.stringify(J)}%`}
41
41
  ORDER BY created_at, id
42
- `).map($J).filter((Z)=>Z.after?.includes(J))}async waiting(J){let $=this.q();return(await $`
42
+ `).map(QJ).filter((Z)=>Z.after?.includes(J))}async waiting(J){let $=this.q();return(await $`
43
43
  SELECT * FROM ${this.name($)}
44
44
  WHERE state = 'waiting'
45
45
  ORDER BY created_at, id
46
46
  LIMIT ${Math.max(0,Math.floor(J))}
47
- `).map($J)}async listBatch(J){if(!await this.columns())return[];let $=this.q();return(await $`
47
+ `).map(QJ)}async listBatch(J){if(!await this.columns())return[];let $=this.q();return(await $`
48
48
  SELECT * FROM ${this.name($)} WHERE batch_key = ${J} ORDER BY created_at, id
49
- `).map($J)}async appendInbox(J,$){await this.requireLaterColumns("`AgentJobs.message`");for(let Q=0;Q<UQ;Q++){let Z=this.q(),[W]=await Z`
49
+ `).map(QJ)}async appendInbox(J,$){await this.requireLaterColumns("`AgentJobs.message`");for(let Q=0;Q<CQ;Q++){let Z=this.q(),[W]=await Z`
50
50
  SELECT state, inbox FROM ${this.name(Z)} WHERE id = ${J}
51
- `;if(!W||g(String(W.state)))return!1;let X=W.inbox===null||W.inbox===void 0?null:String(W.inbox),K=JSON.stringify([...b(X)??[],$]),G=await Z`
51
+ `;if(!W||g(String(W.state)))return!1;let X=W.inbox===null||W.inbox===void 0?null:String(W.inbox),K=JSON.stringify([...v(X)??[],$]),G=await Z`
52
52
  UPDATE ${this.name(Z)} SET inbox = ${K}, updated_at = ${this.clock(Z)}
53
53
  WHERE id = ${J} AND state IN ('waiting', 'running') AND ${this.sameInbox(Z,X)}
54
- `;if(wJ(G)>0)return!0}throw Error(`Could not add a message to background job ${J}: too many writers at once.`)}async takeInbox(J){if(!await this.columns())return[];for(let $=0;$<UQ;$++){let Q=this.q(),[Z]=await Q`SELECT inbox FROM ${this.name(Q)} WHERE id = ${J}`;if(!Z||Z.inbox===null||Z.inbox===void 0)return[];let W=String(Z.inbox),X=await Q`
54
+ `;if(bJ(G)>0)return!0}throw Error(`Could not add a message to background job ${J}: too many writers at once.`)}async takeInbox(J){if(!await this.columns())return[];for(let $=0;$<CQ;$++){let Q=this.q(),[Z]=await Q`SELECT inbox FROM ${this.name(Q)} WHERE id = ${J}`;if(!Z||Z.inbox===null||Z.inbox===void 0)return[];let W=String(Z.inbox),X=await Q`
55
55
  UPDATE ${this.name(Q)} SET inbox = NULL WHERE id = ${J} AND ${this.sameInbox(Q,W)}
56
- `;if(wJ(X)>0)return b(W)??[]}throw Error(`Could not take the messages of background job ${J}: too many writers.`)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async prune(J){let $=this.q(),Q=await $`
56
+ `;if(bJ(X)>0)return v(W)??[]}throw Error(`Could not take the messages of background job ${J}: too many writers.`)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async prune(J){let $=this.q(),Q=await $`
57
57
  DELETE FROM ${this.name($)}
58
58
  WHERE state IN ('ok', 'error') AND settled_at <= ${this.clock($)} - ${this.ms($,J)}
59
- `;return wJ(Q)}columns(){return this.later??=(async()=>{try{return await this.sql.unsafe(`SELECT ${FQ.join(", ")} FROM ${this.quoted(this.table)} WHERE 1 = 0`),!0}catch{return!1}})(),this.later}async requireLaterColumns(J){if(await this.columns())return;throw this.later=void 0,Error(`${J} needs the columns ${FQ.join(", ")} on the ${this.table} table, which it does not have. Add them (see docs/ai-background-jobs.md and UPGRADE.md), or call createTable() on a new table.`)}sameInbox(J,$){return $===null?J`inbox IS NULL`:J`inbox = ${$}`}quoted(J){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${J}\``:`"${J}"`}joinable(){if(this.connection===void 0)return;let J=QJ();if(J===void 0||ZJ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function CQ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function c(J){return J===void 0?null:JSON.stringify(J)}function b(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function $J(J){let $=b(J.summary),Q=b(J.output),Z=b(J.error),W=b(J.usage),X=b(J.after_jobs),K=b(J.queued),G=b(J.inbox),z=b(J.job_checkpoint);return{id:String(J.id),threadId:String(J.thread_id),runId:String(J.run_id),toolCallId:String(J.tool_call_id),toolName:String(J.tool_name),owner:J.owner===null||J.owner===void 0?null:String(J.owner),job:J.job===null||J.job===void 0?null:String(J.job),...$!==void 0?{summary:$}:{},state:String(J.state),...Q!==void 0?{output:Q}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number(J.orphaned)===1?{orphaned:!0}:{},attachmentScope:J.attachment_scope===null||J.attachment_scope===void 0?null:String(J.attachment_scope),...X!==void 0?{after:X}:{},...J.batch_key===null||J.batch_key===void 0?{}:{batch:String(J.batch_key)},...K!==void 0?{queued:K}:{},...G!==void 0&&G.length>0?{inbox:G}:{},...z!==void 0?{checkpoint:z}:{},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 wJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function i8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
59
+ `;return bJ(Q)}columns(){return this.later??=(async()=>{try{return await this.sql.unsafe(`SELECT ${FQ.join(", ")} FROM ${this.quoted(this.table)} WHERE 1 = 0`),!0}catch{return!1}})(),this.later}async requireLaterColumns(J){if(await this.columns())return;throw this.later=void 0,Error(`${J} needs the columns ${FQ.join(", ")} on the ${this.table} table, which it does not have. Add them (see docs/ai-background-jobs.md and UPGRADE.md), or call createTable() on a new table.`)}sameInbox(J,$){return $===null?J`inbox IS NULL`:J`inbox = ${$}`}quoted(J){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${J}\``:`"${J}"`}joinable(){if(this.connection===void 0)return;let J=ZJ();if(J===void 0||WJ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function UQ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function c(J){return J===void 0?null:JSON.stringify(J)}function v(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function QJ(J){let $=v(J.summary),Q=v(J.output),Z=v(J.error),W=v(J.usage),X=v(J.after_jobs),K=v(J.queued),G=v(J.inbox),z=v(J.job_checkpoint);return{id:String(J.id),threadId:String(J.thread_id),runId:String(J.run_id),toolCallId:String(J.tool_call_id),toolName:String(J.tool_name),owner:J.owner===null||J.owner===void 0?null:String(J.owner),job:J.job===null||J.job===void 0?null:String(J.job),...$!==void 0?{summary:$}:{},state:String(J.state),...Q!==void 0?{output:Q}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number(J.orphaned)===1?{orphaned:!0}:{},attachmentScope:J.attachment_scope===null||J.attachment_scope===void 0?null:String(J.attachment_scope),...X!==void 0?{after:X}:{},...J.batch_key===null||J.batch_key===void 0?{}:{batch:String(J.batch_key)},...K!==void 0?{queued:K}:{},...G!==void 0&&G.length>0?{inbox:G}:{},...z!==void 0?{checkpoint:z}:{},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 bJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function d8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
60
60
  \`id\` VARCHAR(191) NOT NULL,
61
61
  \`thread_id\` VARCHAR(191) NOT NULL,
62
62
  \`run_id\` VARCHAR(191) NOT NULL,
@@ -110,9 +110,9 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
110
110
  "queued" TEXT,
111
111
  "inbox" TEXT,
112
112
  "job_checkpoint" TEXT${Z}
113
- )`,`CREATE INDEX IF NOT EXISTS "${$}_thread_id_created_at_idx" ON "${$}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_state_deadline_at_idx" ON "${$}"("state", "deadline_at")`]}var SQ=4;class K${table;sql;dialect;connection;constructor(J,$={}){let Q=$.table??"gemi_agent_memories";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent memories table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of d8(this.dialect,this.table))await this.sql.unsafe(J)}async list(J,$={}){if(J.length===0)return[];if($.kinds!==void 0&&$.kinds.length===0)return[];let Q=this.q(),Z=[Q`scope IN (${YJ(Q,J)})`];if($.kinds!==void 0)Z.push(Q`kind IN (${YJ(Q,$.kinds)})`);if(!$.includeExpired)Z.push(Q`(expires_at IS NULL OR expires_at > ${this.clock(Q)})`);if($.after!==void 0){let[z]=await Q`
113
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_thread_id_created_at_idx" ON "${$}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_state_deadline_at_idx" ON "${$}"("state", "deadline_at")`]}var MQ=4;class z${table;sql;dialect;connection;constructor(J,$={}){let Q=$.table??"gemi_agent_memories";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent memories table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of n8(this.dialect,this.table))await this.sql.unsafe(J)}async list(J,$={}){if(J.length===0)return[];if($.kinds!==void 0&&$.kinds.length===0)return[];let Q=this.q(),Z=[Q`scope IN (${HJ(Q,J)})`];if($.kinds!==void 0)Z.push(Q`kind IN (${HJ(Q,$.kinds)})`);if(!$.includeExpired)Z.push(Q`(expires_at IS NULL OR expires_at > ${this.clock(Q)})`);if($.after!==void 0){let[z]=await Q`
114
114
  SELECT created_at, id FROM ${this.name(Q)}
115
- WHERE id = ${$.after} AND scope IN (${YJ(Q,J)})
115
+ WHERE id = ${$.after} AND scope IN (${HJ(Q,J)})
116
116
  `;if(z){let V=this.ms(Q,Number(z.created_at));Z.push(Q`(created_at > ${V} OR (created_at = ${V} AND id > ${String(z.id)}))`)}}let W=Z.reduce((z,V)=>Q`${z} AND ${V}`),X=$.limit===void 0||$.tags!==void 0?void 0:Math.max(0,Math.floor($.limit)),G=(X===void 0?await Q`
117
117
  SELECT * FROM ${this.name(Q)} WHERE ${W}
118
118
  ORDER BY created_at, id
@@ -120,16 +120,16 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
120
120
  SELECT * FROM ${this.name(Q)} WHERE ${W}
121
121
  ORDER BY created_at, id
122
122
  LIMIT ${X}
123
- `).map(X$);if($.tags!==void 0){if(G=G.filter((z)=>EQ(z,$.tags)),$.limit!==void 0)G=G.slice(0,Math.max(0,Math.floor($.limit)))}return G}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?X$(Q[0]):null}async upsert(J){let $=J.key??null;if($===null)return await this.insert(J,null),{record:await this.mustGet(J.id),action:"added"};for(let Q=1;;Q++){let Z=await this.atKey(J.scope,$);if(Z){if(kQ(Z,J))return{record:Z,action:"unchanged"};let W=await this.update(Z.id,{kind:J.kind,content:J.content,tags:J.tags??[],pinned:J.pinned??!1,expiresAt:J.expiresAt??null},Z.version);if(W)return{record:W,action:"updated"}}else try{return await this.insert(J,$),{record:await this.mustGet(J.id),action:"added"}}catch(W){if(Q>=SQ||!await this.atKey(J.scope,$))throw W}if(Q>=SQ)throw Error(`The memory at "${$}" in ${J.scope} kept changing while it was being written.`)}}async update(J,$,Q){let Z=this.q(),W=[Z`version = version + 1`,Z`updated_at = ${this.clock(Z)}`];if($.kind!==void 0)W.push(Z`kind = ${$.kind}`);if($.content!==void 0)W.push(Z`content = ${$.content}`);if($.key!==void 0)W.push(Z`${this.column(Z,"key")} = ${$.key}`);if($.tags!==void 0)W.push(Z`tags = ${JSON.stringify($.tags)}`);if($.pinned!==void 0)W.push(Z`pinned = ${$.pinned?1:0}`);if($.expiresAt!==void 0)W.push($.expiresAt===null?Z`expires_at = NULL`:Z`expires_at = ${this.ms(Z,$.expiresAt)}`);let X=W.reduce((G,z)=>Z`${G}, ${z}`),K=Q===void 0?await Z`UPDATE ${this.name(Z)} SET ${X} WHERE id = ${J}`:await Z`
123
+ `).map(V$);if($.tags!==void 0){if(G=G.filter((z)=>EQ(z,$.tags)),$.limit!==void 0)G=G.slice(0,Math.max(0,Math.floor($.limit)))}return G}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?V$(Q[0]):null}async upsert(J){let $=J.key??null;if($===null)return await this.insert(J,null),{record:await this.mustGet(J.id),action:"added"};for(let Q=1;;Q++){let Z=await this.atKey(J.scope,$);if(Z){if(kQ(Z,J))return{record:Z,action:"unchanged"};let W=await this.update(Z.id,{kind:J.kind,content:J.content,tags:J.tags??[],pinned:J.pinned??!1,expiresAt:J.expiresAt??null},Z.version);if(W)return{record:W,action:"updated"}}else try{return await this.insert(J,$),{record:await this.mustGet(J.id),action:"added"}}catch(W){if(Q>=MQ||!await this.atKey(J.scope,$))throw W}if(Q>=MQ)throw Error(`The memory at "${$}" in ${J.scope} kept changing while it was being written.`)}}async update(J,$,Q){let Z=this.q(),W=[Z`version = version + 1`,Z`updated_at = ${this.clock(Z)}`];if($.kind!==void 0)W.push(Z`kind = ${$.kind}`);if($.content!==void 0)W.push(Z`content = ${$.content}`);if($.key!==void 0)W.push(Z`${this.column(Z,"key")} = ${$.key}`);if($.tags!==void 0)W.push(Z`tags = ${JSON.stringify($.tags)}`);if($.pinned!==void 0)W.push(Z`pinned = ${$.pinned?1:0}`);if($.expiresAt!==void 0)W.push($.expiresAt===null?Z`expires_at = NULL`:Z`expires_at = ${this.ms(Z,$.expiresAt)}`);let X=W.reduce((G,z)=>Z`${G}, ${z}`),K=Q===void 0?await Z`UPDATE ${this.name(Z)} SET ${X} WHERE id = ${J}`:await Z`
124
124
  UPDATE ${this.name(Z)} SET ${X}
125
125
  WHERE id = ${J} AND version = ${Math.floor(Q)}
126
- `;if(qJ(K)===0)return null;return this.get(J)}async delete(J){if(J.length===0)return 0;let $=this.q(),Q=await $`DELETE FROM ${this.name($)} WHERE id IN (${YJ($,[...new Set(J)])})`;return qJ(Q)}async deleteScope(J){let $=this.q();return qJ(await $`DELETE FROM ${this.name($)} WHERE scope = ${J}`)}async search(J,$,Q={}){let Z=await this.list(J,{kinds:Q.kinds,tags:Q.tags});return RQ(Z,$,Q.limit)}async count(J){let $=this.q(),[Q]=await $`
126
+ `;if(yJ(K)===0)return null;return this.get(J)}async delete(J){if(J.length===0)return 0;let $=this.q(),Q=await $`DELETE FROM ${this.name($)} WHERE id IN (${HJ($,[...new Set(J)])})`;return yJ(Q)}async deleteScope(J){let $=this.q();return yJ(await $`DELETE FROM ${this.name($)} WHERE scope = ${J}`)}async search(J,$,Q={}){let Z=await this.list(J,{kinds:Q.kinds,tags:Q.tags});return RQ(Z,$,Q.limit)}async count(J){let $=this.q(),[Q]=await $`
127
127
  SELECT COUNT(*) AS total FROM ${this.name($)}
128
128
  WHERE scope = ${J} AND (expires_at IS NULL OR expires_at > ${this.clock($)})
129
129
  `;return Number(Q?.total??0)}async touch(J,$){if(J.length===0)return;let Q=this.q();await Q`
130
130
  UPDATE ${this.name(Q)} SET last_used_at = ${this.ms(Q,$)}
131
- WHERE id IN (${YJ(Q,[...new Set(J)])})
132
- `}async prune(J){let $=this.q();return qJ(await $`DELETE FROM ${this.name($)} WHERE expires_at IS NOT NULL AND expires_at <= ${this.ms($,J)}`)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async insert(J,$){let Q=this.q(),Z=this.clock(Q),W=J.expiresAt===void 0||J.expiresAt===null?null:Math.max(0,Math.round(J.expiresAt));await Q`
131
+ WHERE id IN (${HJ(Q,[...new Set(J)])})
132
+ `}async prune(J){let $=this.q();return yJ(await $`DELETE FROM ${this.name($)} WHERE expires_at IS NOT NULL AND expires_at <= ${this.ms($,J)}`)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async insert(J,$){let Q=this.q(),Z=this.clock(Q),W=J.expiresAt===void 0||J.expiresAt===null?null:Math.max(0,Math.round(J.expiresAt));await Q`
133
133
  INSERT INTO ${this.name(Q)}
134
134
  (id, scope, kind, ${this.column(Q,"key")}, content, tags, pinned, source, version,
135
135
  created_at, updated_at, expires_at)
@@ -140,7 +140,7 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
140
140
  ${W===null?null:this.ms(Q,W)})
141
141
  `}async atKey(J,$){let Q=this.q(),Z=await Q`
142
142
  SELECT * FROM ${this.name(Q)} WHERE scope = ${J} AND ${this.column(Q,"key")} = ${$}
143
- `;return Z[0]?X$(Z[0]):null}async mustGet(J){let $=await this.get(J);if(!$)throw Error(`The memory ${J} was not found after it was written.`);return $}joinable(){if(this.connection===void 0)return;let J=QJ();if(J===void 0||ZJ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function YJ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function AQ(J,$){if(J===null||J===void 0||J==="")return $;try{return JSON.parse(String(J))}catch{return $}}function X$(J){let $=AQ(J.tags,[]);return{id:String(J.id),scope:String(J.scope),kind:String(J.kind),content:String(J.content),key:J.key===null||J.key===void 0?null:String(J.key),tags:Array.isArray($)?$.map(String):[],pinned:Number(J.pinned)===1,source:AQ(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 qJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function d8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
143
+ `;return Z[0]?V$(Z[0]):null}async mustGet(J){let $=await this.get(J);if(!$)throw Error(`The memory ${J} was not found after it was written.`);return $}joinable(){if(this.connection===void 0)return;let J=ZJ();if(J===void 0||WJ()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function HJ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function AQ(J,$){if(J===null||J===void 0||J==="")return $;try{return JSON.parse(String(J))}catch{return $}}function V$(J){let $=AQ(J.tags,[]);return{id:String(J.id),scope:String(J.scope),kind:String(J.kind),content:String(J.content),key:J.key===null||J.key===void 0?null:String(J.key),tags:Array.isArray($)?$.map(String):[],pinned:Number(J.pinned)===1,source:AQ(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 yJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function n8(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
144
144
  \`id\` VARCHAR(191) NOT NULL,
145
145
  \`scope\` VARCHAR(191) NOT NULL,
146
146
  \`kind\` VARCHAR(191) NOT NULL,
@@ -177,8 +177,8 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
177
177
  "updated_at" BIGINT NOT NULL,
178
178
  "last_used_at" BIGINT,
179
179
  "expires_at" BIGINT${Z}
180
- )`,`CREATE INDEX IF NOT EXISTS "${$}_scope_kind_created_at_idx" ON "${$}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${$}_scope_key_key" ON "${$}"("scope", "key")`]}var yQ={n:0,mean:0,stddev:0,low:null,high:null};function d(J){let $=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if(J<0.5)return Math.log(Math.PI/Math.sin(Math.PI*J))-d(1-J);J-=1;let Q=$[0],Z=J+7.5;for(let W=1;W<9;W++)Q+=$[W]/(J+W);return 0.5*Math.log(2*Math.PI)+(J+0.5)*Math.log(Z)-Z+Math.log(Q)}function vQ(J,$,Q){let W=1,X=1-(J+$)*Q/(J+1);if(Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;X=1/X;let K=X;for(let G=1;G<=300;G++){let z=2*G,V=G*($-G)*Q/((J+z-1)*(J+z));if(X=1+V*X,Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+V/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(X=1/X,K*=X*W,V=-(J+G)*(J+$+G)*Q/((J+z)*(J+z+1)),X=1+V*X,Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+V/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;X=1/X;let Y=X*W;if(K*=Y,Math.abs(Y-1)<0.00000000000001)break}return K}function n8(J,$,Q){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(d($+Q)-d($)-d(Q)+$*Math.log(J)+Q*Math.log(1-J));return J<($+1)/($+Q+2)?Z*vQ($,Q,J)/$:1-Z*vQ(Q,$,1-J)/Q}function G$(J,$){return n8($/($+J*J),$/2,0.5)}function o8(J){if(!(J>0))return Number.POSITIVE_INFINITY;let $=1.959964,Q=2;while(G$(Q,J)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=($+Q)/2;if(G$(W,J)>0.05)$=W;else Q=W}return($+Q)/2}function s8(J,$,Q,Z){let W=J+Q,X=$+Z,K=(Y,D)=>d(Y+1)-d(D+1)-d(Y-D+1),G=(Y)=>Math.exp(K($,Y)+K(Z,W-Y)-K(X,W)),z=G(J),V=0;for(let Y=Math.max(0,W-Z);Y<=Math.min($,W);Y++){let D=G(Y);if(D<=z*1.0000001)V+=D}return Math.min(1,V)}function hQ(J,$){if(J.length<2)return 0;let Q=J.reduce((W,X)=>W+(X-$)**2,0),Z=Math.sqrt(Q/(J.length-1));return Z<0.000000000001*Math.max(1,Math.abs($))?0:Z}function V$(J){let $=J.length;if($===0)return yQ;let Q=J.map((G)=>G?1:0),Z=Q.reduce((G,z)=>G+z,0)/$,W=3.841458881296,X=(Z+W/(2*$))/(1+W/$),K=1.959964*Math.sqrt(Z*(1-Z)/$+W/(4*$*$))/(1+W/$);return{n:$,mean:Z,stddev:hQ(Q,Z),low:Math.max(0,X-K),high:Math.min(1,X+K)}}function z$(J){let $=J.length;if($===0)return yQ;let Q=J.reduce((X,K)=>X+K,0)/$,Z=hQ(J,Q);if($<2||Z===0)return{n:$,mean:Q,stddev:Z,low:null,high:null};let W=o8($-1)*Z/Math.sqrt($);return{n:$,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function DJ(J,$,Q){return{before:J.mean,after:$.mean,delta:$.mean-J.mean,p:Q,pAdjusted:Q,significant:!1}}function gQ(J,$){if(J.n===0||$.n===0)return DJ(J,$,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return DJ(J,$,s8(Q(J),J.n,Q($),$.n))}function cQ(J,$){if(J.n<2||$.n<2)return DJ(J,$,null);let Q=J.stddev**2/J.n,Z=$.stddev**2/$.n,W=Math.sqrt(Q+Z);if(W===0)return DJ(J,$,null);let X=(Q+Z)**2/(Q**2/(J.n-1)+Z**2/($.n-1));return DJ(J,$,G$(($.mean-J.mean)/W,X))}function uQ(J,$,Q){if(Q==="holm"){let Z=J.filter((X)=>X.p!==null).sort((X,K)=>X.p-K.p),W=0;Z.forEach((X,K)=>{W=Math.max(W,Math.min(1,X.p*(Z.length-K))),X.pAdjusted=W})}else for(let Z of J)Z.pAdjusted=Z.p;for(let Z of J)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<$&&Z.delta!==0}class bJ{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:($)=>bJ.judge($)}):J.graders,this.pricing=J.pricing}static create(J){let $=`The eval "${J.name}"`;HJ(J.runs,$,"runs"),HJ(J.concurrency,$,"concurrency");let Q=new Set;for(let W of J.cases){if(Q.has(W.id))throw Error(`${$} has two cases with the id "${W.id}".`);Q.add(W.id)}let Z=new bJ(J);for(let[W,X]of Object.entries(Z.graders))if(typeof X!=="function"&&X.kind==="judge")HJ(X.samples,`${$}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,$,Q={}){return nQ(J,$,Q)}static format(J,$={}){return e8(J,$)}async run(J={}){let $=`${this.name}.run`;HJ(J.runs,$,"runs"),HJ(J.concurrency,$,"concurrency");let Q=J.only?new Set(J.only):null;if(Q){let P=[...Q].filter((U)=>!this.cases.some((F)=>F.id===U));if(P.length>0)throw Error(`The eval "${this.name}" has no case ${P.map((U)=>`"${U}"`).join(", ")}.`)}let Z=J.runs??this.runs,W=Date.now(),X=new AbortController,K=J.signal?AbortSignal.any([J.signal,X.signal]):X.signal,G=this.cases.filter((P)=>!Q||Q.has(P.id)),z={};for(let[P,U]of Object.entries(this.graders)){if(K.aborted)break;if(typeof U==="function"||U.kind!=="judge"||!U.calibration)continue;z[P]=await this.calibrate(U,K)}let V=G.flatMap((P)=>Array.from({length:Z},(U,F)=>({test:P,run:F+1}))),Y=Array.from({length:V.length}),D=0,N,H=async()=>{while(D<V.length&&!K.aborted){let P=D++,U=V[P],F=await this.sample(U.test,U.run,K,J.keepOutputs??!1);Y[P]=F;try{J.onSample?.(F)}catch(O){N??={error:O},X.abort(O)}}},C=Math.min(J.concurrency??this.concurrency,V.length);if(await Promise.all(Array.from({length:C},H)),N)throw N.error;let _=Y.filter((P)=>P!==void 0);return this.report(_,z,Z,new Date(W).toISOString(),Date.now()-W,{aborted:K.aborted||_.length<V.length,planned:G.map((P)=>P.id)})}async sample(J,$,Q,Z){let W=Date.now(),X,K,G=await PJ(async()=>{try{X=await this.task(J.input,{case:J,run:$,signal:Q})}catch(C){K=sQ(C)}}),z={},V=!1,Y=await PJ(async()=>{if(K!==void 0)return;let C={case:J,input:J.input,run:$};for(let[_,P]of Object.entries(this.graders)){if(J.skip?.includes(_))continue;let U=await mQ(P,X,C,Q);if(!U)continue;if(z[_]=U,!U.pass&&typeof P!=="function"&&P.gate)V=!0}}),D=Object.values(z).map((C)=>C.score),N=K===void 0&&D.length===0,H=this.pricing?Y$(this.pricing,G.byModel).cost+Y$(this.pricing,Y.byModel).cost:void 0;return{case:J.id,run:$,pass:K===void 0&&!N&&Object.values(z).every((C)=>C.pass),excluded:V||N,...N?{ungraded:!0}:{},score:K!==void 0||N?0:oQ(D),grades:z,...K!==void 0?{error:K}:{},...Z&&K===void 0?{output:X}:{},usage:G.usage,byModel:t8(G.byModel,Y.byModel),judgeUsage:Y.usage,...H!==void 0?{cost:H}:{},durationMs:Date.now()-W}}async calibrate(J,$){let Q=J.calibration,Z=[],W=0,X=await PJ(async()=>{for(let[z,V]of Q.examples.entries()){if($.aborted)break;let Y=V.id??`example-${z+1}`,D={case:{id:Y,input:V.input},input:V.input,run:0},N=await mQ(J,V.output,D,$),H=N?.pass??!1;if(H===V.expected)W++;else Z.push({id:Y,expected:V.expected,got:H,...N?.note?{note:N.note}:{}})}}),K=Q.examples.length,G=K===0?1:W/K;return{n:K,agreement:G,ok:G>=(Q.minAgreement??0.8),disagreements:Z,usage:X.usage}}report(J,$,Q,Z,W,X){let K=new Set(Object.entries(this.graders).filter(([,N])=>typeof N!=="function"&&N.gate).map(([N])=>N)),G={};for(let N of this.cases){let H=J.filter((C)=>C.case===N.id);if(H.length===0)continue;G[N.id]={...pQ(H),graders:lQ(H,K)}}let z=S(),V=S(),Y={};for(let N of J){z=T(z,N.usage),V=T(V,N.judgeUsage);for(let[H,C]of Object.entries(N.byModel))Y[H]=T(Y[H]??S(),C)}let D=this.pricing?Y$(this.pricing,Y):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:Q,aborted:X.aborted,planned:X.planned,samples:J,cases:G,graders:lQ(J,K),calibration:$,totals:{...pQ(J),usage:z,judgeUsage:V,byModel:Y,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(Y)}}}}async function mQ(J,$,Q,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return D$(await J($,Q),W);if(J.kind!=="judge")return D$(await J.check($,Q),W);return await a8(J,$,Q,W,Z)}catch(X){return{pass:!1,score:0,error:sQ(X)}}}async function a8(J,$,Q,Z,W){let X=await J.prompt($,Q),K=typeof X==="string"?{prompt:X}:X,G=[];for(let D=0;D<(J.samples??1)&&!W.aborted;D++){let N=await H$({signal:W,provider:J.provider,...J.instructions!==void 0?{instructions:J.instructions}:{},...K,output:J.output,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},...J.maxOutputTokens!==void 0?{maxOutputTokens:J.maxOutputTokens}:{},...J.temperature!==void 0?{temperature:J.temperature}:{},logErrors:!1});if(!N.ok){G.push({pass:!1,score:0,error:`The judge failed: ${N.error.message}`});continue}let H=D$(J.verdict(N.output,Q),Z);if(H)G.push(H)}if(G.length===0)return null;if(G.length===1)return G[0];let z=G.filter((D)=>D.pass).length,V=G.map((D)=>D.note??D.error).filter(Boolean),Y=G.map((D)=>D.error).filter(Boolean);return{pass:z*2>G.length,score:oQ(G.map((D)=>D.score)),...V.length>0?{note:V.join(" | ")}:{},...Y.length===G.length?{error:Y.join(" | ")}:{}}}function D$(J,$){if(J===null||J===void 0)return null;if(typeof J==="boolean")return{pass:J,score:J?1:0};if(typeof J==="number"){if(!Number.isFinite(J))throw Error(`A grader answered the score ${J}.`);let Q=iQ(J);return{pass:Q>=$,score:Q}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:iQ(J.score),...J.note!==void 0?{note:J.note}:{}}}function pQ(J){let $=J.filter((Q)=>!Q.excluded);return{samples:J.length,kept:$.length,passed:$.filter((Q)=>Q.pass).length,errors:J.filter((Q)=>Q.error!==void 0).length,passRate:V$($.map((Q)=>Q.pass)),score:z$($.map((Q)=>Q.score))}}function lQ(J,$){let Q=J.filter((W)=>!W.excluded),Z=[...new Set(J.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let K=($.has(W)?J:Q).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:V$(K.map((G)=>G.pass)),score:z$(K.map((G)=>G.score))}]}))}function Y$(J,$){let Q=0,Z=[];for(let[W,X]of Object.entries($)){let K=dQ(J,W,X);if(K===void 0){Z.push(W);continue}Q+=K}return{cost:Q,unpriced:Z}}function t8(...J){let $={};for(let Q of J)for(let[Z,W]of Object.entries(Q))$[Z]=T($[Z]??S(),W);return $}function nQ(J,$,Q){for(let[P,U]of[["baseline",J],["current report",$]])if(U.aborted)throw Error(`Eval.compare: the ${P} for "${U.name}" was aborted (${U.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`);let Z=Q.alpha??0.05,W=Q.adjust??"holm",X=[],K=(P,U,F)=>{let O={label:P,passRate:gQ(U.passRate,F.passRate),score:cQ(U.score,F.score)};return X.push(O),{passRate:O.passRate,score:O.score}},G=(P,U,F)=>Object.fromEntries(Object.keys(F).filter((O)=>(O in U)).map((O)=>[O,K(`${P} ${O}`,U[O],F[O])])),z=(P,U)=>({fromCurrent:P.filter((F)=>!U.includes(F)),fromBaseline:U.filter((F)=>!P.includes(F))}),V=K("total",J.totals,$.totals),Y=G("case",J.cases,$.cases),D=G("grader",J.graders,$.graders),N=X.flatMap((P)=>[P.passRate,P.score]);uQ(N,Z,W);let H={cases:z([...new Set([...J.planned??[],...Object.keys(J.cases)])],[...new Set([...$.planned??[],...Object.keys($.cases)])]),graders:z(Object.keys(J.graders),Object.keys($.graders))},C=[...H.cases.fromCurrent.map((P)=>`case ${P}: in the baseline, missing from this report`),...H.graders.fromCurrent.map((P)=>`grader ${P}: in the baseline, missing from this report`)],_=[];for(let P of X)for(let[U,F]of[["pass rate",P.passRate],["score",P.score]]){if(!F.significant)continue;let O=`${P.label}: ${U} ${F.before.toFixed(2)} \u2192 ${F.after.toFixed(2)} (p = ${r8(F.pAdjusted)})`;(F.delta<0?C:_).push(O)}return{totals:V,cases:Y,graders:D,missing:H,comparisons:N.filter((P)=>P.p!==null).length,alpha:Z,adjust:W,regressions:C,improvements:_}}function r8(J){return J<0.001?"<0.001":J.toFixed(3)}function e8(J,$){let Q=$.baseline&&!$.baseline.aborted&&!J.aborted?nQ($.baseline,J,$):void 0,{totals:Z}=J,W=[];if(W.push(`eval ${J.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(J.durationMs/1000).toFixed(1)}s)`),J.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let X=(V)=>{if(V.n===0)return"-";let Y=V.mean.toFixed(2);if(V.low===null||V.high===null)return`${Y} (${V.n===1?"n=1":"no spread"})`;return`${Y} [${V.low.toFixed(2)}, ${V.high.toFixed(2)}]`},K=(V)=>V?` ${V.delta>=0?"+":""}${V.delta.toFixed(2)}${V.significant?"*":""}`:"",G=(V,Y)=>{let D=[0,1,2,3].map((H)=>Math.max(...[[V,"n","pass rate","score"],...Y].map((C)=>C[H].length))),N=(H)=>H.map((C,_)=>C.padEnd(D[_])).join(" ").trimEnd();W.push("",N([V,"n","pass rate","score"]),...Y.map(N))};G("case",Object.entries(J.cases).map(([V,Y])=>[V,`${Y.kept}/${Y.samples}`,X(Y.passRate)+K(Q?.cases[V]?.passRate),X(Y.score)+K(Q?.cases[V]?.score)])),G("grader",Object.entries(J.graders).map(([V,Y])=>[V,String(Y.passRate.n),X(Y.passRate)+K(Q?.graders[V]?.passRate),X(Y.score)+K(Q?.graders[V]?.score)])),W.push("",`total pass rate ${X(Z.passRate)}${K(Q?.totals.passRate)} score ${X(Z.score)}${K(Q?.totals.score)}`);for(let[V,Y]of Object.entries(J.calibration))W.push(`judge ${V}: agreement ${Y.agreement.toFixed(2)} on ${Y.n} examples${Y.ok?"":" (BELOW minAgreement)"}`);let z=(V)=>`${V.inputTokens} in, ${V.outputTokens} out`;if(W.push(`tokens: task ${z(Z.usage)}; judges ${z(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),Q){W.push("",`* significant at ${Q.alpha} over ${Q.comparisons} tests (${Q.adjust==="holm"?"Holm-adjusted":"unadjusted"}; Fisher's exact for pass rates, Welch's t for scores)`);for(let V of Q.regressions)W.push(`regression: ${V}`);for(let V of Q.improvements)W.push(`improvement: ${V}`)}return W.join(`
181
- `)}function oQ(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function iQ(J){return Math.min(1,Math.max(0,J))}function sQ(J){return J instanceof Error?J.message:String(J)}function HJ(J,$,Q){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${$} sets \`${Q}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var J9=/^[A-Za-z0-9_-]{1,64}$/;function $9(J,$){let Q=Q9($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((Y)=>P$(J,Y,Z));let X=Object.entries(Q.namespaces),K=new Set(J.descriptors().flatMap((Y)=>Y.tags));for(let[Y,D]of X){if(!J9.test(Y))throw Error(`toAgentTools: "${Y}" 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 "${Y}" needs a description. It is what the model reads to decide whether to look inside.`);if(!K.has(Y))throw Error(`toAgentTools: no tool is tagged "${Y}", so its namespace would be empty.`)}let G=new Map(X.map(([Y])=>[Y,[]])),z=[];for(let Y of W){let D=X.find(([N])=>Y.tags.includes(N))?.[0];if(D===void 0)z.push(P$(J,Y,Z));else G.get(D).push(P$(J,Y,!1))}let V=[];for(let[Y,D]of X){let N=G.get(Y);if(N.length===0)continue;V.push(N$.create({name:Y,description:D.description,tools:N,deferred:D.deferred??Z}))}return[...V,...z]}function Q9(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function P$(J,$,Q){if($.kind==="tool")return Z9(J,$,Q);return vJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Q,execute:(Z,W)=>{let X=n.getStore()?.req;if(!X)throw new o(`"${$.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:X},$.name,Z,W)}})}function Z9(J,$,Q){let Z=J.nativeTool($.name);return vJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:J.nativeApproval($.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,X)=>{let K=n.getStore()?.req;return J.startNative(K?{kind:"local",req:K}:void 0,$.name,W,X)}})}function W9(J){if(J==="auto")return;let $=/^(\d+)x(\d+)$/.exec(J);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let Q=Number($[1]),Z=Number($[2]);if(Q%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max(Q/Z,Z/Q)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function aQ(J,$){if(J.size!==void 0)try{W9(J.size)}catch(Q){throw Error(`${$}: ${Q.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let Q=J.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Q}.`)}}function tQ(J,$){if(J instanceof File)return J;let Q=J.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([J],`${$}.${Z}`,{type:Q})}class F${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;aQ(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new F$(J)}async generate(J){let $=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...$,signal:J.signal}))}async edit(J){let $=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...$,images:J.images.map((Q,Z)=>tQ(Q,`image-${Z}`)),...J.mask?{mask:tQ(J.mask,"mask")}:{},signal:J.signal}))}present(J){return rQ(this.provider.model,J.usage),X9(J)}merge(J){let $={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return aQ($,`ImageModel "${this.name}"`),$}}function X9(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}var U$=300000;function C$(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 yJ extends Error{code;retryable;retryAfter;constructor(J,$={}){super(J.message,$);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var K9={png:"image/png",jpeg:"image/jpeg"};function G9(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let X=J?.output_tokens_details?.image_tokens;if(typeof X==="number")Z.imageOutputTokens=X;return Z}function V9(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function z9(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new yJ({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:V9(Q),mimeType:K9[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:G9(J.usage)}}async function JZ(J,$,Q,Z){let W;try{W=await eQ(J,$,{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(X){if(Z.signal?.aborted)throw X;throw new yJ(WJ(X),{cause:X})}return z9(await W.json())}async function $Z(J,$,Q={}){return await JZ(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function QZ(J,$,Q={}){return await JZ(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class hJ{static models(){return[]}modelName(){return this.model}async generate(J){return await $Z(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let $=new FormData;for(let[Q,Z]of Object.entries(this.body(J)))if(Z!==void 0)$.set(Q,String(Z));for(let Q of J.images)$.append("image[]",Q,Q.name);if(J.mask)$.set("mask",J.mask,J.mask.name);return await QZ(this.endpoint(),$,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return WJ(J)}}var XZ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class _$ extends hJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new _$(J,$)}static models(){return XZ}endpoint(){return C$(ZZ(this.config,{timeoutMs:U$}))}}class O$ extends hJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new O$(J,$)}static models(){return XZ}modelName(){return this.config.deployment??this.model}endpoint(){return C$(WZ(this.config,{timeoutMs:U$}))}}class gJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,$){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return!0;let Z=this.now();if(Z<Q.openUntil)return!1;if(Q.probeUntil!==void 0&&Z<Q.probeUntil)return!1;return Q.probeUntil=Z+$.cooldownMs,!0}record(J,$,Q){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if($==="success")return this.entries.delete(J),W?"closed":void 0;if($==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let $=this.entries.get(J);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}var GZ=Symbol("timed-out");class NJ extends M${model;capabilities;entries;options;circuit;constructor(J,$={}){super();if(J.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of J)if(Z.timeoutMs!==void 0&&!(Z.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${Z.provider.model} must be a positive number, got ${Z.timeoutMs}.`);this.entries=[...J];let Q=$.circuit;if(Q){let Z=Q.failures??3,W=Q.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let X=new Set;for(let G of J){let z=L$(G);if(X.has(z))throw Error(`FallbackProvider: two legs share the circuit key "${z}". Give one of them a \`circuitKey\`.`);X.add(z)}let K=Q.store??new gJ;this.options={...$,circuit:{...Q,store:K}},this.circuit={policy:{failures:Z,cooldownMs:W},store:K,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=Y9(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new NJ(J,$)}from(J){if(!Number.isInteger(J)||J<0||J>=this.entries.length)throw RangeError(`FallbackProvider.from(${J}): the chain has ${this.entries.length} entries.`);return new NJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new NJ([$],this.options)}upload(J){return this.entries[0].provider.upload(J)}deleteFile(J){let $=this.entries[0].provider;if(!$.deleteFile)return Promise.reject(Error(`${$.constructor.name} cannot delete provider files: it does not implement deleteFile().`));return $.deleteFile(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let $,Q={},Z=J.signal,W=0;for(let X=0;X<this.entries.length;X++){let K=this.entries[X],G=X===this.entries.length-1,z=K.provider.model;if(this.circuit&&!G&&!await this.allow(K))continue;W+=1;let V=!1,Y=async(L)=>{if(V)return;V=!0,await this.record(X,K,L)},D=new AbortController,N=()=>D.abort(Z?.reason);if(Z?.aborted)D.abort(Z.reason);else Z?.addEventListener("abort",N,{once:!0});let H=[],C=!1,_=!1,P,U,F,O=!1,A,f=!1,x,I=(L)=>{x=L.usage;let R=L.model??z;if(!$)return{...L,model:R};let B={...Q};return B[R]=T(T(S(),B[R]??S()),L.usage),{type:"usage",usage:T(T(S(),$),L.usage),byModel:B}},v=(L)=>{let R=$?T(T(S(),$),L.usage):L.usage;return $=void 0,{...L,usage:R}};try{A=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:D.signal})[Symbol.asyncIterator]();let L=K.timeoutMs!==void 0?Date.now()+K.timeoutMs:void 0;for(;;){let R=!C&&L!==void 0?await D9(A.next(),Math.max(0,L-Date.now())):await A.next();if(R===GZ){O=!0,F={error:{code:"provider_error",message:`${z} did not start answering within ${K.timeoutMs}ms.`,retryable:!0}};break}if(R.done){f=!0;break}let B=R.value;if(B.type==="finish"&&B.model)U=B.model;if(B.type==="retry"){yield B;continue}if(B.type==="usage"){yield I(B);continue}if(C){if(B.type==="finish")P=T(P??S(),B.usage),_=!0,yield v(B);else{if(B.type==="error")F={error:B.error};yield B}continue}if(KZ(B)){C=!0,await Y("success"),yield*H.splice(0),yield B;continue}if(B.type==="error")F={error:B.error,...XJ(B)};else if(B.type==="finish"){if(P=T(P??S(),B.usage),B.reason==="error"&&!F)F={error:{code:"provider_error",message:`${z} ended the call with an error and did not say which.`,retryable:!1}}}H.push(B)}}catch(L){let R=K.provider.normalizeError(L);if(C){if(R.code!=="aborted")yield{type:"error",error:R,...XJ(L)};this.report({index:X,model:z,responseModel:U,attempt:W,usage:P,outcome:B$(R),error:R}),yield v({type:"finish",reason:R.code==="aborted"?"aborted":"error",usage:S(),...U?{model:U}:{}});return}F={error:R,...XJ(L)}}finally{if(Z?.removeEventListener("abort",N),!f)D.abort(),A?.return?.()?.catch(()=>{})}if(C){if(!_&&$)yield{type:"finish",reason:F?"error":"stop",usage:$},$=void 0;this.report({index:X,model:z,responseModel:U,attempt:W,usage:P,outcome:F?B$(F.error):"ok",...F?{error:F.error}:{}});return}if(Z?.aborted){await Y("none"),this.report({index:X,model:z,responseModel:U,attempt:W,usage:P,outcome:"aborted"}),yield v({type:"finish",reason:"aborted",usage:P??S(),...U?{model:U}:{}});return}if(!F){await Y("success"),this.report({index:X,model:z,responseModel:U,attempt:W,usage:P,outcome:"ok"});for(let L of H)yield L.type==="finish"?v(L):L;return}let r=!G&&F.error.code!=="aborted"&&this.shouldFallBack(F.error,{index:X,model:z,timedOut:O,...XJ(F)});if(await Y(r?"failure":"none"),this.report({index:X,model:z,responseModel:U,attempt:W,usage:P,outcome:r?"fallback":B$(F.error),error:F.error}),r){let L=P??x;if(L){$=T($??S(),L);let R=U??z;Q[R]=T(Q[R]??S(),L)}continue}let p=!1,l;for(let L of H){if(L.type==="finish"){l=L;continue}if(L.type==="error")p=!0;yield L}if(!p&&F.error.code!=="aborted")yield{type:"error",error:F.error,...XJ(F)};yield v({type:"finish",reason:F.error.code==="aborted"?"aborted":l?.reason??"error",usage:P??S(),...U?{model:U}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(L$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=L$($),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:$.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,$){let Q=this.options.fallbackOn??((Z)=>Z.retryable);try{return Q(J,$)}catch{return!1}}report(J){if(J.usage===void 0)delete J.usage;if(J.responseModel===void 0)delete J.responseModel;try{this.options.onUsage?.(J)}catch{}}}function L$(J){return J.circuitKey??J.provider.model}function B$(J){return J.code==="aborted"?"aborted":"failed"}function Y9(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch),supportsForcedToolChoice:J.every(($)=>$.supportsForcedToolChoice!==!1),trailingContext:J.every(($)=>$.trailingContext===!0),allowedTools:J.every(($)=>$.allowedTools===!0)}}function D9(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(GZ),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function H9(J,$,Q={}){let Z=Q.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let X=0;X<J.entries.length;X++){let K=J.leg(X),G={index:X,model:K.model,results:[],errors:[]};for(let z=0;z<Z;z++)try{G.results.push(await $(K,{index:X,sample:z}))}catch(V){G.errors.push({sample:z,error:V})}W.push(G)}return W}class uJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var UJ="ask_agent",P9={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},N9={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 FJ(J={}){return[{name:J.name??UJ,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 cJ=new Map;class s{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 s(J)}static get(J){return cJ.get(J)}static async endAll(J){await Promise.all([...cJ.values()].map(($)=>$.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...P9,...VZ(J.limits)},this.lines={...N9,...VZ(J.lines)},this.delegateName=J.delegate?.name??UJ;let $=new Set(FJ(J.delegate).map((Q)=>Q.name));for(let Q of J.tools??[]){if($.has(Q.tool.name)||this.toolHandlers.has(Q.tool.name))throw Error(`VoiceBridge: two tools are named "${Q.tool.name}".`);this.toolHandlers.set(Q.tool.name,Q)}if("realtime"in J.call){let{realtime:Q,callId:Z}=J.call;this.callId=Z,this.sideband=Q.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=J.call.callId??J.call.sideband.callId,this.sideband=J.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise((Q)=>this.resolveEnded=Q),cJ.set(this.sessionId,this),this.timers.push(setTimeout(()=>void this.end("max_duration",this.lines.maxDuration),this.limits.maxDurationMs)),this.tickTimer=setInterval(()=>void this.tick(),this.limits.tickMs),this.touch(),this.listen()}setBody(J){this.body=J;let $=this.params.contextNote?.(J);if($)this.sideband.addNote($)}end(J="hangup",$){return this.ending??=this.finish(J,$??null)}async listen(){for await(let J of this.sideband){try{this.params.onEvent?.(J)}catch{}this.closingWaiter?.(J),await this.handle(J)}}async handle(J){switch(J.type){case"input_audio_buffer.speech_started":this.touch();return;case"response.created":this.responseActive=!0,this.pendingCreate=void 0,this.touch();return;case"response.done":{if(this.responseActive=!1,this.responseWanted&&!this.ending)this.responseWanted=!1,this.createResponse();let $=J.usage;if($){this.usage=T(this.usage,$);let Q=this.info();this.hook(()=>this.params.onUsage?.($,Q))}return}case"conversation.item.input_audio_transcription.completed":{let $=J;if(this.say("user",String($.transcript??"")),$.transcriptionUsage||$.transcriptionSeconds!==void 0){this.transcription={usage:$.transcriptionUsage?T(this.transcription.usage,$.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+($.transcriptionSeconds??0)};let Q=this.info(),Z={...$.transcriptionUsage?{usage:$.transcriptionUsage}:{},...$.transcriptionSeconds!==void 0?{seconds:$.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}return}case"response.output_audio_transcript.done":this.say("assistant",String(J.transcript??""));return;case"response.output_text.done":this.say("assistant",String(J.text??""));return;case"response.function_call_arguments.done":{let $=J;if(this.touch(),!this.ending)this.call($.call_id,$.name,$.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let $=J.error;if(this.errors.push({code:$?.code,message:String($?.message??"")}),this.pendingCreate&&$?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,$.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let $=J;if(!this.ending&&!$.byClient)this.end($.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,$){if($.trim())this.transcript.push({role:J,text:$,at:Date.now()})}call(J,$,Q){let Z=F9(Q);if($===this.delegateName){let X=typeof Z.request==="string"?Z.request.trim():"";if(!X)return this.answer(J,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:X,status:"queued"},turn:{text:X},callId:J})}let W=this.toolHandlers.get($);if(W)return void this.runTool(J,W,Z);switch($){case"stop_work":{let X=this.running;if(X)X.stopRequested=!0,X.handle?.stop({reason:"Stopped by voice."});let K=this.dropQueue();return this.answer(J,{stopped:Boolean(X),dropped:K})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((X)=>X.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 X=typeof Z.answer==="string"?Z.answer:"",K=typeof Z.approve==="boolean"?Z.approve:void 0,G=this.pending.map((z)=>U9(z,X,K));return this.pending=[],this.enqueue({record:{request:`(answer) ${X}`,status:"queued"},turn:{toolResults:G},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${$}.`})}}enqueue(J){if(!this.running){this.requests.push(J.record),this.run(J);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(J.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(J.record),this.queue.push(J),this.answer(J.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),J.callId=void 0}async run(J){this.running=J,J.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let $=new Set;await this.waitForThread($);let Q=await this.latestBody();while(!J.stopRequested&&await this.waitForThread($));if(J.stopRequested||this.ending){J.record.status="dropped",this.complete(J,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:Q,turn:J.turn})}catch(X){J.record.status="refused",this.complete(J,{status:"refused",message:X instanceof Error?X.message:"The request could not be started."});return}J.handle=Z,J.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(J.record.status="done",J.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(J,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(J,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(J,{status:"stopped",text:W.text});else this.complete(J,{status:"done",text:W.text})}catch($){J.record.status="done",this.complete(J,{status:"failed",message:$ instanceof Error?$.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let $=this.queue.shift();if($&&!this.ending)this.run($);else this.touch()}}async runTool(J,$,Q){let Z=$.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let X={name:Z,status:"running"};this.toolCalls.push(X),this.toolsRunning+=1,this.pauseIdle();let K=new AbortController,G=$.timeoutMs??this.limits.toolTimeoutMs,z,V;try{let D=await Promise.race([$.run(Q,{sessionId:this.sessionId,signal:K.signal}),new Promise((N,H)=>{z=setTimeout(()=>{H(new o(`"${Z}" took longer than ${Math.round(G/1000)} s.`)),K.abort()},G)})]);X.status="done",V={status:"done",output:this.clip(D)}}catch(D){if(D instanceof uJ){X.status="refused",X.message=D.message,this.end("usage",D.line??null);return}let N=D instanceof o?D.message:"The tool failed.";if(!(D instanceof o))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);X.status="failed",X.message=N,V={status:"failed",message:N}}finally{clearTimeout(z),X.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let Y=this.info();if(this.hook(()=>this.params.onToolCall?.({...X},Y)),!this.ending)this.answer(J,V)}clip(J){let $;try{$=JSON.stringify(J)}catch{return String(J)}if($===void 0||$.length<=this.limits.toolOutputChars)return J;return`${$.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${$.length} characters in all)`}async waitForThread(J=new Set){let $=this.params.liveRuns;if(!$)return!1;let Q=await $.find({threadId:this.threadId}),Z=Q&&!J.has(Q.runId)?$.get(Q.runId):null;if(!Q||!Z)return!1;return J.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let $=await J.get(this.sessionId).catch(()=>null);if($)this.body=$.body;return this.body}async follow(J){let $=this.params.progress??C9();try{for await(let Q of J.run){let Z=$(Q);if(Z)this.note(Z)}}catch{}}complete(J,$){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,$),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify($)}`);this.respond()}answer(J,$){this.sideband.functionOutput(J,$),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let J=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=J,this.sideband.send({type:"response.create",event_id:J})}questions(){return this.pending.map((J)=>({kind:J.kind,tool:String(J.name),input:J.input}))}dropQueue(){let J=this.queue.splice(0);for(let $ of J)$.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let $=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if($<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),$)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let J=this.info();this.hook(()=>this.params.onTick?.(J))}hook(J){this.hooks=this.hooks.then(async()=>{try{await J()}catch($){if($ instanceof uJ)this.end("usage",$.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",$),this.end("error",this.lines.error)}})}tampered(J){let $=this.params.session;if(!$||!J)return!1;if($.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==$.instructions)return!0;if(Array.isArray(J.tools)){let Q=new Set([...FJ(this.params.delegate),...$.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if(Q.size!==Z.size||[...Q].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,$){for(let K of this.timers)clearTimeout(K);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),$&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine($);if(J!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,X={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};cJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(X)}catch(K){console.error("[gemi/ai] a voice session's onEnd threw.",K)}return this.resolveEnded(X),X}async hangUp(){try{await this.hangupCall()}catch(J){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",J),this.errors.push({code:"hangup_failed",message:J instanceof Error?J.message:String(J)});let $;await Promise.race([this.sideband.closed,new Promise((Q)=>$=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout($),this.sideband.close()}}async closingLine(J){await new Promise(($)=>{let Q=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",X,K=setTimeout(G,this.limits.closingLineMs);function G(){clearTimeout(K),$()}let z=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(V)=>{let Y=V;if(Y.type==="sideband.closed")return G();if(W==="cancelling"){if(Y.type==="response.done"||Y.type==="error"&&Y.error?.event_id===Z)z();return}if(Y.type==="error"&&Y.error?.event_id===Q)return G();if(Y.type==="response.created"&&!X){X=Y.response?.id;return}let D=(N)=>!X||!N||N===X;if(Y.type==="response.done"&&D(Y.response?.id))W="playing";else if(Y.type==="output_audio_buffer.stopped"&&W==="playing"&&D(Y.response_id))G()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else z()}),this.closingWaiter=void 0}}function VZ(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function F9(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function U9(J,$,Q){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:$};if(J.kind==="approval")return{...Z,approve:Q===!0,...$?{reason:$}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function C9(){let J=new Set;return($)=>{if($.type==="tool-call"){if($.part.partial||$.resent||J.has($.part.toolCallId))return;return J.add($.part.toolCallId),`running ${String($.part.name)}`}if($.type==="tool-progress"){let Q=$.data;if(typeof Q==="string")return Q;if(Q&&typeof Q==="object")for(let Z of["message","label","title"]){let W=Q[Z];if(typeof W==="string"&&W)return W}}return}}var zZ="http://gemi.internal/__gemi__/voice/mcp";async function S$(J,$){if(!$.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:Q}=J,Z=J.scopes??Q.scopes().map((K)=>K.name),W=(K)=>({kind:"remote",req:K,principal:{user:$.user,via:"voice",id:`voice:${$.sessionId}`,scopes:Z}});return(await Q.available(W(YZ()),J.filter)).filter((K)=>!K.requiresApproval).map((K)=>({tool:{name:K.name,description:K.description,parameters:K.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(G,z)=>{let V=YZ();return n.run(V,async()=>{return await J.authorize?.({name:K.name,input:G,sessionId:z.sessionId}),Q.execute(W(V),K.name,G,void 0,{signal:z.signal})},{user:$.user})}}))}function YZ(){return new w(new Request(zZ,{method:"POST"}),{},"api",new URL(zZ).pathname)}class A${records=new Map;retainEndedMs;constructor(J={}){this.retainEndedMs=J.retainEndedMs??600000}async create(J){this.sweep(),this.records.set(J.id,structuredClone(J))}async get(J){let $=this.records.get(J);return $?structuredClone($):null}async update(J,$){let Q=this.records.get(J);if(!Q)return;this.records.set(J,{...Q,...structuredClone($),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[$,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<J)this.records.delete($)}}var R$=new A$;var DZ=new WeakMap,HZ=100;class E${threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(J,$={}){if(this.threadsTable=PZ($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=PZ($.messagesTable??"gemi_agent_messages","messages"),this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.options=$,$.ttlMs!==void 0)CZ($.ttlMs,"ttlMs")}get expires(){return this.options.ttlMs!==void 0}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A DatabaseAgentStore scope is a non-empty string.");let $=new E$({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return $.scope=J,$}async createTable(){let J=L9(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($);await this.addScopeColumns(),await this.addExpiryColumns()}async addExpiryColumns(){if(await this.hasColumn(this.threadsTable,"expires_at"))return;for(let J of M9(this.dialect,this.threadsTable))await this.sql.unsafe(J)}async addScopeColumns(){let J=B9(this.dialect,this.threadsTable,this.messagesTable);for(let[$,Q]of J){if(await this.hasColumn($,"scope"))continue;for(let Z of Q)await this.sql.unsafe(Z)}}async hasColumn(J,$){try{return await this.sql.unsafe(`SELECT ${$} FROM ${this.quote(J)} WHERE 1 = 0`),!0}catch{return!1}}async createThread(J={}){let $=crypto.randomUUID(),Q=J.userId===void 0||J.userId===null?null:String(J.userId),Z=this.expiryOf(J);return await this.run(async(W)=>{let X=this.clock(W);if(Z){let K=Z.at!==void 0?this.ms(W,Z.at):Z.ttlMs===null?null:W`${X} + ${this.ms(W,Z.ttlMs)}`,G=Z.slides&&Z.ttlMs!==null?this.ms(W,Z.ttlMs):null;if(this.scope===null)await W`
180
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_scope_kind_created_at_idx" ON "${$}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${$}_scope_key_key" ON "${$}"("scope", "key")`]}var yQ={n:0,mean:0,stddev:0,low:null,high:null};function d(J){let $=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if(J<0.5)return Math.log(Math.PI/Math.sin(Math.PI*J))-d(1-J);J-=1;let Q=$[0],Z=J+7.5;for(let W=1;W<9;W++)Q+=$[W]/(J+W);return 0.5*Math.log(2*Math.PI)+(J+0.5)*Math.log(Z)-Z+Math.log(Q)}function vQ(J,$,Q){let W=1,X=1-(J+$)*Q/(J+1);if(Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;X=1/X;let K=X;for(let G=1;G<=300;G++){let z=2*G,V=G*($-G)*Q/((J+z-1)*(J+z));if(X=1+V*X,Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+V/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(X=1/X,K*=X*W,V=-(J+G)*(J+$+G)*Q/((J+z)*(J+z+1)),X=1+V*X,Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+V/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;X=1/X;let Y=X*W;if(K*=Y,Math.abs(Y-1)<0.00000000000001)break}return K}function o8(J,$,Q){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(d($+Q)-d($)-d(Q)+$*Math.log(J)+Q*Math.log(1-J));return J<($+1)/($+Q+2)?Z*vQ($,Q,J)/$:1-Z*vQ(Q,$,1-J)/Q}function Y$(J,$){return o8($/($+J*J),$/2,0.5)}function s8(J){if(!(J>0))return Number.POSITIVE_INFINITY;let $=1.959964,Q=2;while(Y$(Q,J)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=($+Q)/2;if(Y$(W,J)>0.05)$=W;else Q=W}return($+Q)/2}function a8(J,$,Q,Z){let W=J+Q,X=$+Z,K=(Y,D)=>d(Y+1)-d(D+1)-d(Y-D+1),G=(Y)=>Math.exp(K($,Y)+K(Z,W-Y)-K(X,W)),z=G(J),V=0;for(let Y=Math.max(0,W-Z);Y<=Math.min($,W);Y++){let D=G(Y);if(D<=z*1.0000001)V+=D}return Math.min(1,V)}function hQ(J,$){if(J.length<2)return 0;let Q=J.reduce((W,X)=>W+(X-$)**2,0),Z=Math.sqrt(Q/(J.length-1));return Z<0.000000000001*Math.max(1,Math.abs($))?0:Z}function D$(J){let $=J.length;if($===0)return yQ;let Q=J.map((G)=>G?1:0),Z=Q.reduce((G,z)=>G+z,0)/$,W=3.841458881296,X=(Z+W/(2*$))/(1+W/$),K=1.959964*Math.sqrt(Z*(1-Z)/$+W/(4*$*$))/(1+W/$);return{n:$,mean:Z,stddev:hQ(Q,Z),low:Math.max(0,X-K),high:Math.min(1,X+K)}}function H$(J){let $=J.length;if($===0)return yQ;let Q=J.reduce((X,K)=>X+K,0)/$,Z=hQ(J,Q);if($<2||Z===0)return{n:$,mean:Q,stddev:Z,low:null,high:null};let W=s8($-1)*Z/Math.sqrt($);return{n:$,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function PJ(J,$,Q){return{before:J.mean,after:$.mean,delta:$.mean-J.mean,p:Q,pAdjusted:Q,significant:!1}}function gQ(J,$){if(J.n===0||$.n===0)return PJ(J,$,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return PJ(J,$,a8(Q(J),J.n,Q($),$.n))}function cQ(J,$){if(J.n<2||$.n<2)return PJ(J,$,null);let Q=J.stddev**2/J.n,Z=$.stddev**2/$.n,W=Math.sqrt(Q+Z);if(W===0)return PJ(J,$,null);let X=(Q+Z)**2/(Q**2/(J.n-1)+Z**2/($.n-1));return PJ(J,$,Y$(($.mean-J.mean)/W,X))}function uQ(J,$,Q){if(Q==="holm"){let Z=J.filter((X)=>X.p!==null).sort((X,K)=>X.p-K.p),W=0;Z.forEach((X,K)=>{W=Math.max(W,Math.min(1,X.p*(Z.length-K))),X.pAdjusted=W})}else for(let Z of J)Z.pAdjusted=Z.p;for(let Z of J)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<$&&Z.delta!==0}class hJ{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:($)=>hJ.judge($)}):J.graders,this.pricing=J.pricing}static create(J){let $=`The eval "${J.name}"`;NJ(J.runs,$,"runs"),NJ(J.concurrency,$,"concurrency");let Q=new Set;for(let W of J.cases){if(Q.has(W.id))throw Error(`${$} has two cases with the id "${W.id}".`);Q.add(W.id)}let Z=new hJ(J);for(let[W,X]of Object.entries(Z.graders))if(typeof X!=="function"&&X.kind==="judge")NJ(X.samples,`${$}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,$,Q={}){return nQ(J,$,Q)}static format(J,$={}){return J9(J,$)}async run(J={}){let $=`${this.name}.run`;NJ(J.runs,$,"runs"),NJ(J.concurrency,$,"concurrency");let Q=J.only?new Set(J.only):null;if(Q){let P=[...Q].filter((C)=>!this.cases.some((F)=>F.id===C));if(P.length>0)throw Error(`The eval "${this.name}" has no case ${P.map((C)=>`"${C}"`).join(", ")}.`)}let Z=J.runs??this.runs,W=Date.now(),X=new AbortController,K=J.signal?AbortSignal.any([J.signal,X.signal]):X.signal,G=this.cases.filter((P)=>!Q||Q.has(P.id)),z={};for(let[P,C]of Object.entries(this.graders)){if(K.aborted)break;if(typeof C==="function"||C.kind!=="judge"||!C.calibration)continue;z[P]=await this.calibrate(C,K)}let V=G.flatMap((P)=>Array.from({length:Z},(C,F)=>({test:P,run:F+1}))),Y=Array.from({length:V.length}),D=0,N,H=async()=>{while(D<V.length&&!K.aborted){let P=D++,C=V[P],F=await this.sample(C.test,C.run,K,J.keepOutputs??!1);Y[P]=F;try{J.onSample?.(F)}catch(O){N??={error:O},X.abort(O)}}},U=Math.min(J.concurrency??this.concurrency,V.length);if(await Promise.all(Array.from({length:U},H)),N)throw N.error;let _=Y.filter((P)=>P!==void 0);return this.report(_,z,Z,new Date(W).toISOString(),Date.now()-W,{aborted:K.aborted||_.length<V.length,planned:G.map((P)=>P.id)})}async sample(J,$,Q,Z){let W=Date.now(),X,K,G=await FJ(async()=>{try{X=await this.task(J.input,{case:J,run:$,signal:Q})}catch(U){K=sQ(U)}}),z={},V=!1,Y=await FJ(async()=>{if(K!==void 0)return;let U={case:J,input:J.input,run:$};for(let[_,P]of Object.entries(this.graders)){if(J.skip?.includes(_))continue;let C=await mQ(P,X,U,Q);if(!C)continue;if(z[_]=C,!C.pass&&typeof P!=="function"&&P.gate)V=!0}}),D=Object.values(z).map((U)=>U.score),N=K===void 0&&D.length===0,H=this.pricing?P$(this.pricing,G.byModel).cost+P$(this.pricing,Y.byModel).cost:void 0;return{case:J.id,run:$,pass:K===void 0&&!N&&Object.values(z).every((U)=>U.pass),excluded:V||N,...N?{ungraded:!0}:{},score:K!==void 0||N?0:oQ(D),grades:z,...K!==void 0?{error:K}:{},...Z&&K===void 0?{output:X}:{},usage:G.usage,byModel:r8(G.byModel,Y.byModel),judgeUsage:Y.usage,...H!==void 0?{cost:H}:{},durationMs:Date.now()-W}}async calibrate(J,$){let Q=J.calibration,Z=[],W=0,X=await FJ(async()=>{for(let[z,V]of Q.examples.entries()){if($.aborted)break;let Y=V.id??`example-${z+1}`,D={case:{id:Y,input:V.input},input:V.input,run:0},N=await mQ(J,V.output,D,$),H=N?.pass??!1;if(H===V.expected)W++;else Z.push({id:Y,expected:V.expected,got:H,...N?.note?{note:N.note}:{}})}}),K=Q.examples.length,G=K===0?1:W/K;return{n:K,agreement:G,ok:G>=(Q.minAgreement??0.8),disagreements:Z,usage:X.usage}}report(J,$,Q,Z,W,X){let K=new Set(Object.entries(this.graders).filter(([,N])=>typeof N!=="function"&&N.gate).map(([N])=>N)),G={};for(let N of this.cases){let H=J.filter((U)=>U.case===N.id);if(H.length===0)continue;G[N.id]={...pQ(H),graders:lQ(H,K)}}let z=S(),V=S(),Y={};for(let N of J){z=k(z,N.usage),V=k(V,N.judgeUsage);for(let[H,U]of Object.entries(N.byModel))Y[H]=k(Y[H]??S(),U)}let D=this.pricing?P$(this.pricing,Y):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:Q,aborted:X.aborted,planned:X.planned,samples:J,cases:G,graders:lQ(J,K),calibration:$,totals:{...pQ(J),usage:z,judgeUsage:V,byModel:Y,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(Y)}}}}async function mQ(J,$,Q,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return N$(await J($,Q),W);if(J.kind!=="judge")return N$(await J.check($,Q),W);return await t8(J,$,Q,W,Z)}catch(X){return{pass:!1,score:0,error:sQ(X)}}}async function t8(J,$,Q,Z,W){let X=await J.prompt($,Q),K=typeof X==="string"?{prompt:X}:X,G=[];for(let D=0;D<(J.samples??1)&&!W.aborted;D++){let N=await F$({signal:W,provider:J.provider,...J.instructions!==void 0?{instructions:J.instructions}:{},...K,output:J.output,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},...J.maxOutputTokens!==void 0?{maxOutputTokens:J.maxOutputTokens}:{},...J.temperature!==void 0?{temperature:J.temperature}:{},logErrors:!1});if(!N.ok){G.push({pass:!1,score:0,error:`The judge failed: ${N.error.message}`});continue}let H=N$(J.verdict(N.output,Q),Z);if(H)G.push(H)}if(G.length===0)return null;if(G.length===1)return G[0];let z=G.filter((D)=>D.pass).length,V=G.map((D)=>D.note??D.error).filter(Boolean),Y=G.map((D)=>D.error).filter(Boolean);return{pass:z*2>G.length,score:oQ(G.map((D)=>D.score)),...V.length>0?{note:V.join(" | ")}:{},...Y.length===G.length?{error:Y.join(" | ")}:{}}}function N$(J,$){if(J===null||J===void 0)return null;if(typeof J==="boolean")return{pass:J,score:J?1:0};if(typeof J==="number"){if(!Number.isFinite(J))throw Error(`A grader answered the score ${J}.`);let Q=iQ(J);return{pass:Q>=$,score:Q}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:iQ(J.score),...J.note!==void 0?{note:J.note}:{}}}function pQ(J){let $=J.filter((Q)=>!Q.excluded);return{samples:J.length,kept:$.length,passed:$.filter((Q)=>Q.pass).length,errors:J.filter((Q)=>Q.error!==void 0).length,passRate:D$($.map((Q)=>Q.pass)),score:H$($.map((Q)=>Q.score))}}function lQ(J,$){let Q=J.filter((W)=>!W.excluded),Z=[...new Set(J.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let K=($.has(W)?J:Q).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:D$(K.map((G)=>G.pass)),score:H$(K.map((G)=>G.score))}]}))}function P$(J,$){let Q=0,Z=[];for(let[W,X]of Object.entries($)){let K=dQ(J,W,X);if(K===void 0){Z.push(W);continue}Q+=K}return{cost:Q,unpriced:Z}}function r8(...J){let $={};for(let Q of J)for(let[Z,W]of Object.entries(Q))$[Z]=k($[Z]??S(),W);return $}function nQ(J,$,Q){for(let[P,C]of[["baseline",J],["current report",$]])if(C.aborted)throw Error(`Eval.compare: the ${P} for "${C.name}" was aborted (${C.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`);let Z=Q.alpha??0.05,W=Q.adjust??"holm",X=[],K=(P,C,F)=>{let O={label:P,passRate:gQ(C.passRate,F.passRate),score:cQ(C.score,F.score)};return X.push(O),{passRate:O.passRate,score:O.score}},G=(P,C,F)=>Object.fromEntries(Object.keys(F).filter((O)=>(O in C)).map((O)=>[O,K(`${P} ${O}`,C[O],F[O])])),z=(P,C)=>({fromCurrent:P.filter((F)=>!C.includes(F)),fromBaseline:C.filter((F)=>!P.includes(F))}),V=K("total",J.totals,$.totals),Y=G("case",J.cases,$.cases),D=G("grader",J.graders,$.graders),N=X.flatMap((P)=>[P.passRate,P.score]);uQ(N,Z,W);let H={cases:z([...new Set([...J.planned??[],...Object.keys(J.cases)])],[...new Set([...$.planned??[],...Object.keys($.cases)])]),graders:z(Object.keys(J.graders),Object.keys($.graders))},U=[...H.cases.fromCurrent.map((P)=>`case ${P}: in the baseline, missing from this report`),...H.graders.fromCurrent.map((P)=>`grader ${P}: in the baseline, missing from this report`)],_=[];for(let P of X)for(let[C,F]of[["pass rate",P.passRate],["score",P.score]]){if(!F.significant)continue;let O=`${P.label}: ${C} ${F.before.toFixed(2)} \u2192 ${F.after.toFixed(2)} (p = ${e8(F.pAdjusted)})`;(F.delta<0?U:_).push(O)}return{totals:V,cases:Y,graders:D,missing:H,comparisons:N.filter((P)=>P.p!==null).length,alpha:Z,adjust:W,regressions:U,improvements:_}}function e8(J){return J<0.001?"<0.001":J.toFixed(3)}function J9(J,$){let Q=$.baseline&&!$.baseline.aborted&&!J.aborted?nQ($.baseline,J,$):void 0,{totals:Z}=J,W=[];if(W.push(`eval ${J.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(J.durationMs/1000).toFixed(1)}s)`),J.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let X=(V)=>{if(V.n===0)return"-";let Y=V.mean.toFixed(2);if(V.low===null||V.high===null)return`${Y} (${V.n===1?"n=1":"no spread"})`;return`${Y} [${V.low.toFixed(2)}, ${V.high.toFixed(2)}]`},K=(V)=>V?` ${V.delta>=0?"+":""}${V.delta.toFixed(2)}${V.significant?"*":""}`:"",G=(V,Y)=>{let D=[0,1,2,3].map((H)=>Math.max(...[[V,"n","pass rate","score"],...Y].map((U)=>U[H].length))),N=(H)=>H.map((U,_)=>U.padEnd(D[_])).join(" ").trimEnd();W.push("",N([V,"n","pass rate","score"]),...Y.map(N))};G("case",Object.entries(J.cases).map(([V,Y])=>[V,`${Y.kept}/${Y.samples}`,X(Y.passRate)+K(Q?.cases[V]?.passRate),X(Y.score)+K(Q?.cases[V]?.score)])),G("grader",Object.entries(J.graders).map(([V,Y])=>[V,String(Y.passRate.n),X(Y.passRate)+K(Q?.graders[V]?.passRate),X(Y.score)+K(Q?.graders[V]?.score)])),W.push("",`total pass rate ${X(Z.passRate)}${K(Q?.totals.passRate)} score ${X(Z.score)}${K(Q?.totals.score)}`);for(let[V,Y]of Object.entries(J.calibration))W.push(`judge ${V}: agreement ${Y.agreement.toFixed(2)} on ${Y.n} examples${Y.ok?"":" (BELOW minAgreement)"}`);let z=(V)=>`${V.inputTokens} in, ${V.outputTokens} out`;if(W.push(`tokens: task ${z(Z.usage)}; judges ${z(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),Q){W.push("",`* significant at ${Q.alpha} over ${Q.comparisons} tests (${Q.adjust==="holm"?"Holm-adjusted":"unadjusted"}; Fisher's exact for pass rates, Welch's t for scores)`);for(let V of Q.regressions)W.push(`regression: ${V}`);for(let V of Q.improvements)W.push(`improvement: ${V}`)}return W.join(`
181
+ `)}function oQ(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function iQ(J){return Math.min(1,Math.max(0,J))}function sQ(J){return J instanceof Error?J.message:String(J)}function NJ(J,$,Q){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${$} sets \`${Q}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var $9=/^[A-Za-z0-9_-]{1,64}$/;function Q9(J,$){let Q=Z9($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((Y)=>C$(J,Y,Z));let X=Object.entries(Q.namespaces),K=new Set(J.descriptors().flatMap((Y)=>Y.tags));for(let[Y,D]of X){if(!$9.test(Y))throw Error(`toAgentTools: "${Y}" 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 "${Y}" needs a description. It is what the model reads to decide whether to look inside.`);if(!K.has(Y))throw Error(`toAgentTools: no tool is tagged "${Y}", so its namespace would be empty.`)}let G=new Map(X.map(([Y])=>[Y,[]])),z=[];for(let Y of W){let D=X.find(([N])=>Y.tags.includes(N))?.[0];if(D===void 0)z.push(C$(J,Y,Z));else G.get(D).push(C$(J,Y,!1))}let V=[];for(let[Y,D]of X){let N=G.get(Y);if(N.length===0)continue;V.push(U$.create({name:Y,description:D.description,tools:N,deferred:D.deferred??Z}))}return[...V,...z]}function Z9(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function C$(J,$,Q){if($.kind==="tool")return W9(J,$,Q);return gJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Q,execute:(Z,W)=>{let X=n.getStore()?.req;if(!X)throw new o(`"${$.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:X},$.name,Z,W)}})}function W9(J,$,Q){let Z=J.nativeTool($.name);return gJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:J.nativeApproval($.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,X)=>{let K=n.getStore()?.req;return J.startNative(K?{kind:"local",req:K}:void 0,$.name,W,X)}})}function X9(J){if(J==="auto")return;let $=/^(\d+)x(\d+)$/.exec(J);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let Q=Number($[1]),Z=Number($[2]);if(Q%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max(Q/Z,Z/Q)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function aQ(J,$){if(J.size!==void 0)try{X9(J.size)}catch(Q){throw Error(`${$}: ${Q.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let Q=J.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Q}.`)}}function tQ(J,$){if(J instanceof File)return J;let Q=J.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([J],`${$}.${Z}`,{type:Q})}class _${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;aQ(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new _$(J)}async generate(J){let $=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...$,signal:J.signal}))}async edit(J){let $=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...$,images:J.images.map((Q,Z)=>tQ(Q,`image-${Z}`)),...J.mask?{mask:tQ(J.mask,"mask")}:{},signal:J.signal}))}present(J){return rQ(this.provider.model,J.usage),K9({...J,usage:eQ(this.provider.model,J.usage)})}merge(J){let $={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return aQ($,`ImageModel "${this.name}"`),$}}function K9(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}var O$=300000;function L$(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 cJ extends Error{code;retryable;retryAfter;constructor(J,$={}){super(J.message,$);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var G9={png:"image/png",jpeg:"image/jpeg"};function V9(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let X=J?.output_tokens_details?.image_tokens;if(typeof X==="number")Z.imageOutputTokens=X;return Z}function z9(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function Y9(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new cJ({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:z9(Q),mimeType:G9[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:V9(J.usage)}}async function $Z(J,$,Q,Z){let W;try{W=await JZ(J,$,{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(X){if(Z.signal?.aborted)throw X;throw new cJ(XJ(X),{cause:X})}return Y9(await W.json())}async function QZ(J,$,Q={}){return await $Z(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function ZZ(J,$,Q={}){return await $Z(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class uJ{static models(){return[]}modelName(){return this.model}async generate(J){return await QZ(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let $=new FormData;for(let[Q,Z]of Object.entries(this.body(J)))if(Z!==void 0)$.set(Q,String(Z));for(let Q of J.images)$.append("image[]",Q,Q.name);if(J.mask)$.set("mask",J.mask,J.mask.name);return await ZZ(this.endpoint(),$,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return XJ(J)}}var KZ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class B$ extends uJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new B$(J,$)}static models(){return KZ}endpoint(){return L$(WZ(this.config,{timeoutMs:O$}))}}class S$ extends uJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new S$(J,$)}static models(){return KZ}modelName(){return this.config.deployment??this.model}endpoint(){return L$(XZ(this.config,{timeoutMs:O$}))}}class mJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,$){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return!0;let Z=this.now();if(Z<Q.openUntil)return!1;if(Q.probeUntil!==void 0&&Z<Q.probeUntil)return!1;return Q.probeUntil=Z+$.cooldownMs,!0}record(J,$,Q){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if($==="success")return this.entries.delete(J),W?"closed":void 0;if($==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let $=this.entries.get(J);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}var VZ=Symbol("timed-out");class CJ extends R${model;capabilities;entries;options;circuit;constructor(J,$={}){super();if(J.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of J)if(Z.timeoutMs!==void 0&&!(Z.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${Z.provider.model} must be a positive number, got ${Z.timeoutMs}.`);this.entries=[...J];let Q=$.circuit;if(Q){let Z=Q.failures??3,W=Q.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let X=new Set;for(let G of J){let z=M$(G);if(X.has(z))throw Error(`FallbackProvider: two legs share the circuit key "${z}". Give one of them a \`circuitKey\`.`);X.add(z)}let K=Q.store??new mJ;this.options={...$,circuit:{...Q,store:K}},this.circuit={policy:{failures:Z,cooldownMs:W},store:K,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=D9(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new CJ(J,$)}from(J){if(!Number.isInteger(J)||J<0||J>=this.entries.length)throw RangeError(`FallbackProvider.from(${J}): the chain has ${this.entries.length} entries.`);return new CJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new CJ([$],this.options)}upload(J){return this.entries[0].provider.upload(J)}deleteFile(J){let $=this.entries[0].provider;if(!$.deleteFile)return Promise.reject(Error(`${$.constructor.name} cannot delete provider files: it does not implement deleteFile().`));return $.deleteFile(J)}cacheWriteFactor(J){return(this.entries.find((Q)=>Q.provider.model===J)??this.entries.find((Q)=>J.startsWith(Q.provider.model)))?.provider.cacheWriteFactor?.(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let $,Q={},Z=J.signal,W=0;for(let X=0;X<this.entries.length;X++){let K=this.entries[X],G=X===this.entries.length-1,z=K.provider.model;if(this.circuit&&!G&&!await this.allow(K))continue;W+=1;let V=!1,Y=async(L)=>{if(V)return;V=!0,await this.record(X,K,L)},D=new AbortController,N=()=>D.abort(Z?.reason);if(Z?.aborted)D.abort(Z.reason);else Z?.addEventListener("abort",N,{once:!0});let H=[],U=!1,_=!1,P,C,F,O=!1,R,f=!1,x,I=(L)=>{x=L.usage;let A=L.model??z;if(!$)return{...L,model:A};let B={...Q};return B[A]=k(k(S(),B[A]??S()),L.usage),{type:"usage",usage:k(k(S(),$),L.usage),byModel:B}},h=(L)=>{if(!$)return L;let A=L.model??z,B={...Q};B[A]=k(k(S(),B[A]??S()),L.usage);let q=k(k(S(),$),L.usage);$=void 0;for(let e of Object.keys(Q))delete Q[e];let DJ=Object.entries(B).filter(([e,kJ])=>e===A||kJ.totalTokens>0);return DJ.length>1?{...L,usage:q,byModel:Object.fromEntries(DJ)}:{...L,usage:q}};try{R=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:D.signal})[Symbol.asyncIterator]();let L=K.timeoutMs!==void 0?Date.now()+K.timeoutMs:void 0;for(;;){let A=!U&&L!==void 0?await H9(R.next(),Math.max(0,L-Date.now())):await R.next();if(A===VZ){O=!0,F={error:{code:"provider_error",message:`${z} did not start answering within ${K.timeoutMs}ms.`,retryable:!0}};break}if(A.done){f=!0;break}let B=A.value;if(B.type==="finish"&&B.model)C=B.model;if(B.type==="retry"){yield B;continue}if(B.type==="usage"){yield I(B);continue}if(U){if(B.type==="finish")P=k(P??S(),B.usage),_=!0,yield h(B);else{if(B.type==="error")F={error:B.error};yield B}continue}if(GZ(B)){U=!0,await Y("success"),yield*H.splice(0),yield B;continue}if(B.type==="error")F={error:B.error,...KJ(B)};else if(B.type==="finish"){if(P=k(P??S(),B.usage),B.reason==="error"&&!F)F={error:{code:"provider_error",message:`${z} ended the call with an error and did not say which.`,retryable:!1}}}H.push(B)}}catch(L){let A=K.provider.normalizeError(L);if(U){if(A.code!=="aborted")yield{type:"error",error:A,...KJ(L)};this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:A$(A),error:A}),yield h({type:"finish",reason:A.code==="aborted"?"aborted":"error",usage:S(),...C?{model:C}:{}});return}F={error:A,...KJ(L)}}finally{if(Z?.removeEventListener("abort",N),!f)D.abort(),R?.return?.()?.catch(()=>{})}if(U){if(!_&&$)yield{type:"finish",reason:F?"error":"stop",usage:$,byModel:{...Q}},$=void 0;this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:F?A$(F.error):"ok",...F?{error:F.error}:{}});return}if(Z?.aborted){await Y("none"),this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:"aborted"}),yield h({type:"finish",reason:"aborted",usage:P??S(),...C?{model:C}:{}});return}if(!F){await Y("success"),this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:"ok"});for(let L of H)yield L.type==="finish"?h(L):L;return}let r=!G&&F.error.code!=="aborted"&&this.shouldFallBack(F.error,{index:X,model:z,timedOut:O,...KJ(F)});if(await Y(r?"failure":"none"),this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:r?"fallback":A$(F.error),error:F.error}),r){let L=P??x;if(L){$=k($??S(),L);let A=C??z;Q[A]=k(Q[A]??S(),L)}continue}let p=!1,l;for(let L of H){if(L.type==="finish"){l=L;continue}if(L.type==="error")p=!0;yield L}if(!p&&F.error.code!=="aborted")yield{type:"error",error:F.error,...KJ(F)};yield h({type:"finish",reason:F.error.code==="aborted"?"aborted":l?.reason??"error",usage:P??S(),...C?{model:C}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(M$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=M$($),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:$.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,$){let Q=this.options.fallbackOn??((Z)=>Z.retryable);try{return Q(J,$)}catch{return!1}}report(J){if(J.usage===void 0)delete J.usage;if(J.responseModel===void 0)delete J.responseModel;try{this.options.onUsage?.(J)}catch{}}}function M$(J){return J.circuitKey??J.provider.model}function A$(J){return J.code==="aborted"?"aborted":"failed"}function D9(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch),supportsForcedToolChoice:J.every(($)=>$.supportsForcedToolChoice!==!1),trailingContext:J.every(($)=>$.trailingContext===!0),allowedTools:J.every(($)=>$.allowedTools===!0)}}function H9(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(VZ),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function P9(J,$,Q={}){let Z=Q.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let X=0;X<J.entries.length;X++){let K=J.leg(X),G={index:X,model:K.model,results:[],errors:[]};for(let z=0;z<Z;z++)try{G.results.push(await $(K,{index:X,sample:z}))}catch(V){G.errors.push({sample:z,error:V})}W.push(G)}return W}class lJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var _J="ask_agent",N9={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},F9={maxDuration:"We've reached the time limit for this voice session. Tap the microphone to start again.",idle:"It's gone quiet, so I'll hang up. Tap the microphone when you want to talk again.",error:null};function UJ(J={}){return[{name:J.name??_J,description:J.description??"Hand one self-contained request to the agent that does the work, in the user's own words with references resolved. It can take minutes; the result comes back when it is done, so tell the user you are on it.",parameters:{type:"object",properties:{request:{type:"string",description:"What the user wants done."}},required:["request"],additionalProperties:!1}},{name:"stop_work",description:"Stop the work that is running, and drop any requests waiting behind it.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"work_status",description:"What the agent is doing right now, and what is waiting.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"answer_question",description:"Answer the question the agent asked (it came back from a request with status needs_input). For an approval, set approve.",parameters:{type:"object",properties:{answer:{type:"string",description:"The user's answer, in their words."},approve:{type:"boolean",description:"For an approval: whether the user approved."}},required:["answer"],additionalProperties:!1}}]}var pJ=new Map;class s{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 s(J)}static get(J){return pJ.get(J)}static async endAll(J){await Promise.all([...pJ.values()].map(($)=>$.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...N9,...zZ(J.limits)},this.lines={...F9,...zZ(J.lines)},this.delegateName=J.delegate?.name??_J;let $=new Set(UJ(J.delegate).map((Q)=>Q.name));for(let Q of J.tools??[]){if($.has(Q.tool.name)||this.toolHandlers.has(Q.tool.name))throw Error(`VoiceBridge: two tools are named "${Q.tool.name}".`);this.toolHandlers.set(Q.tool.name,Q)}if("realtime"in J.call){let{realtime:Q,callId:Z}=J.call;this.callId=Z,this.sideband=Q.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=J.call.callId??J.call.sideband.callId,this.sideband=J.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise((Q)=>this.resolveEnded=Q),pJ.set(this.sessionId,this),this.timers.push(setTimeout(()=>void this.end("max_duration",this.lines.maxDuration),this.limits.maxDurationMs)),this.tickTimer=setInterval(()=>void this.tick(),this.limits.tickMs),this.touch(),this.listen()}setBody(J){this.body=J;let $=this.params.contextNote?.(J);if($)this.sideband.addNote($)}end(J="hangup",$){return this.ending??=this.finish(J,$??null)}async listen(){for await(let J of this.sideband){try{this.params.onEvent?.(J)}catch{}this.closingWaiter?.(J),await this.handle(J)}}async handle(J){switch(J.type){case"input_audio_buffer.speech_started":this.touch();return;case"response.created":this.responseActive=!0,this.pendingCreate=void 0,this.touch();return;case"response.done":{if(this.responseActive=!1,this.responseWanted&&!this.ending)this.responseWanted=!1,this.createResponse();let $=J.usage;if($){this.usage=k(this.usage,$);let Q=this.info();this.hook(()=>this.params.onUsage?.($,Q))}return}case"conversation.item.input_audio_transcription.completed":{let $=J;if(this.say("user",String($.transcript??"")),$.transcriptionUsage||$.transcriptionSeconds!==void 0){this.transcription={usage:$.transcriptionUsage?k(this.transcription.usage,$.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+($.transcriptionSeconds??0)};let Q=this.info(),Z={...$.transcriptionUsage?{usage:$.transcriptionUsage}:{},...$.transcriptionSeconds!==void 0?{seconds:$.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}return}case"response.output_audio_transcript.done":this.say("assistant",String(J.transcript??""));return;case"response.output_text.done":this.say("assistant",String(J.text??""));return;case"response.function_call_arguments.done":{let $=J;if(this.touch(),!this.ending)this.call($.call_id,$.name,$.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let $=J.error;if(this.errors.push({code:$?.code,message:String($?.message??"")}),this.pendingCreate&&$?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,$.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let $=J;if(!this.ending&&!$.byClient)this.end($.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,$){if($.trim())this.transcript.push({role:J,text:$,at:Date.now()})}call(J,$,Q){let Z=C9(Q);if($===this.delegateName){let X=typeof Z.request==="string"?Z.request.trim():"";if(!X)return this.answer(J,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:X,status:"queued"},turn:{text:X},callId:J})}let W=this.toolHandlers.get($);if(W)return void this.runTool(J,W,Z);switch($){case"stop_work":{let X=this.running;if(X)X.stopRequested=!0,X.handle?.stop({reason:"Stopped by voice."});let K=this.dropQueue();return this.answer(J,{stopped:Boolean(X),dropped:K})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((X)=>X.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 X=typeof Z.answer==="string"?Z.answer:"",K=typeof Z.approve==="boolean"?Z.approve:void 0,G=this.pending.map((z)=>U9(z,X,K));return this.pending=[],this.enqueue({record:{request:`(answer) ${X}`,status:"queued"},turn:{toolResults:G},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${$}.`})}}enqueue(J){if(!this.running){this.requests.push(J.record),this.run(J);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(J.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(J.record),this.queue.push(J),this.answer(J.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),J.callId=void 0}async run(J){this.running=J,J.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let $=new Set;await this.waitForThread($);let Q=await this.latestBody();while(!J.stopRequested&&await this.waitForThread($));if(J.stopRequested||this.ending){J.record.status="dropped",this.complete(J,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:Q,turn:J.turn})}catch(X){J.record.status="refused",this.complete(J,{status:"refused",message:X instanceof Error?X.message:"The request could not be started."});return}J.handle=Z,J.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(J.record.status="done",J.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(J,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(J,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(J,{status:"stopped",text:W.text});else this.complete(J,{status:"done",text:W.text})}catch($){J.record.status="done",this.complete(J,{status:"failed",message:$ instanceof Error?$.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let $=this.queue.shift();if($&&!this.ending)this.run($);else this.touch()}}async runTool(J,$,Q){let Z=$.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let X={name:Z,status:"running"};this.toolCalls.push(X),this.toolsRunning+=1,this.pauseIdle();let K=new AbortController,G=$.timeoutMs??this.limits.toolTimeoutMs,z,V;try{let D=await Promise.race([$.run(Q,{sessionId:this.sessionId,signal:K.signal}),new Promise((N,H)=>{z=setTimeout(()=>{H(new o(`"${Z}" took longer than ${Math.round(G/1000)} s.`)),K.abort()},G)})]);X.status="done",V={status:"done",output:this.clip(D)}}catch(D){if(D instanceof lJ){X.status="refused",X.message=D.message,this.end("usage",D.line??null);return}let N=D instanceof o?D.message:"The tool failed.";if(!(D instanceof o))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);X.status="failed",X.message=N,V={status:"failed",message:N}}finally{clearTimeout(z),X.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let Y=this.info();if(this.hook(()=>this.params.onToolCall?.({...X},Y)),!this.ending)this.answer(J,V)}clip(J){let $;try{$=JSON.stringify(J)}catch{return String(J)}if($===void 0||$.length<=this.limits.toolOutputChars)return J;return`${$.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${$.length} characters in all)`}async waitForThread(J=new Set){let $=this.params.liveRuns;if(!$)return!1;let Q=await $.find({threadId:this.threadId}),Z=Q&&!J.has(Q.runId)?$.get(Q.runId):null;if(!Q||!Z)return!1;return J.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let $=await J.get(this.sessionId).catch(()=>null);if($)this.body=$.body;return this.body}async follow(J){let $=this.params.progress??_9();try{for await(let Q of J.run){let Z=$(Q);if(Z)this.note(Z)}}catch{}}complete(J,$){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,$),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify($)}`);this.respond()}answer(J,$){this.sideband.functionOutput(J,$),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let J=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=J,this.sideband.send({type:"response.create",event_id:J})}questions(){return this.pending.map((J)=>({kind:J.kind,tool:String(J.name),input:J.input}))}dropQueue(){let J=this.queue.splice(0);for(let $ of J)$.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let $=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if($<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),$)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let J=this.info();this.hook(()=>this.params.onTick?.(J))}hook(J){this.hooks=this.hooks.then(async()=>{try{await J()}catch($){if($ instanceof lJ)this.end("usage",$.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",$),this.end("error",this.lines.error)}})}tampered(J){let $=this.params.session;if(!$||!J)return!1;if($.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==$.instructions)return!0;if(Array.isArray(J.tools)){let Q=new Set([...UJ(this.params.delegate),...$.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if(Q.size!==Z.size||[...Q].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,$){for(let K of this.timers)clearTimeout(K);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),$&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine($);if(J!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,X={sessionId:this.sessionId,...this.callId?{callId:this.callId}:{},threadId:this.threadId,reason:J,startedAt:this.startedAt,endedAt:Z,durationMs:W,seconds:Math.ceil(W/1000),usage:this.usage,transcription:this.transcription,transcript:this.transcript,requests:this.requests,toolCalls:this.toolCalls,errors:this.errors};pJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(X)}catch(K){console.error("[gemi/ai] a voice session's onEnd threw.",K)}return this.resolveEnded(X),X}async hangUp(){try{await this.hangupCall()}catch(J){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",J),this.errors.push({code:"hangup_failed",message:J instanceof Error?J.message:String(J)});let $;await Promise.race([this.sideband.closed,new Promise((Q)=>$=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout($),this.sideband.close()}}async closingLine(J){await new Promise(($)=>{let Q=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",X,K=setTimeout(G,this.limits.closingLineMs);function G(){clearTimeout(K),$()}let z=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(V)=>{let Y=V;if(Y.type==="sideband.closed")return G();if(W==="cancelling"){if(Y.type==="response.done"||Y.type==="error"&&Y.error?.event_id===Z)z();return}if(Y.type==="error"&&Y.error?.event_id===Q)return G();if(Y.type==="response.created"&&!X){X=Y.response?.id;return}let D=(N)=>!X||!N||N===X;if(Y.type==="response.done"&&D(Y.response?.id))W="playing";else if(Y.type==="output_audio_buffer.stopped"&&W==="playing"&&D(Y.response_id))G()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else z()}),this.closingWaiter=void 0}}function zZ(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function C9(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function U9(J,$,Q){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:$};if(J.kind==="approval")return{...Z,approve:Q===!0,...$?{reason:$}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function _9(){let J=new Set;return($)=>{if($.type==="tool-call"){if($.part.partial||$.resent||J.has($.part.toolCallId))return;return J.add($.part.toolCallId),`running ${String($.part.name)}`}if($.type==="tool-progress"){let Q=$.data;if(typeof Q==="string")return Q;if(Q&&typeof Q==="object")for(let Z of["message","label","title"]){let W=Q[Z];if(typeof W==="string"&&W)return W}}return}}var YZ="http://gemi.internal/__gemi__/voice/mcp";async function E$(J,$){if(!$.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:Q}=J,Z=J.scopes??Q.scopes().map((K)=>K.name),W=(K)=>({kind:"remote",req:K,principal:{user:$.user,via:"voice",id:`voice:${$.sessionId}`,scopes:Z}});return(await Q.available(W(DZ()),J.filter)).filter((K)=>!K.requiresApproval).map((K)=>({tool:{name:K.name,description:K.description,parameters:K.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(G,z)=>{let V=DZ();return n.run(V,async()=>{return await J.authorize?.({name:K.name,input:G,sessionId:z.sessionId}),Q.execute(W(V),K.name,G,void 0,{signal:z.signal})},{user:$.user})}}))}function DZ(){return new w(new Request(YZ,{method:"POST"}),{},"api",new URL(YZ).pathname)}class k${records=new Map;retainEndedMs;constructor(J={}){this.retainEndedMs=J.retainEndedMs??600000}async create(J){this.sweep(),this.records.set(J.id,structuredClone(J))}async get(J){let $=this.records.get(J);return $?structuredClone($):null}async update(J,$){let Q=this.records.get(J);if(!Q)return;this.records.set(J,{...Q,...structuredClone($),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[$,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<J)this.records.delete($)}}var T$=new k$;var HZ=new WeakMap,PZ=100;class j${threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(J,$={}){if(this.threadsTable=NZ($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=NZ($.messagesTable??"gemi_agent_messages","messages"),this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.options=$,$.ttlMs!==void 0)_Z($.ttlMs,"ttlMs")}get expires(){return this.options.ttlMs!==void 0}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A DatabaseAgentStore scope is a non-empty string.");let $=new j$({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return $.scope=J,$}async createTable(){let J=B9(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($);await this.addScopeColumns(),await this.addExpiryColumns()}async addExpiryColumns(){if(await this.hasColumn(this.threadsTable,"expires_at"))return;for(let J of M9(this.dialect,this.threadsTable))await this.sql.unsafe(J)}async addScopeColumns(){let J=S9(this.dialect,this.threadsTable,this.messagesTable);for(let[$,Q]of J){if(await this.hasColumn($,"scope"))continue;for(let Z of Q)await this.sql.unsafe(Z)}}async hasColumn(J,$){try{return await this.sql.unsafe(`SELECT ${$} FROM ${this.quote(J)} WHERE 1 = 0`),!0}catch{return!1}}async createThread(J={}){let $=crypto.randomUUID(),Q=J.userId===void 0||J.userId===null?null:String(J.userId),Z=this.expiryOf(J);return await this.run(async(W)=>{let X=this.clock(W);if(Z){let K=Z.at!==void 0?this.ms(W,Z.at):Z.ttlMs===null?null:W`${X} + ${this.ms(W,Z.ttlMs)}`,G=Z.slides&&Z.ttlMs!==null?this.ms(W,Z.ttlMs):null;if(this.scope===null)await W`
182
182
  INSERT INTO ${this.threads(W)} (id, user_id, created_at, updated_at, expires_at, ttl_ms)
183
183
  VALUES (${$}, ${Q}, ${X}, ${X}, ${K}, ${G})
184
184
  `;else await W`
@@ -197,7 +197,7 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
197
197
  SELECT message FROM ${this.messages($)}
198
198
  WHERE thread_id = ${J} AND ${this.inScope($)}
199
199
  ORDER BY position
200
- `).map((W)=>JSON.parse(String(W.message)))})}async appendMessages(J,$){if($.length===0){if(await this.getThread(J)===null)throw NZ(J);return}await this.atomically(async(Q)=>{if(this.expires)await Q`
200
+ `).map((W)=>JSON.parse(String(W.message)))})}async appendMessages(J,$){if($.length===0){if(await this.getThread(J)===null)throw FZ(J);return}await this.atomically(async(Q)=>{if(this.expires)await Q`
201
201
  UPDATE ${this.threads(Q)}
202
202
  SET updated_at = ${this.clock(Q)},
203
203
  expires_at = CASE WHEN ttl_ms IS NULL THEN expires_at ELSE ${this.clock(Q)} + ttl_ms END
@@ -208,9 +208,9 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
208
208
  `;let Z=await Q`
209
209
  SELECT title FROM ${this.threads(Q)}
210
210
  WHERE id = ${J} AND ${this.inScope(Q)} AND ${this.live(Q)}
211
- `;if(Z.length===0)throw NZ(J);let W=[...new Set($.map((V)=>V.id))],X=await Q`
211
+ `;if(Z.length===0)throw FZ(J);let W=[...new Set($.map((V)=>V.id))],X=await Q`
212
212
  SELECT id FROM ${this.messages(Q)}
213
- WHERE thread_id = ${J} AND id IN (${KJ(Q,W)})
213
+ WHERE thread_id = ${J} AND id IN (${GJ(Q,W)})
214
214
  `,K=new Set(X.map((V)=>String(V.id))),[G]=await Q`
215
215
  SELECT MAX(position) AS position FROM ${this.messages(Q)} WHERE thread_id = ${J}
216
216
  `,z=G?.position===null||G?.position===void 0?0:Number(G.position)+1;for(let V of $){let Y=JSON.stringify(V);if(K.has(V.id))await Q`
@@ -222,23 +222,23 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
222
222
  `,K.add(V.id),z+=1;else await Q`
223
223
  INSERT INTO ${this.messages(Q)} (thread_id, scope, id, position, message, created_at)
224
224
  VALUES (${J}, ${this.scope}, ${V.id}, ${z}, ${Y}, ${this.clock(Q)})
225
- `,K.add(V.id),z+=1}if(Z[0].title===null||Z[0].title===void 0){let V=_9($);if(V!==null)await Q`
225
+ `,K.add(V.id),z+=1}if(Z[0].title===null||Z[0].title===void 0){let V=O9($);if(V!==null)await Q`
226
226
  UPDATE ${this.threads(Q)} SET title = ${V}
227
227
  WHERE id = ${J} AND title IS NULL
228
228
  `}})}async removeMessages(J,$){if($.length===0)return;await this.run(async(Q)=>{await Q`
229
229
  DELETE FROM ${this.messages(Q)}
230
230
  WHERE thread_id = ${J} AND ${this.inScope(Q)}
231
- AND id IN (${KJ(Q,[...new Set($)])})
231
+ AND id IN (${GJ(Q,[...new Set($)])})
232
232
  `})}async loadSummaries(J){return this.run(async($)=>{let[Q]=await $`
233
233
  SELECT summaries FROM ${this.threads($)}
234
234
  WHERE id = ${J} AND ${this.inScope($)} AND ${this.live($)}
235
- `;return Q?FZ(Q.summaries):[]})}async saveSummary(J,$){await this.atomically(async(Q)=>{await Q`
235
+ `;return Q?CZ(Q.summaries):[]})}async saveSummary(J,$){await this.atomically(async(Q)=>{await Q`
236
236
  UPDATE ${this.threads(Q)} SET updated_at = updated_at
237
237
  WHERE id = ${J} AND ${this.inScope(Q)}
238
238
  `;let[Z]=await Q`
239
239
  SELECT summaries FROM ${this.threads(Q)}
240
240
  WHERE id = ${J} AND ${this.inScope(Q)} AND ${this.live(Q)}
241
- `;if(!Z)return;let W=CJ(FZ(Z.summaries),$);await Q`
241
+ `;if(!Z)return;let W=OJ(CZ(Z.summaries),$);await Q`
242
242
  UPDATE ${this.threads(Q)} SET summaries = ${JSON.stringify(W)}
243
243
  WHERE id = ${J}
244
244
  `})}async lockSummary(J,$,Q){let Z=`${$}:${crypto.randomUUID()}`;if(!await this.run(async(X)=>{let K=this.clock(X),G=await X`
@@ -246,7 +246,7 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
246
246
  SET summary_lock = ${Z}, summary_lock_until = ${K} + ${this.ms(X,Q)}
247
247
  WHERE id = ${J} AND ${this.inScope(X)} AND ${this.live(X)}
248
248
  AND (summary_lock_until IS NULL OR summary_lock_until <= ${K})
249
- `;return O9(G)>0}))return null;return async()=>{await this.run(async(X)=>{await X`
249
+ `;return L9(G)>0}))return null;return async()=>{await this.run(async(X)=>{await X`
250
250
  UPDATE ${this.threads(X)} SET summary_lock = NULL, summary_lock_until = NULL
251
251
  WHERE id = ${J} AND ${this.inScope(X)} AND summary_lock = ${Z}
252
252
  `})}}async getThread(J){return this.run(async($)=>{let[Q]=await $`
@@ -263,9 +263,9 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
263
263
  SELECT id FROM ${this.threads(Q)} WHERE ${W}
264
264
  ORDER BY expires_at, id
265
265
  LIMIT ${$}
266
- `;if(X.length===0)return{deleted:0};let K=X.map((V)=>String(V.id));await Q`UPDATE ${this.threads(Q)} SET updated_at = updated_at WHERE id IN (${KJ(Q,K)})`;let G=await Q`
267
- SELECT id FROM ${this.threads(Q)} WHERE id IN (${KJ(Q,K)}) AND ${W}
268
- `;if(G.length===0)return{deleted:0};let z=G.map((V)=>String(V.id));return await Q`DELETE FROM ${this.messages(Q)} WHERE thread_id IN (${KJ(Q,z)})`,await Q`DELETE FROM ${this.threads(Q)} WHERE id IN (${KJ(Q,z)})`,{deleted:z.length}})}atomically(J){if(this.guard(),this.joinable())return fJ(this.sql,(K)=>J(K),{connection:this.connection});let $=this.scope,Q=this.options.beginScope,Z=()=>this.sql.begin(async(K)=>{if($!==null&&Q)await Q(K,$);return J(K)});if(this.dialect!=="sqlite")return Z();let X=(DZ.get(this.sql)??Promise.resolve()).then(Z,Z);return DZ.set(this.sql,X.then(()=>{},()=>{})),X}joinable(){if(this.connection===void 0)return;let J=QJ();if(J===void 0||ZJ()!==this.connection)return;return J}run(J){this.guard();let $=this.joinable();if($)return J($);if(this.scope!==null&&this.options.beginScope)return this.atomically(J);return J(this.sql)}guard(){if(this.scope===null&&this.options.requireScope)throw Error("This DatabaseAgentStore requires a scope: call it through store.forScope(scope).")}inScope(J){return this.scope===null?J`1 = 1`:J`scope = ${this.scope}`}live(J){return this.expires?J`(expires_at IS NULL OR expires_at > ${this.clock(J)})`:J`1 = 1`}recordColumns(J){return this.expires?J.unsafe("id, user_id, title, created_at, updated_at, expires_at"):J.unsafe("id, user_id, title, created_at, updated_at")}expiryOf(J){let $=J.ttlMs!==void 0||J.expiresAt!==void 0;if(!this.expires){if($)throw Error("createThread({ ttlMs, expiresAt }) needs a store with `ttlMs`: set `new DatabaseAgentStore(connection, { ttlMs })`, which turns expiry on and reads the expiry columns.");return null}if(J.expiresAt!==void 0){let Z=J.expiresAt instanceof Date?J.expiresAt.getTime():J.expiresAt;if(!Number.isFinite(Z))throw TypeError("createThread: `expiresAt` is not a valid time.");return{at:Z,ttlMs:null,slides:!1}}let Q=J.ttlMs===void 0?this.options.ttlMs:J.ttlMs;if(Q!==null)CZ(Q,"createThread: ttlMs");return{ttlMs:Q,slides:this.options.slidingTtl===!0}}quote(J){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${J}\``:`"${J}"`}threads(J){return J.unsafe(this.quote(this.threadsTable))}messages(J){return J.unsafe(this.quote(this.messagesTable))}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function PZ(J,$){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The agent ${$} table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);return J}function NZ(J){return Error(`Thread ${J} does not exist here, or has been deleted.`)}function KJ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function _9(J){for(let $ of J){if($.role!=="user"||$.event)continue;let Q=$.content.map((Z)=>Z.type==="text"?Z.text:"").join(" ").replace(/\s+/g," ").trim();if(Q)return Q.length>HZ?`${Q.slice(0,HZ-1)}\u2026`:Q}return null}function FZ(J){if(J===null||J===void 0||J==="")return[];let $=JSON.parse(String(J));return Array.isArray($)?$:[]}function UZ(J){return{id:String(J.id),userId:J.user_id===null||J.user_id===void 0?null:String(J.user_id),title:J.title===null||J.title===void 0?null:String(J.title),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),..."expires_at"in J?{expiresAt:J.expires_at===null||J.expires_at===void 0?null:Number(J.expires_at)}:{}}}function CZ(J,$){if(typeof J!=="number"||!Number.isFinite(J)||J<=0)throw TypeError(`${$} must be a positive number of milliseconds.`)}function O9(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function L9(J,$,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
266
+ `;if(X.length===0)return{deleted:0};let K=X.map((V)=>String(V.id));await Q`UPDATE ${this.threads(Q)} SET updated_at = updated_at WHERE id IN (${GJ(Q,K)})`;let G=await Q`
267
+ SELECT id FROM ${this.threads(Q)} WHERE id IN (${GJ(Q,K)}) AND ${W}
268
+ `;if(G.length===0)return{deleted:0};let z=G.map((V)=>String(V.id));return await Q`DELETE FROM ${this.messages(Q)} WHERE thread_id IN (${GJ(Q,z)})`,await Q`DELETE FROM ${this.threads(Q)} WHERE id IN (${GJ(Q,z)})`,{deleted:z.length}})}atomically(J){if(this.guard(),this.joinable())return vJ(this.sql,(K)=>J(K),{connection:this.connection});let $=this.scope,Q=this.options.beginScope,Z=()=>this.sql.begin(async(K)=>{if($!==null&&Q)await Q(K,$);return J(K)});if(this.dialect!=="sqlite")return Z();let X=(HZ.get(this.sql)??Promise.resolve()).then(Z,Z);return HZ.set(this.sql,X.then(()=>{},()=>{})),X}joinable(){if(this.connection===void 0)return;let J=ZJ();if(J===void 0||WJ()!==this.connection)return;return J}run(J){this.guard();let $=this.joinable();if($)return J($);if(this.scope!==null&&this.options.beginScope)return this.atomically(J);return J(this.sql)}guard(){if(this.scope===null&&this.options.requireScope)throw Error("This DatabaseAgentStore requires a scope: call it through store.forScope(scope).")}inScope(J){return this.scope===null?J`1 = 1`:J`scope = ${this.scope}`}live(J){return this.expires?J`(expires_at IS NULL OR expires_at > ${this.clock(J)})`:J`1 = 1`}recordColumns(J){return this.expires?J.unsafe("id, user_id, title, created_at, updated_at, expires_at"):J.unsafe("id, user_id, title, created_at, updated_at")}expiryOf(J){let $=J.ttlMs!==void 0||J.expiresAt!==void 0;if(!this.expires){if($)throw Error("createThread({ ttlMs, expiresAt }) needs a store with `ttlMs`: set `new DatabaseAgentStore(connection, { ttlMs })`, which turns expiry on and reads the expiry columns.");return null}if(J.expiresAt!==void 0){let Z=J.expiresAt instanceof Date?J.expiresAt.getTime():J.expiresAt;if(!Number.isFinite(Z))throw TypeError("createThread: `expiresAt` is not a valid time.");return{at:Z,ttlMs:null,slides:!1}}let Q=J.ttlMs===void 0?this.options.ttlMs:J.ttlMs;if(Q!==null)_Z(Q,"createThread: ttlMs");return{ttlMs:Q,slides:this.options.slidingTtl===!0}}quote(J){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${J}\``:`"${J}"`}threads(J){return J.unsafe(this.quote(this.threadsTable))}messages(J){return J.unsafe(this.quote(this.messagesTable))}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function NZ(J,$){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The agent ${$} table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);return J}function FZ(J){return Error(`Thread ${J} does not exist here, or has been deleted.`)}function GJ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function O9(J){for(let $ of J){if($.role!=="user"||$.event)continue;let Q=$.content.map((Z)=>Z.type==="text"?Z.text:"").join(" ").replace(/\s+/g," ").trim();if(Q)return Q.length>PZ?`${Q.slice(0,PZ-1)}\u2026`:Q}return null}function CZ(J){if(J===null||J===void 0||J==="")return[];let $=JSON.parse(String(J));return Array.isArray($)?$:[]}function UZ(J){return{id:String(J.id),userId:J.user_id===null||J.user_id===void 0?null:String(J.user_id),title:J.title===null||J.title===void 0?null:String(J.title),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),..."expires_at"in J?{expiresAt:J.expires_at===null||J.expires_at===void 0?null:Number(J.expires_at)}:{}}}function _Z(J,$){if(typeof J!=="number"||!Number.isFinite(J)||J<=0)throw TypeError(`${$} must be a positive number of milliseconds.`)}function L9(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function B9(J,$,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
269
269
  \`id\` VARCHAR(191) NOT NULL,
270
270
  \`scope\` VARCHAR(191) NULL,
271
271
  \`user_id\` VARCHAR(191) NULL,
@@ -315,13 +315,13 @@ import{ca as eQ,da as ZZ,ea as WZ,fa as r6,ga as e6,ha as J0,ia as $Q,ja as $0,k
315
315
  "created_at" BIGINT NOT NULL,
316
316
 
317
317
  CONSTRAINT "${Q}_pkey" PRIMARY KEY ("thread_id", "id")
318
- )`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}function B9(J,$,Q){if(J==="mysql"||J==="mariadb")return[[$,[`ALTER TABLE \`${$}\` ADD COLUMN \`scope\` VARCHAR(191) NULL, ADD INDEX \`${$}_scope_user_id_updated_at_idx\`(\`scope\`, \`user_id\`, \`updated_at\`)`]],[Q,[`ALTER TABLE \`${Q}\` ADD COLUMN \`scope\` VARCHAR(191) NULL`]]];return[[$,[`ALTER TABLE "${$}" ADD COLUMN "scope" TEXT`,`CREATE INDEX IF NOT EXISTS "${$}_scope_user_id_updated_at_idx" ON "${$}"("scope", "user_id", "updated_at")`]],[Q,[`ALTER TABLE "${Q}" ADD COLUMN "scope" TEXT`]]]}function M9(J,$){if(J==="mysql"||J==="mariadb")return[`ALTER TABLE \`${$}\` ADD COLUMN \`expires_at\` BIGINT NULL, ADD COLUMN \`ttl_ms\` BIGINT NULL, ADD INDEX \`${$}_expires_at_idx\`(\`expires_at\`)`];return[`ALTER TABLE "${$}" ADD COLUMN "expires_at" BIGINT`,`ALTER TABLE "${$}" ADD COLUMN "ttl_ms" BIGINT`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`]}class GJ extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,$,Q){super(`Frame ${$} of run ${J} has been evicted; the oldest frame still buffered is ${Q}. Reload the thread instead of resuming.`);this.runId=J;this.requested=$;this.oldest=Q}}class _J extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class mJ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;threadRuns=new Map;byClientRun=new Map;constructor(J={}){this.ttlMs=J.ttlMs??60000,this.maxFrames=J.maxFrames??4096,this.maxAgeMs=J.maxAgeMs===void 0?3600000:J.maxAgeMs}register(J,$={}){let Q={run:J,threadId:$.threadId,startedAt:Date.now(),owner:$.owner??null,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(J.runId,Q),$.threadId){this.byThread.set($.threadId,J.runId);let Z=this.threadRuns.get($.threadId);if(!Z)Z=new Set,this.threadRuns.set($.threadId,Z);Z.add(J.runId)}if($.clientRunId)this.byClientRun.set($.clientRunId,J.runId);return this.scheduleExpiry(Q,$.maxRunDurationMs),this.pump(Q,$)}findByClientRunId(J){let $=this.byClientRun.get(J);return $&&this.runs.has($)?$:null}async find(J){let $=this.byThread.get(J.threadId);if(!$)return null;let Q=this.runs.get($);if(!Q)return null;return{runId:$,seq:Q.lastSeq}}running(J){let $=[];for(let Q of this.threadRuns.get(J.threadId)??[]){let Z=this.runs.get(Q);if(!Z||Z.ended||Z.evicted)continue;$.push({runId:Q,seq:Z.lastSeq,startedAt:Z.startedAt})}return $}threadOf(J){return this.runs.get(J)?.threadId}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,$){let Q=this.ownerOf(J);return Q===null||Q===$}isRunning(J){let $=this.runs.get(J);return!!$&&!$.ended&&!$.evicted}replay(J,$){let Q=this.runs.get(J);if(!Q)throw new _J(J);if($!==void 0&&$<Q.lostBefore)throw new GJ(J,$,Q.lostBefore);let Z=Q.frames[0]?.seq;return this.drain(Q,J,$??Z??Q.lastSeq+1)}clear(){for(let J of this.runs.values()){if(J.evictAt)clearTimeout(J.evictAt);if(J.expireAt)clearTimeout(J.expireAt);J.ended=!0,this.notify(J)}this.runs.clear(),this.byThread.clear(),this.threadRuns.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(J,$){let Q=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let X=$.onEvent;if(X)Q=Q.then(()=>X(Z.event)).catch((K)=>k$($,K));continue}if(J.frames.push(Z),J.lastSeq=Z.seq,J.frames.length>this.maxFrames){let X=J.frames.shift();if(X)J.lostBefore=X.seq+1}this.notify(J);let W=$.onEvent;if(W)Q=Q.then(()=>W(Z.event)).catch((X)=>k$($,X))}}catch(Z){k$($,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await Q}}async*drain(J,$,Q){let Z=Q;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new GJ($,Z,J.lostBefore);let X=J.frames,K=X[0]?.seq;if(K===void 0)break;let G=Math.max(0,Z-K);if(G>=X.length)break;let z=X[G];yield z,Z=z.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,$){if(J.version!==$)return Promise.resolve();return new Promise((Q)=>J.wake.add(Q))}notify(J){J.version++;let $=Array.from(J.wake);J.wake.clear();for(let Q of $)Q()}scheduleEviction(J){if(J.evictAt)return;let $=setTimeout(()=>{let Q=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get(Q)===J)this.runs.delete(Q);if(J.threadId&&this.byThread.get(J.threadId)===Q)this.byThread.delete(J.threadId);if(J.threadId){let Z=this.threadRuns.get(J.threadId);if(Z?.delete(Q),Z?.size===0)this.threadRuns.delete(J.threadId)}if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===Q)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);$.unref?.(),J.evictAt=$}scheduleExpiry(J,$){if(this.maxAgeMs===null||$===null)return;let Q=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Q)||Q>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round(Q/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},Q);Z.unref?.(),J.expireAt=Z}}var T$=new mJ;function k$(J,$){try{J.onInternalError?.($)}catch{}}class pJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,$){if(this.records.has(J))return;this.records.set(J,{...$});while(this.records.size>this.maxEntries){let Q=this.records.keys().next().value;if(Q===void 0)break;this.records.delete(Q)}}async get(J){let $=this.records.get(J);return $?{...$}:null}async delete(J){this.records.delete(J)}async expired(J,$){let Q=[];for(let[Z,W]of this.records){if(Q.length>=$)break;if(W.expiresAt&&Date.parse(W.expiresAt)<=J.getTime())Q.push(Z)}return Q}}var j$=new pJ;class w${now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,$){let Q=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Q);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>Q)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:$}),{status:"claimed"}}async complete(J,$,Q){this.receipts.set(J,{result:structuredClone($),expiresAt:Q})}async release(J){let $=this.receipts.get(J);if($&&!$.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[$,Q]of this.receipts)if(Q.expiresAt<=J)this.receipts.delete($);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var _Z="pending",x$="done:",S9=`
318
+ )`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}function S9(J,$,Q){if(J==="mysql"||J==="mariadb")return[[$,[`ALTER TABLE \`${$}\` ADD COLUMN \`scope\` VARCHAR(191) NULL, ADD INDEX \`${$}_scope_user_id_updated_at_idx\`(\`scope\`, \`user_id\`, \`updated_at\`)`]],[Q,[`ALTER TABLE \`${Q}\` ADD COLUMN \`scope\` VARCHAR(191) NULL`]]];return[[$,[`ALTER TABLE "${$}" ADD COLUMN "scope" TEXT`,`CREATE INDEX IF NOT EXISTS "${$}_scope_user_id_updated_at_idx" ON "${$}"("scope", "user_id", "updated_at")`]],[Q,[`ALTER TABLE "${Q}" ADD COLUMN "scope" TEXT`]]]}function M9(J,$){if(J==="mysql"||J==="mariadb")return[`ALTER TABLE \`${$}\` ADD COLUMN \`expires_at\` BIGINT NULL, ADD COLUMN \`ttl_ms\` BIGINT NULL, ADD INDEX \`${$}_expires_at_idx\`(\`expires_at\`)`];return[`ALTER TABLE "${$}" ADD COLUMN "expires_at" BIGINT`,`ALTER TABLE "${$}" ADD COLUMN "ttl_ms" BIGINT`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`]}class VJ extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,$,Q){super(`Frame ${$} of run ${J} has been evicted; the oldest frame still buffered is ${Q}. Reload the thread instead of resuming.`);this.runId=J;this.requested=$;this.oldest=Q}}class LJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class iJ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;threadRuns=new Map;byClientRun=new Map;constructor(J={}){this.ttlMs=J.ttlMs??60000,this.maxFrames=J.maxFrames??4096,this.maxAgeMs=J.maxAgeMs===void 0?3600000:J.maxAgeMs}register(J,$={}){let Q={run:J,threadId:$.threadId,startedAt:Date.now(),owner:$.owner??null,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(J.runId,Q),$.threadId){this.byThread.set($.threadId,J.runId);let Z=this.threadRuns.get($.threadId);if(!Z)Z=new Set,this.threadRuns.set($.threadId,Z);Z.add(J.runId)}if($.clientRunId)this.byClientRun.set($.clientRunId,J.runId);return this.scheduleExpiry(Q,$.maxRunDurationMs),this.pump(Q,$)}findByClientRunId(J){let $=this.byClientRun.get(J);return $&&this.runs.has($)?$:null}async find(J){let $=this.byThread.get(J.threadId);if(!$)return null;let Q=this.runs.get($);if(!Q)return null;return{runId:$,seq:Q.lastSeq}}running(J){let $=[];for(let Q of this.threadRuns.get(J.threadId)??[]){let Z=this.runs.get(Q);if(!Z||Z.ended||Z.evicted)continue;$.push({runId:Q,seq:Z.lastSeq,startedAt:Z.startedAt})}return $}threadOf(J){return this.runs.get(J)?.threadId}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,$){let Q=this.ownerOf(J);return Q===null||Q===$}isRunning(J){let $=this.runs.get(J);return!!$&&!$.ended&&!$.evicted}replay(J,$){let Q=this.runs.get(J);if(!Q)throw new LJ(J);if($!==void 0&&$<Q.lostBefore)throw new VJ(J,$,Q.lostBefore);let Z=Q.frames[0]?.seq;return this.drain(Q,J,$??Z??Q.lastSeq+1)}clear(){for(let J of this.runs.values()){if(J.evictAt)clearTimeout(J.evictAt);if(J.expireAt)clearTimeout(J.expireAt);J.ended=!0,this.notify(J)}this.runs.clear(),this.byThread.clear(),this.threadRuns.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(J,$){let Q=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let X=$.onEvent;if(X)Q=Q.then(()=>X(Z.event)).catch((K)=>x$($,K));continue}if(J.frames.push(Z),J.lastSeq=Z.seq,J.frames.length>this.maxFrames){let X=J.frames.shift();if(X)J.lostBefore=X.seq+1}this.notify(J);let W=$.onEvent;if(W)Q=Q.then(()=>W(Z.event)).catch((X)=>x$($,X))}}catch(Z){x$($,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await Q}}async*drain(J,$,Q){let Z=Q;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new VJ($,Z,J.lostBefore);let X=J.frames,K=X[0]?.seq;if(K===void 0)break;let G=Math.max(0,Z-K);if(G>=X.length)break;let z=X[G];yield z,Z=z.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,$){if(J.version!==$)return Promise.resolve();return new Promise((Q)=>J.wake.add(Q))}notify(J){J.version++;let $=Array.from(J.wake);J.wake.clear();for(let Q of $)Q()}scheduleEviction(J){if(J.evictAt)return;let $=setTimeout(()=>{let Q=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get(Q)===J)this.runs.delete(Q);if(J.threadId&&this.byThread.get(J.threadId)===Q)this.byThread.delete(J.threadId);if(J.threadId){let Z=this.threadRuns.get(J.threadId);if(Z?.delete(Q),Z?.size===0)this.threadRuns.delete(J.threadId)}if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===Q)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);$.unref?.(),J.evictAt=$}scheduleExpiry(J,$){if(this.maxAgeMs===null||$===null)return;let Q=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Q)||Q>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round(Q/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},Q);Z.unref?.(),J.expireAt=Z}}var I$=new iJ;function x$(J,$){try{J.onInternalError?.($)}catch{}}class dJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,$){if(this.records.has(J))return;this.records.set(J,{...$});while(this.records.size>this.maxEntries){let Q=this.records.keys().next().value;if(Q===void 0)break;this.records.delete(Q)}}async get(J){let $=this.records.get(J);return $?{...$}:null}async delete(J){this.records.delete(J)}async expired(J,$){let Q=[];for(let[Z,W]of this.records){if(Q.length>=$)break;if(W.expiresAt&&Date.parse(W.expiresAt)<=J.getTime())Q.push(Z)}return Q}}var w$=new dJ;class b${now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,$){let Q=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Q);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>Q)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:$}),{status:"claimed"}}async complete(J,$,Q){this.receipts.set(J,{result:structuredClone($),expiresAt:Q})}async release(J){let $=this.receipts.get(J);if($&&!$.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[$,Q]of this.receipts)if(Q.expiresAt<=J)this.receipts.delete($);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var OZ="pending",f$="done:",A9=`
319
319
  if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
320
320
  local held = redis.call('GET', KEYS[1])
321
321
  if not held then return ARGV[1] end
322
- return held`,A9=`
322
+ return held`,R9=`
323
323
  if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
324
- return 0`;class f${injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,$){let Q=await this.client.send("EVAL",[S9,"1",this.key(J),_Z,OZ($)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(x$))return{status:"replay",result:JSON.parse(Z.slice(x$.length))};return{status:"blocked"}}async complete(J,$,Q){await this.client.send("SET",[this.key(J),x$+JSON.stringify($),"PX",OZ(Q)])}async release(J){await this.client.send("EVAL",[A9,"1",this.key(J),_Z])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=LZ(),$=J.bound(I$)?J.make(I$).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function OZ(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var R9=86400000,E9=60000;class OJ{ttlMs;slidingTtl;clientOwnedIds;scope=null;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??R9,this.slidingTtl=J.slidingTtl??!0,this.clientOwnedIds=J.clientOwnedIds??!1}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A MemoryAgentStore scope is a non-empty string.");let $=new OJ({ttlMs:this.ttlMs,slidingTtl:this.slidingTtl,clientOwnedIds:this.clientOwnedIds});return $.threads=this.threads,$.scope=J,$}visible(J,$=Date.now()){let Q=this.threads.get(J);if(Q&&q$(Q,$)){this.threads.delete(J);return}if(!Q||this.scope===null||Q.scope===this.scope)return Q;return}fresh(J={}){let $=Date.now(),Q,Z=null;if(J.expiresAt!==void 0){if(Q=J.expiresAt instanceof Date?J.expiresAt.getTime():J.expiresAt,!Number.isFinite(Q))throw TypeError("createThread: `expiresAt` is not a valid time.")}else{let W=J.ttlMs===void 0?this.ttlMs:J.ttlMs;if(W!==null&&!(typeof W==="number"&&W>0))throw TypeError("createThread: ttlMs must be a positive number of milliseconds.");Q=W===null?null:$+W,Z=this.slidingTtl?W:null}return{messages:[],expiresAt:Q,slideMs:Z,...this.scope!==null?{scope:this.scope}:{}}}touch(J){if(J.slideMs!==null)J.expiresAt=Date.now()+J.slideMs}async createThread(J={}){let $=crypto.randomUUID();return this.threads.set($,this.fresh(J)),this.sweep(),{threadId:$}}async loadThread(J){this.sweep();let $=this.visible(J);if(!$){if(this.threads.has(J))return null;return this.clientOwnedIds?[]:null}return this.touch($),$.messages.slice()}async appendMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q){if(!this.clientOwnedIds||this.threads.has(J))throw Error(`Thread ${J} does not exist here, or has expired.`);Q=this.fresh(),this.threads.set(J,Q)}for(let Z of $){let W=JSON.parse(JSON.stringify(Z)),X=Q.messages.findIndex((K)=>K.id===W.id);if(X===-1)Q.messages.push(W);else Q.messages[X]=W}this.touch(Q)}async removeMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q)return;let Z=new Set($);Q.messages=Q.messages.filter((W)=>!Z.has(W.id)),this.touch(Q)}async loadSummaries(J){return this.visible(J)?.summaries?.slice()??[]}async saveSummary(J,$){let Q=this.visible(J);if(!Q)return;Q.summaries=CJ(Q.summaries??[],$)}delete(J){if(this.visible(J))this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<E9)return;this.lastSweep=J;for(let[$,Q]of this.threads)if(q$(Q,J))this.threads.delete($)}async sweepExpired(J={}){let $=J.now??Date.now(),Q=Math.max(0,Math.floor(J.limit??500)),Z=0;for(let[W,X]of this.threads){if(Q===0)break;if(this.scope!==null&&X.scope!==this.scope)continue;if(q$(X,$))this.threads.delete(W),Z+=1,Q-=1}return{deleted:Z}}}function q$(J,$){return J.expiresAt!==null&&$>=J.expiresAt}var b$=new OJ;class BZ{buffer="";textDecoder=new TextDecoder;pendingCR=!1;lastSeq=-1;get cursor(){return this.lastSeq}push(J){return this.append(typeof J==="string"?J:this.textDecoder.decode(J,{stream:!0})),this.drain()}flush(){this.append(this.textDecoder.decode());let J=this.drain();return this.buffer="",this.pendingCR=!1,J}append(J){if(J==="")return;let $=J;if(this.pendingCR){if(this.buffer+=`
324
+ return 0`;class v${injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,$){let Q=await this.client.send("EVAL",[A9,"1",this.key(J),OZ,LZ($)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(f$))return{status:"replay",result:JSON.parse(Z.slice(f$.length))};return{status:"blocked"}}async complete(J,$,Q){await this.client.send("SET",[this.key(J),f$+JSON.stringify($),"PX",LZ(Q)])}async release(J){await this.client.send("EVAL",[R9,"1",this.key(J),OZ])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=BZ(),$=J.bound(q$)?J.make(q$).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function LZ(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var E9=86400000,k9=60000;class BJ{ttlMs;slidingTtl;clientOwnedIds;scope=null;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??E9,this.slidingTtl=J.slidingTtl??!0,this.clientOwnedIds=J.clientOwnedIds??!1}forScope(J){if(typeof J!=="string"||J==="")throw TypeError("A MemoryAgentStore scope is a non-empty string.");let $=new BJ({ttlMs:this.ttlMs,slidingTtl:this.slidingTtl,clientOwnedIds:this.clientOwnedIds});return $.threads=this.threads,$.scope=J,$}visible(J,$=Date.now()){let Q=this.threads.get(J);if(Q&&y$(Q,$)){this.threads.delete(J);return}if(!Q||this.scope===null||Q.scope===this.scope)return Q;return}fresh(J={}){let $=Date.now(),Q,Z=null;if(J.expiresAt!==void 0){if(Q=J.expiresAt instanceof Date?J.expiresAt.getTime():J.expiresAt,!Number.isFinite(Q))throw TypeError("createThread: `expiresAt` is not a valid time.")}else{let W=J.ttlMs===void 0?this.ttlMs:J.ttlMs;if(W!==null&&!(typeof W==="number"&&W>0))throw TypeError("createThread: ttlMs must be a positive number of milliseconds.");Q=W===null?null:$+W,Z=this.slidingTtl?W:null}return{messages:[],expiresAt:Q,slideMs:Z,...this.scope!==null?{scope:this.scope}:{}}}touch(J){if(J.slideMs!==null)J.expiresAt=Date.now()+J.slideMs}async createThread(J={}){let $=crypto.randomUUID();return this.threads.set($,this.fresh(J)),this.sweep(),{threadId:$}}async loadThread(J){this.sweep();let $=this.visible(J);if(!$){if(this.threads.has(J))return null;return this.clientOwnedIds?[]:null}return this.touch($),$.messages.slice()}async appendMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q){if(!this.clientOwnedIds||this.threads.has(J))throw Error(`Thread ${J} does not exist here, or has expired.`);Q=this.fresh(),this.threads.set(J,Q)}for(let Z of $){let W=JSON.parse(JSON.stringify(Z)),X=Q.messages.findIndex((K)=>K.id===W.id);if(X===-1)Q.messages.push(W);else Q.messages[X]=W}this.touch(Q)}async removeMessages(J,$){this.sweep();let Q=this.visible(J);if(!Q)return;let Z=new Set($);Q.messages=Q.messages.filter((W)=>!Z.has(W.id)),this.touch(Q)}async loadSummaries(J){return this.visible(J)?.summaries?.slice()??[]}async saveSummary(J,$){let Q=this.visible(J);if(!Q)return;Q.summaries=OJ(Q.summaries??[],$)}delete(J){if(this.visible(J))this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<k9)return;this.lastSweep=J;for(let[$,Q]of this.threads)if(y$(Q,J))this.threads.delete($)}async sweepExpired(J={}){let $=J.now??Date.now(),Q=Math.max(0,Math.floor(J.limit??500)),Z=0;for(let[W,X]of this.threads){if(Q===0)break;if(this.scope!==null&&X.scope!==this.scope)continue;if(y$(X,$))this.threads.delete(W),Z+=1,Q-=1}return{deleted:Z}}}function y$(J,$){return J.expiresAt!==null&&$>=J.expiresAt}var h$=new BJ;class SZ{buffer="";textDecoder=new TextDecoder;pendingCR=!1;lastSeq=-1;get cursor(){return this.lastSeq}push(J){return this.append(typeof J==="string"?J:this.textDecoder.decode(J,{stream:!0})),this.drain()}flush(){this.append(this.textDecoder.decode());let J=this.drain();return this.buffer="",this.pendingCR=!1,J}append(J){if(J==="")return;let $=J;if(this.pendingCR){if(this.buffer+=`
325
325
  `,this.pendingCR=!1,$.startsWith(`
326
326
  `))$=$.slice(1)}if($.endsWith("\r"))$=$.slice(0,-1),this.pendingCR=!0;this.buffer+=$.replace(/\r\n/g,`
327
327
  `).replace(/\r/g,`
@@ -331,8 +331,8 @@ return 0`;class f${injectedClient;prefix;constructor(J={}){this.injectedClient=J
331
331
 
332
332
  `)}return J}parse(J){let $,Q=[];for(let K of J.split(`
333
333
  `)){if(K===""||K.startsWith(":"))continue;let G=K.indexOf(":"),z=G===-1?K:K.slice(0,G),V=G===-1?"":K.slice(G+1);if(V.startsWith(" "))V=V.slice(1);if(z==="data")Q.push(V);else if(z==="id")$=V}if(Q.length===0)return null;let Z;try{Z=JSON.parse(Q.join(`
334
- `))}catch{return null}let W=$===void 0||$===""?Number.NaN:Number($),X=Number.isFinite(W)?W:this.lastSeq+1;return this.lastSeq=X,{seq:X,event:Z}}}async function*MZ(J){if(!J)return;let $=J.getReader(),Q=new BZ;try{while(!0){let{done:Z,value:W}=await $.read();if(Z){yield*Q.flush();return}if(W)yield*Q.push(W)}}finally{try{await $.cancel()}catch{}}}function EZ(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 k9(J){let $=new Map;for(let Q of J)for(let Z of Q.content)if(Z.type==="tool-call")$.set(Z.toolCallId,Q.turn);return $}var T9=(J)=>J.path?.[0]??J.toolCallId;function j9(J,$,Q){if($.length===0)return[];let Z=k9(J),W=(G)=>G.turn??Z.get(T9(G)),X=new Set(Q.map(W));if(X.has(void 0)||X.size===0)return[];let K=new Set(Q.map((G)=>G.toolCallId));return $.filter((G)=>{let z=W(G);return z!==void 0&&!X.has(z)&&!K.has(G.toolCallId)})}function kZ(J,$,Q=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==J.cursorRunId)&&$.seq<=J.seq)return J;return{...TZ(J,$.event,Q),seq:$.seq}}function TZ(J,$,Q){switch($.type){case"run-start":return{...J,messages:x9(J.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return u(J,$.messageId,Q,(Z)=>({...Z,role:$.role,...$.turn&&Z.turn===void 0?{turn:$.turn}:{}}));case"text-delta":if(AZ(J,$.messageId))return J;return u(J,$.messageId,Q,(Z)=>({...Z,content:b9(Z.content,$.delta)}));case"reasoning-delta":if(AZ(J,$.messageId))return J;return u(J,$.messageId,Q,(Z)=>({...Z,content:v9(Z.content,$.delta,$.id,$.providerMetadata)}));case"output-delta":return u(J,$.messageId,Q,(Z)=>({...Z,content:RZ(Z.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return u(J,$.messageId,Q,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===$.part.toolCallId),X=W===-1?void 0:Z.content[W],K=$.part.progress??X?.progress,G=$.part.nested??X?.nested,z=$.part.attachments??X?.attachments,V={...$.part,...K?{progress:K}:{},...G?{nested:G}:{},...z?{attachments:z}:{}},Y=Z.content.slice();if(W===-1)Y.push(V);else Y[W]=V;return{...Z,content:Y}});case"tool-call-discard":return u(J,$.messageId,Q,(Z)=>{let W=Z.content.filter((X)=>!(X.type==="tool-call"&&X.partial&&$.toolCallIds.includes(X.toolCallId)));return W.length===Z.content.length?Z:{...Z,content:W}});case"tool-search":{let Z=$.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return SZ(J,$.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],$.data]}));case"nested-event":{let Z=$;return SZ(J,$.toolCallId,(W)=>{let X=W.nested??[],K=X.findIndex((Y)=>Y.runId===Z.runId),G=X[K]??{runId:Z.runId,agent:Z.agent,messages:[]},z=f9(G,Z,Q),V=K===-1?[...X,z]:X.map((Y,D)=>D===K?z:Y);return{...W,nested:V}})}case"tool-result":{let Z=u(J,$.messageId,Q,(W)=>({...W,content:RZ(W.content,$.part,(X)=>X.type==="tool-result"&&X.toolCallId===$.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((K)=>K.id===$.message.id),W=J.messages.slice();if(Z===-1)W.push($.message);else W[Z]=$.message;let X=J.runMessageIds.includes($.message.id)?J.runMessageIds:[...J.runMessageIds,$.message.id];return{...J,messages:W,runMessageIds:X}}case"message-id":{let Z=J.messages.findIndex((G)=>G.id===$.localId);if(Z===-1){if(!$.message||J.messages.some((G)=>G.id===$.messageId))return J;return{...J,messages:[...J.messages,$.message]}}let W=J.messages[Z],X={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},K=J.messages.some((G)=>G.id===$.messageId)?J.messages.filter((G,z)=>z!==Z).map((G)=>G.id===$.messageId?{...G,...X}:G):J.messages.map((G,z)=>z===Z?{...G,...X,id:$.messageId}:G);return{...J,messages:K}}case"awaiting-input":return{...J,runId:$.runId,pending:[...j9(J.messages,J.pending,$.pending),...$.pending]};case"message-end":return u(J,$.messageId,Q,(Z)=>({...Z,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...J,usage:$.usage};case"retry":return J;case"error":return{...J,error:$.error,pending:J.pending.filter((Z)=>Z.turn!==void 0)};case"run-end":return{...J,runId:void 0,finishReason:$.finishReason,messages:jZ(J,$.finishReason)};default:return J}}function x9(J,$){if(!J.some((Q)=>Q.runId===$&&Q.finishReason===void 0))return J;return J.map((Q)=>{if(Q.runId!==$||Q.finishReason!==void 0)return Q;let{runId:Z,...W}=Q;return{...W,content:[]}})}function jZ(J,$){return J.messages.map((Q)=>Q.role==="assistant"&&J.runMessageIds.includes(Q.id)?I9(Q,$):Q)}function I9(J,$){let Q=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((X)=>X.finishReason===void 0)?{...W,nested:W.nested.map((X)=>X.finishReason===void 0?w9(X,$):X)}:W);if(J.finishReason===void 0)return{...J,finishReason:$,content:Q};return Q.some((W,X)=>W!==J.content[X])?{...J,content:Q}:J}function w9(J,$){let Q={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:$,messages:jZ(Q,$)}}function SZ(J,$,Q){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],X=W.content.findIndex((V)=>V.type==="tool-call"&&V.toolCallId===$);if(X===-1)continue;if(W.finishReason!==void 0&&!q9(J,W,$))return J;let K=W.content.slice();K[X]=Q(K[X]);let G=J.messages.slice();G[Z]={...W,content:K};let z=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:z,messages:G}}return J}function f9(J,$,Q){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((X)=>X.id),loadedTools:[],finishReason:J.finishReason},W=TZ(Z,$.event,Q);return{...J,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function q9(J,$,Q){if($.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Q))}function AZ(J,$){let Q=J.messages.find((Z)=>Z.id===$);return Q!==void 0&&Q.finishReason!==void 0}function u(J,$,Q,Z){let W=J.messages.findIndex((G)=>G.id===$),X=J.runMessageIds.includes($)?J.runMessageIds:[...J.runMessageIds,$];if(W===-1){let G={id:$,role:"assistant",content:[],createdAt:Q};return{...J,runMessageIds:X,messages:[...J.messages,Z(G)]}}let K=J.messages.slice();return K[W]=Z(K[W]),{...J,runMessageIds:X,messages:K}}function b9(J,$){let Q=J[J.length-1];if(Q&&Q.type==="text")return[...J.slice(0,-1),{type:"text",text:Q.text+$}];return[...J,{type:"text",text:$}]}function v9(J,$,Q,Z){let W=J[J.length-1];if(W&&W.type==="reasoning"&&W.id===Q&&!W.providerMetadata)return[...J.slice(0,-1),{...W,text:(W.text??"")+$,...Z?{providerMetadata:Z}:{}}];return[...J,{type:"reasoning",...Q?{id:Q}:{},text:$,...Z?{providerMetadata:Z}:{}}]}function RZ(J,$,Q){let Z=J.findIndex(Q);if(Z===-1)return[...J,$];let W=J.slice();return W[Z]=$,W}class y${store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,$,Q,Z){this.store=J;this.threadId=$;this.report=Z;this.state=EZ({messages:Q})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[v$(J)])}frame(J){if(this.closed)return;let $=J.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=kZ(this.state,J),$.type){case"message":this.write(()=>[v$($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let $ of J)this.done.add($.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let $=this.state.messages.find((Z)=>Z.id===J);if(!$)return;let Q=this.runId;this.write(()=>{let Z=v$($);if(Z.finishReason===void 0&&Q)Z.runId=Q;return[Z]})}write(J){let $;try{$=J()}catch(Q){this.report(Q);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Q)=>this.report(Q))}}function v$(J){return structuredClone(J)}async function xZ(J,$){let Q=[],Z=null,W=J.slice();for(let X=0;X<W.length;X++){let K=W[X];if(K.role!=="assistant"||K.finishReason!==void 0)continue;if(K.runId&&await $(K.runId))continue;Z??=new Set(J.flatMap((V)=>V.content.flatMap((Y)=>Y.type==="tool-result"?[Y.toolCallId]:[])));let G=K.content.map((V)=>V.type==="tool-call"?IZ(V):V);for(let V of K.content){if(V.type!=="tool-call"||Z.has(V.toolCallId))continue;let Y={type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"interrupted"};G.push(Y)}let z={...K,content:G,finishReason:"interrupted"};W[X]=z,Q.push(z)}return{messages:W,settled:Q}}function IZ(J){let{partial:$,...Q}=J;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(y9)}}function y9(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Q)=>Q.type==="tool-call"?IZ(Q):Q)}:$)}}var h9=50,g9=["waiting","running","ok","error"];async function qZ(J,$){let{store:Q,threadId:Z}=$,W=Math.max(h9,$.scan??0),X=await Q.listForThread(Z,{limit:W}),K,G=async(H)=>{if(H.state!=="running")return H;if(K??=await wZ(Q),H.deadlineAt>K)return H;return await fZ(Q,H),await Q.get(H.id)??H};for(let H=0;H<X.length;H++)X[H]=await G(X[H]);let z=new Map(X.map((H)=>[H.id,H])),V=J.slice(),Y=[],D=new Set;for(let H=0;H<V.length;H++){let C=V[H],_=null;for(let P=0;P<C.content.length;P++){let U=C.content[P];if(U.type==="tool-call")D.add(U.toolCallId);if(U.type!=="tool-result"||U.status!=="running")continue;let F=U.job?.id,O=F?z.get(F):void 0;if(F&&O===void 0){let A=await Q.get(F);if(O=A?await G(A):void 0,O)z.set(F,O)}if(O&&!g(O.state))continue;_??=C.content.slice(),_[P]=c9(U,O,$.outputSchemaFor,$.modelOutputFor)}if(_){let P={...C,content:_};V[H]=P,Y.push(P)}}let N=[];for(let H of X){if(H.orphaned||H.toolCallId===""||D.has(H.toolCallId))continue;if(await $.isRunLive(H.runId))continue;N.push(H)}return{messages:V,settled:Y,orphans:N,jobs:X}}async function bZ(J,$,Q){for(let Z of $)try{await J.transition(Z.id,g9,{orphaned:!0})}catch(W){Q(W)}}function c9(J,$,Q,Z){let W={type:"tool-result",toolCallId:J.toolCallId,name:J.name},X=(z,V)=>{let Y=Z?.(String(J.name),z);return{...W,status:"ok",job:V,output:z,...Y!==void 0?{modelOutput:Y}:{}}};if(!$)return{...W,status:"error",job:J.job,error:{code:"tool_error",message:`The background job for "${String(J.name)}" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,toolCallId:J.toolCallId,retryable:!0}};let K={id:$.id,...$.summary!==void 0?{summary:$.summary}:{},...$.usage?{usage:$.usage}:{}};if($.state==="error")return{...W,status:"error",job:K,error:$.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let G=Q?.(String(J.name));if(G){let z=G.safeParse($.output);if(z.ok===!1)return{...W,status:"error",job:K,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: ${z.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return X(z.value,K)}return X($.output,K)}var u9=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;class zJ extends Error{status;code;kind;constructor(J,$){super(J);this.name="AgentTurnError",this.status=$.status,this.code=$.code,this.kind=$.kind}static async from(J){let $={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")$=Z.error}catch{}let Q=(Z)=>typeof $[Z]==="string"?$[Z]:void 0;return new zJ(Q("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:Q("code"),kind:Q("kind")})}}function m9(J){for(let $=J.length-1;$>=0;$--){let Q=J[$];if(Q.role!=="assistant")continue;return Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}function i$(J,$,Q,Z=!1){let W=[],X=(async()=>{for await(let G of $)if(G.type==="awaiting-input")W=G.pending})().catch(k),K;return{runId:$.runId,threadId:J,run:$,joined:Z,stop:(G)=>AJ($,G),result:()=>K??=(async()=>{let G=await $.result();await Promise.all([Q,X]);let z=G.messages;return{...G,threadId:J,text:m9(z),pending:G.finishReason==="awaiting-input"?W:[]}})()}}function p9(J,$){let Q=i$(J,$.run,t.get($.run)??$.run.result().then(k,k),!0),Z;return{...Q,stop:(W)=>{AJ($.run,W),$.answer.then((X)=>{if("run"in X)AJ(X.run,W)},k)},result:()=>Z??=(async()=>{let W=await $.answer;if(W.kind==="refused")throw await Q.result(),W.error;if(W.kind==="dropped"||W.run===$.run)return Q.result();return i$(J,W.run,W.hooks).result()})()}}var vZ=["supersede","queue","join","parallel","skip"];function l9(J,$){if($)return{event:{name:$.name,...$.text!==void 0?{text:$.text}:{},...$.data!==void 0?{data:$.data}:{}}};if(!J||J.toolResults&&J.toolResults.length>0)return null;if(!J.text&&!(J.files&&J.files.length>0))return null;return{...J.text?{text:J.text}:{},...J.files&&J.files.length>0?{files:J.files}:{},...J.localId?{localId:J.localId}:{}}}function yZ(J){if(!J)return{};let $="event"in J?J.event:void 0,Q=$?$.text:J.text;return{...Q?{text:Q}:{},...!$&&J.files&&J.files.length>0?{files:J.files}:{},...$?{event:{name:$.name}}:{}}}var i9=["supersede","queue","join","parallel"],d9=X8,LJ=new Map,t=new WeakMap,y=new WeakMap,hZ=new WeakMap,gZ=new WeakMap;function n9(J){return J.headers.get("Content-Type")?.startsWith("text/event-stream")??!1}var h$=new WeakMap,g$=new WeakMap,cZ=new WeakMap,uZ=new WeakMap,c$={parallel:!1},o9=5000,mZ=new WeakMap,u$=new WeakMap,pZ=new WeakMap,d$=new WeakSet;function AJ(J,$){d$.add(J),J.stop($)}function lZ(J,$){let Q=mZ.get(J);if(Q)return Q;let Z=(async()=>{for await(let X of J.frames()){let K=X.event.type;if(K==="message-start"||K==="awaiting-input"||K==="run-end")return}})().catch(k),W={done:!1,promise:Promise.resolve()};return W.promise=Promise.race([Z,J.result().then(k,k)]).then(()=>$?.settled()).then(k,k).then(()=>{W.done=!0}),mZ.set(J,W),W}var BJ=new WeakMap,R8="thread_busy",iZ="http://gemi.internal/__gemi/agent-turn",lJ=new Map,s9=4194304,a9=1000,t9=5;function r9(J){let{max:$,overflow:Q}=typeof J==="number"?{max:J,overflow:"reject"}:J??{};if(!($===1/0||Number.isInteger($)&&$>0)||Q!=="queue"&&Q!=="reject")throw TypeError(`AgentController.maxThreadRuns answers a positive whole number (or Infinity), or { max, overflow: "queue" | "reject" }; got ${JSON.stringify(J)}.`);return{max:$,overflow:Q}}var e9=3,MJ=65536,k=()=>{};class E8{byKey=new Map;take(J,$,Q){let Z=this.byKey.get(J);if(!Z?.has($)&&(Z?.size??0)>=Q)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set($,(Z.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let X=this.byKey.get(J),K=(X?.get($)??1)-1;if(!X)return;if(K>0)X.set($,K);else if(X.delete($),X.size===0)this.byKey.delete(J)}}}var dZ=new WeakMap,n$=new WeakMap;function J6(J){let $=n$.get(J);if(!$)$=new Map,n$.set(J,$);return $}function $6(J,$,Q){let Z=n$.get(J)?.get($);if(!Z)return;for(let W of[...Z])try{W(Q)}catch{}}function nZ(J){let $=dZ.get(J);if(!$)$=new E8,dZ.set(J,$);return $}function Q6(J){return J}class oJ extends d9{static kind="agent-controller";hooks;store=b$;storeScope(J,$){return null}boundScope=void 0;async threadInScope(J,$){if(await this.scopeStore(J,{}),this.boundScope===null)return!0;return await this.store.loadThread($)!==null}async scopeStore(J,$){let Z=hZ.get(J)??await this.storeScope(J,{body:$})??null;if(this.boundScope!==void 0){if(this.boundScope!==Z)throw Error("This AgentController instance already served a request in another store scope. Build a controller per request (the router and startTurn do).");return}if(Z!==null)this.store=Z8(this.store,Z);this.boundScope=Z}liveRuns=T$;voice;voiceStore=R$;attachments=rJ;attachmentStorage=V8;turnAttachmentMaxAgeMs=3600000;fileOwners=j$;nonces=r$;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,$){return this.hooks?.instructions?.(J,$)}reasoning(J,$){return this.hooks?.reasoning?.(J,$)}skills(J,$){return this.hooks?.skills?.(J,$)}runTools(J,$){return this.hooks?.runTools?.(J,$)}trailingContext(J,$){return this.hooks?.trailingContext?.(J,$)}usageLimits(J,$){return this.hooks?.usageLimits?.(J,$)}context(J,$){let Q=this.hooks?.context;if(Q)return Q(J,$);return{}}memoryScopes(J,$){let Q=this.hooks?.memoryScopes;if(Q)return Q(J,$);return{}}memoryMaxTokens=void 0;requireThread=!1;maxBodyBytes=s9;maxHistoryMessages=a9;contextWindow=void 0;prepareStep(J,$){return this.hooks?.prepareStep?.(J,$)}maxConcurrentRuns=t9;maxThreadRuns(J,$){let Q=this.hooks?.maxThreadRuns;if(Q)return Q(J,$);return e9}busyPolicy(J,$){let Q=this.hooks?.busyPolicy;if(Q)return Q(J,$);return $.requested??"supersede"}runLimitKey(J,$){let Q=this.hooks?.runLimitKey;if(Q)return Q(J,$);return $.owner}authorizeRequest(J,$){let Q=this.hooks?.authorizeRequest;if(Q)return Q(J,$);return this.resource?.authorize(J,$)}resource;runOwner(J){let $=this.hooks?.runOwner;if($)return $(J);let Q=J.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(J){let{threadId:$}=J;if(typeof $!=="string"||$==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let Q=J.ifBusy;if(Q!==void 0&&!vZ.includes(Q))throw TypeError(`AgentController.startTurn's \`ifBusy\` is "supersede", "queue", "join", "parallel" or "skip"; got ${JSON.stringify(J.ifBusy)}.`);let Z=J.event===void 0?void 0:N6(J),W={...J.turn,...J.text!==void 0?{text:J.text}:{}},X={...J.body,threadId:$,turn:W},K=new w(new Request(iZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}),{},"api",new URL(iZ).pathname),G=new this;if(y.set(K,null),J.scope!==void 0)hZ.set(K,J.scope);if(Q!==void 0)gZ.set(K,Q);if(Z)BJ.set(K,Z);let z=await n.run(K,()=>G.stream(K),{user:J.user??null}),V=u$.get(K),Y=y.get(K);if(!Y&&!V){let H=await zJ.from(z);if(Q==="skip"&&H.code===R8)return{skipped:!0,threadId:$};throw H}if(y.delete(K),u$.delete(K),z.body?.cancel().catch(k),V)return p9($,V);let{run:D,hooks:N}=Y;return i$($,D,N)}async stream(J=new w){let $=await VJ(J,this.maxBodyBytes);if($.error)return m($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=Y6(Q);if(W.error)return m({body:{},error:W.error});let X=W.turn,K=Z!==void 0&&Q.regenerate===!0,G=typeof Q.clientRunId==="string"?Q.clientRunId:void 0,z=gZ.get(J);if(!y.has(J)&&Q.ifBusy!==void 0){if(!i9.includes(Q.ifBusy))return m({body:{},error:`\`ifBusy\` is "supersede", "queue", "join" or "parallel"; got ${JSON.stringify(Q.ifBusy)}.`});z=Q.ifBusy}let V=nJ(Q);if(this.requireThread&&!Z)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(await this.scopeStore(J,V),K&&!this.store.removeMessages)return M(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!Z&&Array.isArray(Q.messages)&&Q.messages.length>this.maxHistoryMessages)return SJ(413,"history_too_long",`The conversation has ${Q.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(J),D=G?{cancelled:!1,owner:Y}:null;if(D)lJ.set(G,D);let N=null,H=[],C=async(P=c$)=>{try{return await _(P)}finally{if(Z&&H.length>0&&N===null)await this.store.appendMessages(Z,H).catch((U)=>this.reportHookFailure(U));if(P.release&&N===null)P.release()}},_=async(P)=>{let U,F=null;if(Z){let E=await this.store.loadThread(Z);if(!E)return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let JJ=await this.settleThread(Z,E,{write:!0});if(U=JJ.messages.filter((q)=>!(q.role==="assistant"&&q.finishReason===void 0&&q.runId&&this.liveRuns.isRunning(q.runId))),F=this.jobsBlock(JJ.jobs),K){let q=P6(U);if(!q)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});H=U.slice(q.index),await this.store.removeMessages(Z,H.map((w8)=>w8.id)),U=U.slice(0,q.index),X=X?.localId?{...q.turn,localId:X.localId}:q.turn}}else U=Array.isArray(Q.messages)?Q.messages:[],M6(this.nonces);let O=[await this.instructions(J,{body:V})||void 0,F??void 0].filter(Boolean).join(`
334
+ `))}catch{return null}let W=$===void 0||$===""?Number.NaN:Number($),X=Number.isFinite(W)?W:this.lastSeq+1;return this.lastSeq=X,{seq:X,event:Z}}}async function*MZ(J){if(!J)return;let $=J.getReader(),Q=new SZ;try{while(!0){let{done:Z,value:W}=await $.read();if(Z){yield*Q.flush();return}if(W)yield*Q.push(W)}}finally{try{await $.cancel()}catch{}}}function kZ(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 T9(J){let $=new Map;for(let Q of J)for(let Z of Q.content)if(Z.type==="tool-call")$.set(Z.toolCallId,Q.turn);return $}var j9=(J)=>J.path?.[0]??J.toolCallId;function x9(J,$,Q){if($.length===0)return[];let Z=T9(J),W=(G)=>G.turn??Z.get(j9(G)),X=new Set(Q.map(W));if(X.has(void 0)||X.size===0)return[];let K=new Set(Q.map((G)=>G.toolCallId));return $.filter((G)=>{let z=W(G);return z!==void 0&&!X.has(z)&&!K.has(G.toolCallId)})}function TZ(J,$,Q=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==J.cursorRunId)&&$.seq<=J.seq)return J;return{...jZ(J,$.event,Q),seq:$.seq}}function jZ(J,$,Q){switch($.type){case"run-start":return{...J,messages:I9(J.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return u(J,$.messageId,Q,(Z)=>({...Z,role:$.role,...$.turn&&Z.turn===void 0?{turn:$.turn}:{}}));case"text-delta":if(RZ(J,$.messageId))return J;return u(J,$.messageId,Q,(Z)=>({...Z,content:v9(Z.content,$.delta)}));case"reasoning-delta":if(RZ(J,$.messageId))return J;return u(J,$.messageId,Q,(Z)=>({...Z,content:y9(Z.content,$.delta,$.id,$.providerMetadata)}));case"output-delta":return u(J,$.messageId,Q,(Z)=>({...Z,content:EZ(Z.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return u(J,$.messageId,Q,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===$.part.toolCallId),X=W===-1?void 0:Z.content[W],K=$.part.progress??X?.progress,G=$.part.nested??X?.nested,z=$.part.attachments??X?.attachments,V={...$.part,...K?{progress:K}:{},...G?{nested:G}:{},...z?{attachments:z}:{}},Y=Z.content.slice();if(W===-1)Y.push(V);else Y[W]=V;return{...Z,content:Y}});case"tool-call-discard":return u(J,$.messageId,Q,(Z)=>{let W=Z.content.filter((X)=>!(X.type==="tool-call"&&X.partial&&$.toolCallIds.includes(X.toolCallId)));return W.length===Z.content.length?Z:{...Z,content:W}});case"tool-search":{let Z=$.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return AZ(J,$.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],$.data]}));case"nested-event":{let Z=$;return AZ(J,$.toolCallId,(W)=>{let X=W.nested??[],K=X.findIndex((Y)=>Y.runId===Z.runId),G=X[K]??{runId:Z.runId,agent:Z.agent,messages:[]},z=q9(G,Z,Q),V=K===-1?[...X,z]:X.map((Y,D)=>D===K?z:Y);return{...W,nested:V}})}case"tool-result":{let Z=u(J,$.messageId,Q,(W)=>({...W,content:EZ(W.content,$.part,(X)=>X.type==="tool-result"&&X.toolCallId===$.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((K)=>K.id===$.message.id),W=J.messages.slice();if(Z===-1)W.push($.message);else W[Z]=$.message;let X=J.runMessageIds.includes($.message.id)?J.runMessageIds:[...J.runMessageIds,$.message.id];return{...J,messages:W,runMessageIds:X}}case"message-id":{let Z=J.messages.findIndex((G)=>G.id===$.localId);if(Z===-1){if(!$.message||J.messages.some((G)=>G.id===$.messageId))return J;return{...J,messages:[...J.messages,$.message]}}let W=J.messages[Z],X={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},K=J.messages.some((G)=>G.id===$.messageId)?J.messages.filter((G,z)=>z!==Z).map((G)=>G.id===$.messageId?{...G,...X}:G):J.messages.map((G,z)=>z===Z?{...G,...X,id:$.messageId}:G);return{...J,messages:K}}case"awaiting-input":return{...J,runId:$.runId,pending:[...x9(J.messages,J.pending,$.pending),...$.pending]};case"message-end":return u(J,$.messageId,Q,(Z)=>({...Z,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...J,usage:$.usage};case"retry":return J;case"error":return{...J,error:$.error,pending:J.pending.filter((Z)=>Z.turn!==void 0)};case"run-end":return{...J,runId:void 0,finishReason:$.finishReason,messages:xZ(J,$.finishReason)};default:return J}}function I9(J,$){if(!J.some((Q)=>Q.runId===$&&Q.finishReason===void 0))return J;return J.map((Q)=>{if(Q.runId!==$||Q.finishReason!==void 0)return Q;let{runId:Z,...W}=Q;return{...W,content:[]}})}function xZ(J,$){return J.messages.map((Q)=>Q.role==="assistant"&&J.runMessageIds.includes(Q.id)?w9(Q,$):Q)}function w9(J,$){let Q=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((X)=>X.finishReason===void 0)?{...W,nested:W.nested.map((X)=>X.finishReason===void 0?f9(X,$):X)}:W);if(J.finishReason===void 0)return{...J,finishReason:$,content:Q};return Q.some((W,X)=>W!==J.content[X])?{...J,content:Q}:J}function f9(J,$){let Q={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:$,messages:xZ(Q,$)}}function AZ(J,$,Q){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],X=W.content.findIndex((V)=>V.type==="tool-call"&&V.toolCallId===$);if(X===-1)continue;if(W.finishReason!==void 0&&!b9(J,W,$))return J;let K=W.content.slice();K[X]=Q(K[X]);let G=J.messages.slice();G[Z]={...W,content:K};let z=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:z,messages:G}}return J}function q9(J,$,Q){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((X)=>X.id),loadedTools:[],finishReason:J.finishReason},W=jZ(Z,$.event,Q);return{...J,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function b9(J,$,Q){if($.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Q))}function RZ(J,$){let Q=J.messages.find((Z)=>Z.id===$);return Q!==void 0&&Q.finishReason!==void 0}function u(J,$,Q,Z){let W=J.messages.findIndex((G)=>G.id===$),X=J.runMessageIds.includes($)?J.runMessageIds:[...J.runMessageIds,$];if(W===-1){let G={id:$,role:"assistant",content:[],createdAt:Q};return{...J,runMessageIds:X,messages:[...J.messages,Z(G)]}}let K=J.messages.slice();return K[W]=Z(K[W]),{...J,runMessageIds:X,messages:K}}function v9(J,$){let Q=J[J.length-1];if(Q&&Q.type==="text")return[...J.slice(0,-1),{type:"text",text:Q.text+$}];return[...J,{type:"text",text:$}]}function y9(J,$,Q,Z){let W=J[J.length-1];if(W&&W.type==="reasoning"&&W.id===Q&&!W.providerMetadata)return[...J.slice(0,-1),{...W,text:(W.text??"")+$,...Z?{providerMetadata:Z}:{}}];return[...J,{type:"reasoning",...Q?{id:Q}:{},text:$,...Z?{providerMetadata:Z}:{}}]}function EZ(J,$,Q){let Z=J.findIndex(Q);if(Z===-1)return[...J,$];let W=J.slice();return W[Z]=$,W}class c${store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,$,Q,Z){this.store=J;this.threadId=$;this.report=Z;this.state=kZ({messages:Q})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[g$(J)])}frame(J){if(this.closed)return;let $=J.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=TZ(this.state,J),$.type){case"message":this.write(()=>[g$($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let $ of J)this.done.add($.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let $=this.state.messages.find((Z)=>Z.id===J);if(!$)return;let Q=this.runId;this.write(()=>{let Z=g$($);if(Z.finishReason===void 0&&Q)Z.runId=Q;return[Z]})}write(J){let $;try{$=J()}catch(Q){this.report(Q);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Q)=>this.report(Q))}}function g$(J){return structuredClone(J)}async function IZ(J,$){let Q=[],Z=null,W=J.slice();for(let X=0;X<W.length;X++){let K=W[X];if(K.role!=="assistant"||K.finishReason!==void 0)continue;if(K.runId&&await $(K.runId))continue;Z??=new Set(J.flatMap((V)=>V.content.flatMap((Y)=>Y.type==="tool-result"?[Y.toolCallId]:[])));let G=K.content.map((V)=>V.type==="tool-call"?wZ(V):V);for(let V of K.content){if(V.type!=="tool-call"||Z.has(V.toolCallId))continue;let Y={type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"interrupted"};G.push(Y)}let z={...K,content:G,finishReason:"interrupted"};W[X]=z,Q.push(z)}return{messages:W,settled:Q}}function wZ(J){let{partial:$,...Q}=J;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(h9)}}function h9(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Q)=>Q.type==="tool-call"?wZ(Q):Q)}:$)}}var g9=50,c9=["waiting","running","ok","error"];async function bZ(J,$){let{store:Q,threadId:Z}=$,W=Math.max(g9,$.scan??0),X=await Q.listForThread(Z,{limit:W}),K,G=async(H)=>{if(H.state!=="running")return H;if(K??=await fZ(Q),H.deadlineAt>K)return H;return await qZ(Q,H),await Q.get(H.id)??H};for(let H=0;H<X.length;H++)X[H]=await G(X[H]);let z=new Map(X.map((H)=>[H.id,H])),V=J.slice(),Y=[],D=new Set;for(let H=0;H<V.length;H++){let U=V[H],_=null;for(let P=0;P<U.content.length;P++){let C=U.content[P];if(C.type==="tool-call")D.add(C.toolCallId);if(C.type!=="tool-result"||C.status!=="running")continue;let F=C.job?.id,O=F?z.get(F):void 0;if(F&&O===void 0){let R=await Q.get(F);if(O=R?await G(R):void 0,O)z.set(F,O)}if(O&&!g(O.state))continue;_??=U.content.slice(),_[P]=u9(C,O,$.outputSchemaFor,$.modelOutputFor)}if(_){let P={...U,content:_};V[H]=P,Y.push(P)}}let N=[];for(let H of X){if(H.orphaned||H.toolCallId===""||D.has(H.toolCallId))continue;if(await $.isRunLive(H.runId))continue;N.push(H)}return{messages:V,settled:Y,orphans:N,jobs:X}}async function vZ(J,$,Q){for(let Z of $)try{await J.transition(Z.id,c9,{orphaned:!0})}catch(W){Q(W)}}function u9(J,$,Q,Z){let W={type:"tool-result",toolCallId:J.toolCallId,name:J.name},X=(z,V)=>{let Y=Z?.(String(J.name),z);return{...W,status:"ok",job:V,output:z,...Y!==void 0?{modelOutput:Y}:{}}};if(!$)return{...W,status:"error",job:J.job,error:{code:"tool_error",message:`The background job for "${String(J.name)}" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,toolCallId:J.toolCallId,retryable:!0}};let K={id:$.id,...$.summary!==void 0?{summary:$.summary}:{},...$.usage?{usage:$.usage}:{}};if($.state==="error")return{...W,status:"error",job:K,error:$.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let G=Q?.(String(J.name));if(G){let z=G.safeParse($.output);if(z.ok===!1)return{...W,status:"error",job:K,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: ${z.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return X(z.value,K)}return X($.output,K)}var m9=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;class YJ extends Error{status;code;kind;constructor(J,$){super(J);this.name="AgentTurnError",this.status=$.status,this.code=$.code,this.kind=$.kind}static async from(J){let $={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")$=Z.error}catch{}let Q=(Z)=>typeof $[Z]==="string"?$[Z]:void 0;return new YJ(Q("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:Q("code"),kind:Q("kind")})}}function p9(J){for(let $=J.length-1;$>=0;$--){let Q=J[$];if(Q.role!=="assistant")continue;return Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}function o$(J,$,Q,Z=!1){let W=[],X=(async()=>{for await(let G of $)if(G.type==="awaiting-input")W=G.pending})().catch(T),K;return{runId:$.runId,threadId:J,run:$,joined:Z,stop:(G)=>EJ($,G),result:()=>K??=(async()=>{let G=await $.result();await Promise.all([Q,X]);let z=G.messages;return{...G,threadId:J,text:p9(z),pending:G.finishReason==="awaiting-input"?W:[]}})()}}function l9(J,$){let Q=o$(J,$.run,t.get($.run)??$.run.result().then(T,T),!0),Z;return{...Q,stop:(W)=>{EJ($.run,W),$.answer.then((X)=>{if("run"in X)EJ(X.run,W)},T)},result:()=>Z??=(async()=>{let W=await $.answer;if(W.kind==="refused")throw await Q.result(),W.error;if(W.kind==="dropped"||W.run===$.run)return Q.result();return o$(J,W.run,W.hooks).result()})()}}var yZ=["supersede","queue","join","parallel","skip"];function i9(J,$){if($)return{event:{name:$.name,...$.text!==void 0?{text:$.text}:{},...$.data!==void 0?{data:$.data}:{}}};if(!J||J.toolResults&&J.toolResults.length>0)return null;if(!J.text&&!(J.files&&J.files.length>0))return null;return{...J.text?{text:J.text}:{},...J.files&&J.files.length>0?{files:J.files}:{},...J.localId?{localId:J.localId}:{}}}function hZ(J){if(!J)return{};let $="event"in J?J.event:void 0,Q=$?$.text:J.text;return{...Q?{text:Q}:{},...!$&&J.files&&J.files.length>0?{files:J.files}:{},...$?{event:{name:$.name}}:{}}}var d9=["supersede","queue","join","parallel"],n9=K8,SJ=new Map,t=new WeakMap,y=new WeakMap,gZ=new WeakMap,cZ=new WeakMap;function o9(J){return J.headers.get("Content-Type")?.startsWith("text/event-stream")??!1}var u$=new WeakMap,m$=new WeakMap,uZ=new WeakMap,mZ=new WeakMap,p$={parallel:!1},s9=5000,pZ=new WeakMap,l$=new WeakMap,lZ=new WeakMap,s$=new WeakSet;function EJ(J,$){s$.add(J),J.stop($)}function iZ(J,$){let Q=pZ.get(J);if(Q)return Q;let Z=(async()=>{for await(let X of J.frames()){let K=X.event.type;if(K==="message-start"||K==="awaiting-input"||K==="run-end")return}})().catch(T),W={done:!1,promise:Promise.resolve()};return W.promise=Promise.race([Z,J.result().then(T,T)]).then(()=>$?.settled()).then(T,T).then(()=>{W.done=!0}),pZ.set(J,W),W}var MJ=new WeakMap,E8="thread_busy",dZ="http://gemi.internal/__gemi/agent-turn",nJ=new Map,a9=4194304,t9=1000,r9=5;function e9(J){let{max:$,overflow:Q}=typeof J==="number"?{max:J,overflow:"reject"}:J??{};if(!($===1/0||Number.isInteger($)&&$>0)||Q!=="queue"&&Q!=="reject")throw TypeError(`AgentController.maxThreadRuns answers a positive whole number (or Infinity), or { max, overflow: "queue" | "reject" }; got ${JSON.stringify(J)}.`);return{max:$,overflow:Q}}var J6=3,AJ=65536,T=()=>{};class k8{byKey=new Map;take(J,$,Q){let Z=this.byKey.get(J);if(!Z?.has($)&&(Z?.size??0)>=Q)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set($,(Z.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let X=this.byKey.get(J),K=(X?.get($)??1)-1;if(!X)return;if(K>0)X.set($,K);else if(X.delete($),X.size===0)this.byKey.delete(J)}}}var nZ=new WeakMap,a$=new WeakMap;function $6(J){let $=a$.get(J);if(!$)$=new Map,a$.set(J,$);return $}function Q6(J,$,Q){let Z=a$.get(J)?.get($);if(!Z)return;for(let W of[...Z])try{W(Q)}catch{}}function oZ(J){let $=nZ.get(J);if(!$)$=new k8,nZ.set(J,$);return $}function Z6(J){return J}class tJ extends n9{static kind="agent-controller";hooks;store=h$;storeScope(J,$){return null}boundScope=void 0;async threadInScope(J,$){if(await this.scopeStore(J,{}),this.boundScope===null)return!0;return await this.store.loadThread($)!==null}async scopeStore(J,$){let Z=gZ.get(J)??await this.storeScope(J,{body:$})??null;if(this.boundScope!==void 0){if(this.boundScope!==Z)throw Error("This AgentController instance already served a request in another store scope. Build a controller per request (the router and startTurn do).");return}if(Z!==null)this.store=W8(this.store,Z);this.boundScope=Z}liveRuns=I$;voice;voiceStore=T$;attachments=$$;attachmentStorage=z8;turnAttachmentMaxAgeMs=3600000;fileOwners=w$;nonces=$Q;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,$){return this.hooks?.instructions?.(J,$)}reasoning(J,$){return this.hooks?.reasoning?.(J,$)}skills(J,$){return this.hooks?.skills?.(J,$)}runTools(J,$){return this.hooks?.runTools?.(J,$)}trailingContext(J,$){return this.hooks?.trailingContext?.(J,$)}usageLimits(J,$){return this.hooks?.usageLimits?.(J,$)}context(J,$){let Q=this.hooks?.context;if(Q)return Q(J,$);return{}}memoryScopes(J,$){let Q=this.hooks?.memoryScopes;if(Q)return Q(J,$);return{}}memoryMaxTokens=void 0;requireThread=!1;maxBodyBytes=a9;maxHistoryMessages=t9;contextWindow=void 0;prepareStep(J,$){return this.hooks?.prepareStep?.(J,$)}maxConcurrentRuns=r9;maxThreadRuns(J,$){let Q=this.hooks?.maxThreadRuns;if(Q)return Q(J,$);return J6}busyPolicy(J,$){let Q=this.hooks?.busyPolicy;if(Q)return Q(J,$);return $.requested??"supersede"}runLimitKey(J,$){let Q=this.hooks?.runLimitKey;if(Q)return Q(J,$);return $.owner}authorizeRequest(J,$){let Q=this.hooks?.authorizeRequest;if(Q)return Q(J,$);return this.resource?.authorize(J,$)}resource;runOwner(J){let $=this.hooks?.runOwner;if($)return $(J);let Q=J.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(J){let{threadId:$}=J;if(typeof $!=="string"||$==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let Q=J.ifBusy;if(Q!==void 0&&!yZ.includes(Q))throw TypeError(`AgentController.startTurn's \`ifBusy\` is "supersede", "queue", "join", "parallel" or "skip"; got ${JSON.stringify(J.ifBusy)}.`);let Z=J.event===void 0?void 0:F6(J),W={...J.turn,...J.text!==void 0?{text:J.text}:{}},X={...J.body,threadId:$,turn:W},K=new w(new Request(dZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}),{},"api",new URL(dZ).pathname),G=new this;if(y.set(K,null),J.scope!==void 0)gZ.set(K,J.scope);if(Q!==void 0)cZ.set(K,Q);if(Z)MJ.set(K,Z);let z=await n.run(K,()=>G.stream(K),{user:J.user??null}),V=l$.get(K),Y=y.get(K);if(!Y&&!V){let H=await YJ.from(z);if(Q==="skip"&&H.code===E8)return{skipped:!0,threadId:$};throw H}if(y.delete(K),l$.delete(K),z.body?.cancel().catch(T),V)return l9($,V);let{run:D,hooks:N}=Y;return o$($,D,N)}async stream(J=new w){let $=await zJ(J,this.maxBodyBytes);if($.error)return m($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=D6(Q);if(W.error)return m({body:{},error:W.error});let X=W.turn,K=Z!==void 0&&Q.regenerate===!0,G=typeof Q.clientRunId==="string"?Q.clientRunId:void 0,z=cZ.get(J);if(!y.has(J)&&Q.ifBusy!==void 0){if(!d9.includes(Q.ifBusy))return m({body:{},error:`\`ifBusy\` is "supersede", "queue", "join" or "parallel"; got ${JSON.stringify(Q.ifBusy)}.`});z=Q.ifBusy}let V=aJ(Q);if(this.requireThread&&!Z)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(await this.scopeStore(J,V),K&&!this.store.removeMessages)return M(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!Z&&Array.isArray(Q.messages)&&Q.messages.length>this.maxHistoryMessages)return RJ(413,"history_too_long",`The conversation has ${Q.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(J),D=G?{cancelled:!1,owner:Y}:null;if(D)nJ.set(G,D);let N=null,H=[],U=async(P=p$)=>{try{return await _(P)}finally{if(Z&&H.length>0&&N===null)await this.store.appendMessages(Z,H).catch((C)=>this.reportHookFailure(C));if(P.release&&N===null)P.release()}},_=async(P)=>{let C,F=null;if(Z){let E=await this.store.loadThread(Z);if(!E)return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let $J=await this.settleThread(Z,E,{write:!0});if(C=$J.messages.filter((b)=>!(b.role==="assistant"&&b.finishReason===void 0&&b.runId&&this.liveRuns.isRunning(b.runId))),F=this.jobsBlock($J.jobs),K){let b=N6(C);if(!b)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});H=C.slice(b.index),await this.store.removeMessages(Z,H.map((f8)=>f8.id)),C=C.slice(0,b.index),X=X?.localId?{...b.turn,localId:X.localId}:b.turn}}else C=Array.isArray(Q.messages)?Q.messages:[],M6(this.nonces);let O=[await this.instructions(J,{body:V})||void 0,F??void 0].filter(Boolean).join(`
335
335
 
336
- `)||void 0,A=await this.context(J,{body:V}),f=await this.reasoning(J,{body:V})||void 0,x=await this.skills(J,{body:V})||void 0,I=await this.runTools(J,{body:V,context:A})||void 0,v=await this.usageLimits(J,{body:V,context:A})||void 0,r=await this.trailingContext(J,{body:V,context:A})||void 0,p=await this.attachmentsFor(J,Z,{body:V}),l=await this.attachmentRetention(J,{route:"stream",threadId:Z,body:V});dJ(l,this.turnAttachmentMaxAgeMs);let L=[],R=p&&l?p.withLifetime({next:()=>dJ(l,this.turnAttachmentMaxAgeMs),onPut:(E)=>L.push(E)}):p,B=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(D?.cancelled)return eZ();let h=Z?new y$(this.store,Z,U,(E)=>this.reportHookFailure(E)):null,QQ=`run_${crypto.randomUUID()}`,ZQ=[],WQ,e={req:J,runId:QQ,threadId:Z,get denials(){return ZQ},get turn(){return WQ?.turn}},RJ={id:null,notified:Promise.resolve()},j=this.agent.stream({runId:QQ,messages:U,turn:X,threadId:Z,...P.parallel||z==="parallel"?{keepOtherTurnsOpen:!0}:{},...h?{onMessage:(E)=>h.finish(E)}:{},onTurn:(E)=>{if(RJ.id!==null)return;RJ.id=E.id;let JJ=h?h.settled():Promise.resolve();RJ.notified=JJ.then(()=>this.safely(()=>this.onMessage(E,e)))},instructions:O,...BJ.has(J)?{event:BJ.get(J)}:{},...y.has(J)?{echoTurn:!0}:{},...f?{reasoning:f}:{},...x&&x.length>0?{skills:x}:{},...I?.tools&&I.tools.length>0?{tools:I.tools}:{},...I?.activeTools?{activeTools:I.activeTools}:{},...r?{trailingContext:r}:{},...v?{usageLimits:v}:{},context:A,attachments:R,body:V,redactError:(E,JJ)=>this.redactError(E,JJ,e),onProviderRetry:(E)=>this.onProviderRetry(E,e),nonces:this.nonces,receipts:this.receipts,subject:Y,...B?{memory:{scopes:B,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&B8(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==oJ.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(E)=>this.prepareStep(E,e)}:{}});ZQ=j.denials,WQ=j;let j8=this.liveRuns.register(j,{threadId:Z,owner:Y,clientRunId:G,onEvent:(E)=>this.dispatchEvent(E,e),onInternalError:(E)=>this.reportHookFailure(E),maxRunDurationMs:this.agent.maxRunDurationMs});N=j;let EJ=BJ.get(J);if(h$.set(j,{startedAt:new Date,owner:Y,turn:EJ?{...EJ.text?{text:EJ.text}:{},event:{name:EJ.name}}:yZ(X),joined:[],body:V}),h)g$.set(j,h),this.follow(j,h);if(Z)$6(this.liveRuns,Z,j.runId);let XQ=X?.files??[],x8=this.definesRetention()&&(XQ.length>0||l==="turn")?()=>this.expireTurn({scoped:p,files:XQ,made:L,owner:Y}):null,{stored:I8,hooks:eJ}=this.persistRun(j,e,j8,h,RJ,x8);if(t.set(j,I8),uZ.set(J,{run:j,hooks:eJ}),y.has(J))y.set(J,{run:j,hooks:eJ});if(P.release)j.result().then(P.release,P.release);return J.ctx?.()?.waitUntil(eJ),j.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let P=await this.foreignFile([...X?.files??[],...Z?[]:U6(Q.messages)],Y);if(P)return P;if(D?.cancelled)return eZ();let U=await this.runLimitKey(J,{owner:Y,threadId:Z}),F=U===null?k:nZ(this.liveRuns).take(U,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!F)return SJ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);let O;try{return O=Z?await this.withThread(Z,Y,C,{req:J,requested:K?"supersede":z,decide:!K,source:y.has(J)?"server":"client",turn:X,body:V,limitKey:U}):await C(),O}finally{let A=N,f=O?cZ.get(O):void 0;if(A)A.result().then(F,F);else if(f)f.then(F,F);else F()}}finally{if(D&&lJ.get(G)===D)lJ.delete(G)}}async withThread(J,$,Q,Z){if(Z.requested==="skip"&&LJ.has(J))return J8(J);for(;;){let W=await this.underThreadLock(J,$,Q,Z);if(!("waitFor"in W))return W.response;await W.waitFor}}async underThreadLock(J,$,Q,Z){let W=LJ.get(J)??Promise.resolve(),X,K=new Promise((z)=>{X=z}),G=W.then(()=>K);LJ.set(J,G),await W;try{let z=this.liveRuns.running({threadId:J}).map((D)=>({info:D,run:this.liveRuns.get(D.runId)})).filter((D)=>D.run!==null);if(z.length===0){let D=await this.liveRuns.find({threadId:J}),N=D?this.liveRuns.get(D.runId):null;if(N)await t.get(N);return{response:await Q(c$)}}let V=Z.intake?.policy??(Z.decide?await this.decideBusy(J,$,z,Z):Z.requested??"supersede"),Y=(D)=>(t.get(D)??D.result()).then(k,k);if(V==="skip")return{response:J8(J)};if(V==="queue")return{waitFor:Promise.all(z.map(({run:D})=>Y(D)))};if(V==="join"){let D=z.filter(({info:_})=>this.liveRuns.mayAccess(_.runId,$));if(D.length===0)return{response:a()};let N=D[D.length-1],H=l9(Z.turn,BJ.get(Z.req)),C=H?N.run.join?.(H)??null:null;if(!C)return{waitFor:Y(N.run)};return h$.get(N.run)?.joined.push(yZ(H)),{response:this.joinResponse(J,$,N.run,C,H,Q,Z)}}if(V==="parallel"){let D=Z.intake??={policy:V,waited:new WeakSet},N=z.filter(({run:P})=>!lZ(P,g$.get(P)).done&&!D.waited.has(P));if(N.length>0){for(let{run:O}of N)D.waited.add(O);let P=Promise.all(N.map(({run:O})=>lZ(O,g$.get(O)).promise)),U,F=new Promise((O)=>{U=setTimeout(O,o9)});return{waitFor:Promise.race([P,F]).finally(()=>clearTimeout(U))}}let{max:H,overflow:C}=r9(await this.maxThreadRuns(Z.req,{threadId:J,owner:$,body:Z.body}));if(z.length>=H){if(C==="queue")return{waitFor:Promise.race(z.map(({run:P})=>Y(P)))};return{response:SJ(429,"too_many_runs",`This conversation already has ${z.length} answers going. Wait for one to finish, or stop it, and send again.`)}}let _=Z.limitKey===null?k:nZ(this.liveRuns).take(Z.limitKey,`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!_)return{response:SJ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`)};return{response:await Q({parallel:!0,release:_})}}if(z.some(({info:D})=>!this.liveRuns.mayAccess(D.runId,$)))return{response:a()};for(let{run:D}of z)D.stop({reason:"superseded by a later turn on this thread"});return await Promise.all(z.map(({run:D})=>t.get(D))),{response:await Q(c$)}}finally{if(X(),LJ.get(J)===G)LJ.delete(J)}}async decideBusy(J,$,Q,Z){let W=await this.busyPolicy(Z.req,{threadId:J,owner:$,requested:Z.requested,source:Z.source,turn:Z.turn,body:Z.body,running:Q.map(({info:X,run:K})=>{let G=h$.get(K);return{runId:X.runId,startedAt:G?.startedAt??new Date(X.startedAt),owner:this.liveRuns.ownerOf(X.runId),turn:G?.turn??{},messageId:K.turn?.id,body:G?.body,joined:[...G?.joined??[]]}})});if(!vZ.includes(W))throw TypeError(`AgentController.busyPolicy answers "supersede", "queue", "join", "parallel" or "skip"; got ${JSON.stringify(W)}.`);return W}joinResponse(J,$,Q,Z,W,X,K){let G=(H)=>({kind:"answered",run:H,hooks:t.get(H)??H.result().then(k,k)}),z=Z.taken.then(async(H)=>{if(H||d$.has(Q))return null;return this.withThread(J,$,X,K)}),V=z.then(async(H)=>{if(!H)return d$.has(Q)?{kind:"dropped"}:G(Q);let C=pZ.get(H);if(C)return C;let _=uZ.get(K.req);if(_&&n9(H))return{kind:"answered",..._};return{kind:"refused",error:await zJ.from(H),stored:await this.storeUnanswered(J,Q,W)}},async(H)=>{return this.reportHookFailure(H),{kind:"refused",error:new zJ("The turn started for a joined message failed.",{status:500}),stored:await this.storeUnanswered(J,Q,W)}});if(y.has(K.req))u$.set(K.req,{run:Q,answer:V});async function*Y(){let H=-1;for await(let P of Q.frames())H=P.seq,yield P;let C=await z.catch(()=>null),_=await V;if(_.kind==="refused"){if(C?.body?.cancel().catch(k),_.stored&&W.localId)yield{seq:++H,event:{type:"message-id",localId:W.localId,messageId:_.stored.id,message:_.stored}};let P=_.error.status===429;yield{seq:++H,event:{type:"error",error:{code:P?"rate_limited":"unknown",message:`Your message was not answered: ${_.error.message}`,retryable:P}}};return}if(!C?.body)return;try{for await(let P of MZ(C.body))yield P}finally{C.body.cancel().catch(k)}}let D=(async()=>{await Q.result().catch(k);let H=await V;if(H.kind==="answered")await H.run.result().catch(k)})(),N=p$(Y());return cZ.set(N,D),pZ.set(N,V),N}async storeUnanswered(J,$,Q){await t.get($);let Z=A8(Q.event?Q.event.text:Q.text,Q.files,Q.event);Z.turn=Z.id;try{return await this.store.appendMessages(J,[Z]),Z}catch(W){return this.reportHookFailure(W),null}}async attach(J=new w){let $=await VJ(J,MJ);if($.error)return m($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:rZ(J,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=Q.emptyMiss===!0;if(!await this.threadInScope(J,Z))return W8(Z,W);let X=typeof Q.runId==="string"?Q.runId:void 0,K=X&&this.liveRuns.isRunning(X)&&this.liveRuns.threadOf(X)===Z?{runId:X}:await this.liveRuns.find({threadId:Z});if(K&&!this.liveRuns.mayAccess(K.runId,await this.runOwner(J)))return a();if(!K)return W8(Z,W);let G=typeof Q.runId==="string"?Q.runId:void 0,z=G&&G!==K.runId?void 0:H6(J,Q);try{return p$(this.liveRuns.replay(K.runId,z))}catch(V){if(V instanceof GJ)return M(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof _J)return M(404,{code:V.code,message:V.message});throw V}}async watch(J=new w){let $=await VJ(J,MJ);if($.error)return m($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:rZ(J,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"watch needs a threadId: it is the thread whose runs are announced."});if(await this.authorizeRequest(J,{route:"attach",threadId:Z}),!await this.threadInScope(J,Z))return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let W=await this.runOwner(J),X=this.liveRuns,K=J6(X),G=null,z=null,V=0,Y=()=>{if(z?.stop(),!G)return;let N=K.get(Z);if(N?.delete(G),N&&N.size===0)K.delete(Z);G=null},D=new ReadableStream({start(N){z=Y8(N);let H=(_)=>{if(!X.mayAccess(_,W))return;try{N.enqueue(new TextEncoder().encode(z8({seq:++V,event:{type:"run-start",runId:_,threadId:Z}}))),z?.touch()}catch{Y()}};G=H;let C=K.get(Z);if(!C)C=new Set,K.set(Z,C);C.add(H);for(let{runId:_}of X.running({threadId:Z}))H(_)},cancel(){Y()}});return J.rawRequest?.signal?.addEventListener("abort",Y,{once:!0}),new Response(D,{status:200,headers:D8()})}async stop(J=new w){let $=await VJ(J,MJ);if($.error)return m($);let Q=$.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner(J),W=typeof Q.runId==="string"?Q.runId:void 0;if(!W&&typeof Q.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Q.clientRunId)??void 0,!W){let K=lJ.get(Q.clientRunId);if(K){if(K.owner!==null&&K.owner!==Z)return a();return K.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Q.threadId==="string"){let K=this.liveRuns.running({threadId:Q.threadId});if(K.length>1){let G=K.filter((V)=>this.liveRuns.mayAccess(V.runId,Z));if(G.length===0)return a();let z=typeof Q.reason==="string"?Q.reason:void 0;for(let V of G){let Y=this.liveRuns.get(V.runId);if(Y)AJ(Y,{reason:z})}return{stopped:!0}}W=(await this.liveRuns.find({threadId:Q.threadId}))?.runId}let X=W?this.liveRuns.get(W):null;if(!X)return{stopped:!1};if(!this.liveRuns.mayAccess(X.runId,Z))return a();return AJ(X,{reason:typeof Q.reason==="string"?Q.reason:void 0}),{stopped:!0}}attachmentScope(J,$,Q){let Z=this.hooks?.attachmentScope;if(Z)return Z(J,$,Q);let W=J.ctx()?.user,X=W?.id??W?.publicId;if(X!==void 0&&X!==null&&String(X)!=="")return{key:`user:${String(X)}`};if($)return{key:`thread:${$}`};return null}attachmentRetention(J,$){return this.hooks?.attachmentRetention?.(J,$)??null}definesRetention(){return this.attachmentRetention!==oJ.prototype.attachmentRetention||Boolean(this.hooks?.attachmentRetention)}async sweepAttachments(J={}){let $=J.now??new Date,Q=J.limit??500;if(!this.attachments.expired||!this.attachments.delete)throw Error("sweepAttachments() needs an attachment store with expired() and delete(). Implement both on the controller's `attachments` store.");let Z={deleted:0,failed:0},W=this.deletionTargets();for(let X of await this.attachments.expired($,Q))try{await l$(X,W),Z.deleted++}catch(K){Z.failed++,this.reportHookFailure(K)}for(let X of await this.fileOwners.expired?.($,Q)??[])try{await this.deleteProviderFile(X),Z.deleted++}catch(K){Z.failed++,this.reportHookFailure(K)}return Z}deletionTargets(){return{store:this.attachments,storage:this.attachmentStorage,provider:this.agent.provider,fileOwners:this.fileOwners}}async deleteProviderFile(J){let $=this.agent.provider;if(!$.deleteFile)throw Error(`Cannot delete provider file ${J}: the agent's provider has no deleteFile().`);await $.deleteFile(J),await this.fileOwners.delete?.(J)}async expireTurn(J){let $=this.deletionTargets(),Q=new Set,Z=new Set,W=async(X)=>{if(Q.has(X.id))return;if(Q.add(X.id),X.fileId)Z.add(X.fileId);try{await l$(X,$)}catch(K){this.reportHookFailure(K)}};for(let X of J.made)if(X.deleteAfterTurn)await W(X);for(let X of J.files){if(X.attachmentId&&J.scoped){let K=await J.scoped.get(X.attachmentId).catch(()=>null);if(K?.deleteAfterTurn)await W(K)}if(X.fileId&&!Z.has(X.fileId)){Z.add(X.fileId);let K=await this.fileOwners.get(X.fileId);if(K?.deleteAfterTurn&&K.owner===J.owner)try{await this.deleteProviderFile(X.fileId)}catch(G){this.reportHookFailure(G)}}}}attachmentLimits(J){let $=this.hooks?.attachmentLimits;if($)return $(J);return null}checkUpload(J,$,Q){return this.hooks?.checkUpload?.(J,$,Q)}attachmentDestination(J,$,Q){let Z=this.hooks?.attachmentDestination;if(Z)return Z(J,$,Q);return"both"}async attachmentsFor(J,$,Q={body:{}}){let Z=await this.attachmentScope(J,$,Q);if(!Z)return null;return new tJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new w){let $=this.voice;if(!$)return m$();let Q=await VJ(J,MJ);if(Q.error)return m(Q);let{sdp:Z,threadId:W,pushToTalk:X}=Q.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return M(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let K=nJ(Q.body,C6),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:G,body:K});let z=J.ctx?.()?.user??null,V=await $.start({req:J,body:K,threadId:G,user:z,pushToTalk:X===!0}),Y=Date.now(),D,N=async(F)=>{if(F!==void 0)console.error("[gemi/ai] a voice session could not start.",F);if(D)await $.realtime.hangup(D).catch((O)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",O)});try{await V.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:V.threadId??G??"",reason:"start_failed",startedAt:Y,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)}},H=V.threadId??G;if(!H)return await N(void 0),M(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(H!==G)await this.authorizeRequest(J,{route:"stream",threadId:H,body:K})}catch(F){throw await N(void 0),F}let C=crypto.randomUUID(),_=V.tools??[];try{if(V.mcp)_=[..._,...await S$(V.mcp,{user:z,sessionId:C})]}catch(F){return await N(F),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...V.session,tools:[...FJ($.delegate),...V.session?.tools??[],..._.map((F)=>F.tool)],...X===!0?{turnDetection:null}:{}},U;try{U=await $.realtime.createCall({sdp:Z,session:P,safetyIdentifier:V.safetyIdentifier})}catch(F){await N(F);let O=F instanceof $Q&&F.code==="rate_limited";return M(O?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=U.callId;try{await this.voiceStore.create({id:C,callId:U.callId,threadId:H,owner:await this.runOwner(J),body:K,startedAt:Y});let{threadId:F,session:O,safetyIdentifier:A,mcp:f,tools:x,...I}=V;return{sessionId:s.start({...I,tools:_,controller:this.constructor,threadId:H,user:z,body:K,call:{realtime:$.realtime,callId:U.callId},sessionId:C,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:P}).sessionId,sdp:U.sdpAnswer,threadId:H,delegate:$.delegate?.name??UJ,endsAt:Y+(V.limits?.maxDurationMs??900000)}}catch(F){return await N(F),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new w){if(!this.voice)return m$();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await VJ(J,MJ);if(Q.error)return m(Q);let Z=nJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),s.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new w){let $=this.voice;if(!$)return m$();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Q.body}),Q.endedAt!==void 0)return{ended:!1};let Z=s.get(Q.id);if(Z)await Z.end("hangup");else await $.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let $=J.params?.sessionId,Q=typeof $==="string"&&$?await this.voiceStore.get($):null;if(!Q)return M(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return a();return Q}async upload(J=new w){let $=await J.rawRequest.formData(),Q=$.get("file");if(!(Q instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=Q instanceof File&&Q.name?Q.name:"upload",W=Q.type||"application/octet-stream",X=W6($.get("body")),K=$.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof K==="string"&&K.length>0?K:void 0,body:X});let G=K6(await this.attachmentLimits(J),Q,Z,W);if(G)throw new a$(G.code,G.message);await this.scopeStore(J,X);let z=typeof K==="string"&&K.length>0&&await this.store.loadThread(K)!==null?K:void 0,V=await this.runOwner(J),Y=null,D=(x)=>this.fileOwners.record(x,{owner:V,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),...Y}),N={body:X,threadId:z},H=await this.checkUpload({name:Z,size:Q.size,mimeType:W},J,N);if(H)throw new a$(H.code||"upload_refused",H.message);let C=await this.attachmentDestination(Q,J,N),_=_6(C,$.get("destination")),P=await this.attachmentScope(J,z,{body:X});Y=dJ(await this.attachmentRetention(J,{route:"upload",threadId:z,body:X}),this.turnAttachmentMaxAgeMs);let U=_!=="provider"&&!P;if(U){if(_==="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()`.');O6()}if(_==="provider"||!P){let x=await oZ(this.agent.provider,Q);await D(x);let I={fileId:x,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(U)I.downgraded="no_scope";return I}let F=C8(),O=await this.attachmentStorage.put({name:_8(F,Z),body:Q,contentType:W}),A=_==="both"?await oZ(this.agent.provider,Q):void 0;if(A)await D(A);let f={id:F,scopeKey:P.key,fileId:A,objectName:O,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:_,...Y};return await this.attachments.put(P,f),{fileId:A,attachmentId:F,name:Z,mimeType:W,size:Q.size,destination:_}}async foreignFile(J,$){let Q=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of Q){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return F6()}return null}onMessage(J,$){return this.hooks?.onMessage?.(J,$)}onToolCall(J,$){return this.hooks?.onToolCall?.(J,$)}onToolResult(J,$,Q){return this.hooks?.onToolResult?.(J,$,Q)}onAwaitingInput(J,$){return this.hooks?.onAwaitingInput?.(J,$)}redactError(J,$,Q){let Z=this.hooks?.redactError;if(Z)return Z(J,$,Q);return e$(J,$)}onError(J,$){return this.hooks?.onError?.(J,$)}onProviderRetry(J,$){return this.hooks?.onProviderRetry?.(J,$)}onStreamComplete(J,$){return this.hooks?.onStreamComplete?.(J,$)}reportHookFailure(J){let $=this.hooks?.reportHookFailure;if($)try{return $(J)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,$){switch(J.type){case"tool-call":if(!J.part.partial&&!J.resent)await this.onToolCall({toolCallId:J.part.toolCallId,name:String(J.part.name),input:J.part.input},$);return;case"tool-result":{let Q=J.part;await this.onToolResult(Q,$,{toolCallId:Q.toolCallId,name:String(Q.name),input:S8(Q)});return}case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(N8(J.error),$);return;default:return}}async readThread(J,$={}){let Z=await($.scope===null||$.scope===void 0?this.store:Z8(this.store,$.scope)).loadThread(J);if(!Z)return null;let{messages:W}=await this.settleThread(J,Z,{write:!1});return W}isRunLive(J,$){return this.liveRuns.get(J)!==null}async settleThread(J,$,{write:Q}){let Z=(z)=>this.isRunLive(z,J),W=await xZ($,Z),X=W.messages,K=[],G=new Map(W.settled.map((z)=>[z.id,z]));if(S6(X)||Q)try{let z=await qZ(X,{threadId:J,store:i.store,isRunLive:Z,outputSchemaFor:(V)=>this.toolNamed(V)?.outputSchema,modelOutputFor:(V,Y)=>M8(this.toolNamed(V),Y,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});X=z.messages,K=z.jobs;for(let V of z.settled)G.set(V.id,V);if(Q&&z.orphans.length>0){await bZ(i.store,z.orphans,(Y)=>this.reportHookFailure(Y));let V=new Set(z.orphans.map((Y)=>Y.id));K=K.map((Y)=>V.has(Y.id)?{...Y,orphaned:!0}:Y)}}catch(z){this.reportHookFailure(z)}if(Q&&G.size>0)try{await this.store.appendMessages(J,[...G.values()])}catch(z){this.reportHookFailure(z)}return{messages:X,jobs:K}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??IJ}jobsBlock(J){return NQ(J,this.jobsBlockMax())}toolNamed(J){let $=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let X=$(W.tools);if(X)return X}else if(W.name===J)return W}return};return $(this.agent.tools??[])}follow(J,$){(async()=>{try{for await(let Q of J.frames())$.frame(Q)}catch(Q){this.reportHookFailure(Q)}})()}persistRun(J,$,Q,Z=null,W={id:null,notified:Promise.resolve()},X=null){let K=(Y)=>X?Y.then(()=>this.safely(X)):Y,G=Promise.resolve(),z=(async()=>{let Y;try{Y=await J.result()}catch(N){Z?.close(),await Z?.settled(),G=K(W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:N instanceof Error?N.message:String(N),retryable:!1},$))));return}let D=Y.messages;if(Z?.close(D),await Z?.settled(),$.threadId&&D.length>0)try{await this.store.appendMessages($.threadId,D)}catch(N){this.reportHookFailure(N)}G=K(this.notifyRun(Y,D,$,W))})(),V=z.then(()=>B6(Promise.all([G,Q]).then(()=>{}),this.hookHoldMs));return{stored:z,hooks:V}}async notifyRun(J,$,Q,Z){await Z.notified;for(let W of $){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete(J,Q))}async safely(J){try{await J()}catch($){this.reportHookFailure($)}}}var o$=["turn","clientRunId","threadId","messages","regenerate","ifBusy"],Z6=["text","files","toolResults"];function nJ(J,$=T8(J)?o$:[...o$,...Z6]){let Q={};for(let[Z,W]of Object.entries(J)){if($.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function W6(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new s$("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new s$("The upload's `body` field must be a JSON object.");return nJ($,o$)}class s$ extends sJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function oZ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof L8&&X6.has(Q.status))throw new k8(WJ(Q).message);throw Q}}var X6=new Set([400,413,415,422]);class a$ extends sJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function K6(J,$,Q,Z){if(!J)return null;let{maxBytes:W,accept:X}=J;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${sZ($.size)}; the limit is ${sZ(W)}.`};if(X&&X.length>0&&!X.some((K)=>G6(K,Q,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify(Q)} is not a type this chat accepts. Accepted: ${X.join(", ")}.`};return null}function G6(J,$,Q){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return $.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function sZ(J){if(J<1024)return`${J} B`;let $=["KB","MB","GB"],Q=J/1024,Z=0;while(Q>=1024&&Z<$.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${$[Z]}`}class k8 extends sJ{constructor(J){super(J);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(J)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:J}}},view:{}}}}async function VJ(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!V6(Q.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number(Q.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>$)return aZ($);let W;try{let K=await z6(Q,$);if(K===null)return aZ($);W=K}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let X;try{X=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(X===null||typeof X!=="object"||Array.isArray(X))return{body:{},error:"The request body must be a JSON object."};return{body:X}}function V6(J){return G8(J)==="application/json"}async function z6(J,$){if(!Number.isFinite($)||!J.body)return await J.text();let Q=J.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:z}=await Q.read();if(G)break;if(W+=z.byteLength,W>$)return await Q.cancel().catch(k),null;Z.push(z)}let X=new Uint8Array(W),K=0;for(let G of Z)X.set(G,K),K+=G.byteLength;return new TextDecoder().decode(X)}function aZ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function SJ(J,$,Q){return M(J,{...aJ(K8(J),Q,J),code:$})}function m(J){if(J.status===413)return SJ(413,J.code??"body_too_large",J.error??"");return M(J.status??400,{code:J.code??"invalid_request",message:J.error})}function T8(J){return Boolean(J.turn)&&typeof J.turn==="object"}function Y6(J){let $=T8(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=D6($.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray($.toolResults))Q.toolResults=$.toolResults;if(Object.keys(Q).length===0)return{};if($===J.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:Z}=$;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>tZ)return{error:`turn.localId is longer than ${tZ} characters.`};Q.localId=Z}return{turn:Q}}var tZ=200;function D6(J){let $=[];for(let[Q,Z]of J.entries()){let W=`turn.files[${Q}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let X={};for(let Y of["fileId","attachmentId","name","mimeType"]){let D=Z[Y];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${Y} must be a string.`;X[Y]=D}let{fileId:K,attachmentId:G,name:z,mimeType:V}=X;if(K?.startsWith(iJ))return`${W}.fileId holds a gemi attachment id (${K}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(G!==void 0&&!G.startsWith(iJ))return`${W}.attachmentId is not a gemi attachment id: it must start with "${iJ}".`;if(!K&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...K?{fileId:K}:{},...G?{attachmentId:G}:{},...z!==void 0?{name:z}:{},...V!==void 0?{mimeType:V}:{}})}return $}function H6(J,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let Z=Math.floor($.cursor);if(Z>=0)return Z+1;return}let Q=J?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function rZ(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function P6(J){let $=JQ(J);for(let Q=J.length-1;Q>=0;Q--){let Z=J[Q];if(Z.role!=="user"||$.has(Z.id))continue;let W="",X=[];for(let K of Z.content){if(K.type==="text")W+=K.text;if(K.type==="file")X.push({...K.fileId?{fileId:K.fileId}:{},...K.attachmentId?{attachmentId:K.attachmentId}:{},...K.name?{name:K.name}:{},...K.mimeType?{mimeType:K.mimeType}:{}})}if(!W&&X.length===0)continue;return{index:Q,turn:{...W?{text:W}:{},...X.length>0?{files:X}:{}}}}return null}function eZ(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function N6(J){let $=J.event;if(J.text!==void 0||J.turn!==void 0)throw TypeError("AgentController.startTurn takes an `event` or a `text`/`turn`, not both: an event is not a person's message.");if(typeof $!=="object"||$===null||typeof $.name!=="string"||!u9.test($.name))throw TypeError('AgentController.startTurn\'s `event.name` must be letters, digits and `.`, `_`, `:`, `-` (at most 64), like "job-settled".');if($.text!==void 0&&typeof $.text!=="string")throw TypeError("AgentController.startTurn's `event.text` must be a string.");let Q;if($.data!==void 0)try{Q=JSON.parse(JSON.stringify($.data))}catch(Z){throw TypeError(`AgentController.startTurn's \`event.data\` is not JSON: ${String(Z)}`)}return{name:$.name,...$.text?{text:$.text}:{},...Q!==void 0?{data:Q}:{}}}function J8(J){return M(409,{code:R8,message:`Thread ${J} has a run going, and this turn was not to interrupt it.`})}function a(){return M(403,aJ("permission","This run belongs to someone else.",403))}function F6(){return M(403,aJ("permission","A file in this turn was uploaded by someone else.",403))}function U6(J){if(!Array.isArray(J))return[];let $=[];for(let Q of J){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}var C6=["sdp","threadId","pushToTalk"];function m$(){return M(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function M(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function _6(J,$){if(typeof $!=="string"||$.length===0)return J;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===J||J==="both"&&$==="storage")return $;if(J==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${J}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var $8=!1;function O6(){if($8)return;$8=!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 L6=2147483647;function B6(J,$){let Q=J.then(()=>{},()=>{});if(!($<=L6))return Q;let Z,W=new Promise((X)=>{Z=setTimeout(X,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var Q8=!1;function M6(J){if(Q8||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof t$))return;Q8=!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 S6(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}function Z8(J,$){if(typeof $!=="string"||$==="")throw TypeError("A store scope is a non-empty string.");if(!J.forScope)throw Error("This controller's store cannot be scoped: storeScope() or a turn's `scope` needs a store that implements `forScope` (DatabaseAgentStore or MemoryAgentStore).");return J.forScope($)}function W8(J,$=!1){if($)return new Response(null,{status:204});return M(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`})}export{f6 as windowMessages,FJ as voiceTools,T6 as turnStarts,J0 as toRealtimeUsage,$9 as toAgentTools,E6 as supportsStrict,j6 as splitTurns,c6 as settleSummaries,R6 as s,e$ as redactError,t6 as parsePartialJson,x6 as messageSize,PJ as measureUsage,S$ as mcpVoiceTools,T$ as liveRuns,CJ as keepSummary,Q0 as isCallNotFound,JQ as injectedMessageIds,H$ as generate,H9 as evalChain,Q6 as defineAgentHooks,R$ as defaultVoiceStore,m6 as defaultUsageLimitStore,g6 as defaultSummaryStore,a6 as defaultPromptCacheKey,r$ as defaultNonceStore,j$ as defaultFileOwners,rJ as defaultAttachmentStore,b$ as defaultAgentStore,uJ as VoiceHangup,s as VoiceBridge,k6 as Usage,N$ as ToolNamespace,o as ToolError,o6 as ToolArgumentsTooLongError,l6 as Skill,tJ as ScopedAttachments,i6 as SKILLS_NAMESPACE,f$ as RedisReceiptStore,H8 as RedisNonceStore,r6 as RealtimeSideband,$Q as RealtimeRequestError,$0 as RealtimeClient,DQ as Prompt,P8 as PrismaNonceStore,p6 as PendingEscalation,Z0 as OpenAIProvider,_$ as OpenAIImageProvider,A$ as MemoryVoiceSessionStore,u6 as MemoryUsageLimitStore,h6 as MemorySummaryStore,w$ as MemoryReceiptStore,t$ as MemoryNonceStore,mJ as MemoryLiveRuns,pJ as MemoryFileOwners,gJ as MemoryCircuitStore,O8 as MemoryAttachmentStore,OJ as MemoryAgentStore,_Q as MemoryAgentJobStore,bQ as MEMORY_NAMESPACE,_J as LiveRunNotFoundError,LQ as JobsRequireThreadError,OQ as JobHandle,A6 as JSONSchemaError,U8 as InvalidAttachmentScopeError,jQ as InMemoryAgentMemoryStore,yJ as ImageRequestError,hJ as ImageProvider,F$ as ImageModel,GJ as FrameCursorEvictedError,NJ as FallbackProvider,fQ as FakeAgentMemoryStore,bJ as Eval,E$ as DatabaseAgentStore,K$ as DatabaseAgentMemoryStore,W$ as DatabaseAgentJobStore,e6 as DEFAULT_TRANSCRIPTION_MODEL,TQ as DEFAULT_MEMORY_MAX_TOKENS,qQ as DEFAULT_MEMORY_LIMITS,q6 as DEFAULT_MAX_SUMMARY_TOKENS,d6 as DEFAULT_MAX_RUN_DURATION_MS,BQ as DEFAULT_JOB_DEADLINE_MS,IJ as DEFAULT_JOBS_CONTEXT_MAX,UJ as DEFAULT_DELEGATE_NAME,I6 as DEFAULT_CONTEXT_WINDOW_STEP,w6 as DEFAULT_CONTEXT_WINDOW_NOTE,b6 as DEFAULT_COMPACT_TRIGGER_TOKENS,v6 as DEFAULT_COMPACT_INSTRUCTIONS,y6 as COMPACT_SUMMARY_HEADER,K0 as AzureOpenAIProvider,O$ as AzureOpenAIImageProvider,X0 as AzureAnthropicProvider,F8 as AttachmentNotFoundError,W0 as AnthropicProvider,zJ as AgentTurnError,vJ as AgentTool,n6 as AgentRunError,M$ as AgentProvider,xQ as AgentMemoryRefusedError,IQ as AgentMemoryConflictError,wQ as AgentMemories,i as AgentJobs,Z$ as AgentJobDeadlineSweep,MQ as AgentJob,oJ as AgentController,s6 as Agent};
336
+ `)||void 0,R=await this.context(J,{body:V}),f=await this.reasoning(J,{body:V})||void 0,x=await this.skills(J,{body:V})||void 0,I=await this.runTools(J,{body:V,context:R})||void 0,h=await this.usageLimits(J,{body:V,context:R})||void 0,r=await this.trailingContext(J,{body:V,context:R})||void 0,p=await this.attachmentsFor(J,Z,{body:V}),l=await this.attachmentRetention(J,{route:"stream",threadId:Z,body:V});sJ(l,this.turnAttachmentMaxAgeMs);let L=[],A=p&&l?p.withLifetime({next:()=>sJ(l,this.turnAttachmentMaxAgeMs),onPut:(E)=>L.push(E)}):p,B=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(D?.cancelled)return J8();let q=Z?new c$(this.store,Z,C,(E)=>this.reportHookFailure(E)):null,DJ=`run_${crypto.randomUUID()}`,e=[],kJ,JJ={req:J,runId:DJ,threadId:Z,get denials(){return e},get turn(){return kJ?.turn}},TJ={id:null,notified:Promise.resolve()},j=this.agent.stream({runId:DJ,messages:C,turn:X,threadId:Z,...P.parallel||z==="parallel"||y.has(J)?{keepOtherTurnsOpen:!0}:{},...q?{onMessage:(E)=>q.finish(E)}:{},onTurn:(E)=>{if(TJ.id!==null)return;TJ.id=E.id;let $J=q?q.settled():Promise.resolve();TJ.notified=$J.then(()=>this.safely(()=>this.onMessage(E,JJ)))},instructions:O,...MJ.has(J)?{event:MJ.get(J)}:{},...y.has(J)?{echoTurn:!0}:{},...f?{reasoning:f}:{},...x&&x.length>0?{skills:x}:{},...I?.tools&&I.tools.length>0?{tools:I.tools}:{},...I?.activeTools?{activeTools:I.activeTools}:{},...r?{trailingContext:r}:{},...h?{usageLimits:h}:{},context:R,attachments:A,body:V,redactError:(E,$J)=>this.redactError(E,$J,JJ),onProviderRetry:(E)=>this.onProviderRetry(E,JJ),nonces:this.nonces,receipts:this.receipts,subject:Y,...B?{memory:{scopes:B,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&S8(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==tJ.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(E)=>this.prepareStep(E,JJ)}:{}});e=j.denials,kJ=j;let x8=this.liveRuns.register(j,{threadId:Z,owner:Y,clientRunId:G,onEvent:(E)=>this.dispatchEvent(E,JJ),onInternalError:(E)=>this.reportHookFailure(E),maxRunDurationMs:this.agent.maxRunDurationMs});N=j;let jJ=MJ.get(J);if(u$.set(j,{startedAt:new Date,owner:Y,turn:jJ?{...jJ.text?{text:jJ.text}:{},event:{name:jJ.name}}:hZ(X),joined:[],body:V}),q)m$.set(j,q),this.follow(j,q);if(Z)Q6(this.liveRuns,Z,j.runId);let XQ=X?.files??[],I8=this.definesRetention()&&(XQ.length>0||l==="turn")?()=>this.expireTurn({scoped:p,files:XQ,made:L,owner:Y}):null,{stored:w8,hooks:Q$}=this.persistRun(j,JJ,x8,q,TJ,I8);if(t.set(j,w8),mZ.set(J,{run:j,hooks:Q$}),y.has(J))y.set(J,{run:j,hooks:Q$});if(P.release)j.result().then(P.release,P.release);return J.ctx?.()?.waitUntil(Q$),j.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let P=await this.foreignFile([...X?.files??[],...Z?[]:U6(Q.messages)],Y);if(P)return P;if(D?.cancelled)return J8();let C=await this.runLimitKey(J,{owner:Y,threadId:Z}),F=C===null?T:oZ(this.liveRuns).take(C,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!F)return RJ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);let O;try{return O=Z?await this.withThread(Z,Y,U,{req:J,requested:K?"supersede":z,decide:!K,source:y.has(J)?"server":"client",turn:X,body:V,limitKey:C}):await U(),O}finally{let R=N,f=O?uZ.get(O):void 0;if(R)R.result().then(F,F);else if(f)f.then(F,F);else F()}}finally{if(D&&nJ.get(G)===D)nJ.delete(G)}}async withThread(J,$,Q,Z){if(Z.requested==="skip"&&SJ.has(J))return $8(J);for(;;){let W=await this.underThreadLock(J,$,Q,Z);if(!("waitFor"in W))return W.response;await W.waitFor}}async underThreadLock(J,$,Q,Z){let W=SJ.get(J)??Promise.resolve(),X,K=new Promise((z)=>{X=z}),G=W.then(()=>K);SJ.set(J,G),await W;try{let z=this.liveRuns.running({threadId:J}).map((D)=>({info:D,run:this.liveRuns.get(D.runId)})).filter((D)=>D.run!==null);if(z.length===0){let D=await this.liveRuns.find({threadId:J}),N=D?this.liveRuns.get(D.runId):null;if(N)await t.get(N);return{response:await Q(p$)}}let V=Z.intake?.policy??(Z.decide?await this.decideBusy(J,$,z,Z):Z.requested??"supersede"),Y=(D)=>(t.get(D)??D.result()).then(T,T);if(V==="skip")return{response:$8(J)};if(V==="queue")return{waitFor:Promise.all(z.map(({run:D})=>Y(D)))};if(V==="join"){let D=z.filter(({info:_})=>this.liveRuns.mayAccess(_.runId,$));if(D.length===0)return{response:a()};let N=D[D.length-1],H=i9(Z.turn,MJ.get(Z.req)),U=H?N.run.join?.(H)??null:null;if(!U)return{waitFor:Y(N.run)};return u$.get(N.run)?.joined.push(hZ(H)),{response:this.joinResponse(J,$,N.run,U,H,Q,Z)}}if(V==="parallel"){let D=Z.intake??={policy:V,waited:new WeakSet},N=z.filter(({run:P})=>!iZ(P,m$.get(P)).done&&!D.waited.has(P));if(N.length>0){for(let{run:O}of N)D.waited.add(O);let P=Promise.all(N.map(({run:O})=>iZ(O,m$.get(O)).promise)),C,F=new Promise((O)=>{C=setTimeout(O,s9)});return{waitFor:Promise.race([P,F]).finally(()=>clearTimeout(C))}}let{max:H,overflow:U}=e9(await this.maxThreadRuns(Z.req,{threadId:J,owner:$,body:Z.body}));if(z.length>=H){if(U==="queue")return{waitFor:Promise.race(z.map(({run:P})=>Y(P)))};return{response:RJ(429,"too_many_runs",`This conversation already has ${z.length} answers going. Wait for one to finish, or stop it, and send again.`)}}let _=Z.limitKey===null?T:oZ(this.liveRuns).take(Z.limitKey,`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!_)return{response:RJ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`)};return{response:await Q({parallel:!0,release:_})}}if(z.some(({info:D})=>!this.liveRuns.mayAccess(D.runId,$)))return{response:a()};for(let{run:D}of z)D.stop({reason:"superseded by a later turn on this thread"});return await Promise.all(z.map(({run:D})=>t.get(D))),{response:await Q(p$)}}finally{if(X(),SJ.get(J)===G)SJ.delete(J)}}async decideBusy(J,$,Q,Z){let W=await this.busyPolicy(Z.req,{threadId:J,owner:$,requested:Z.requested,source:Z.source,turn:Z.turn,body:Z.body,running:Q.map(({info:X,run:K})=>{let G=u$.get(K);return{runId:X.runId,startedAt:G?.startedAt??new Date(X.startedAt),owner:this.liveRuns.ownerOf(X.runId),turn:G?.turn??{},messageId:K.turn?.id,body:G?.body,joined:[...G?.joined??[]]}})});if(!yZ.includes(W))throw TypeError(`AgentController.busyPolicy answers "supersede", "queue", "join", "parallel" or "skip"; got ${JSON.stringify(W)}.`);return W}joinResponse(J,$,Q,Z,W,X,K){let G=(H)=>({kind:"answered",run:H,hooks:t.get(H)??H.result().then(T,T)}),z=Z.taken.then(async(H)=>{if(H||s$.has(Q))return null;return this.withThread(J,$,X,K)}),V=z.then(async(H)=>{if(!H)return s$.has(Q)?{kind:"dropped"}:G(Q);let U=lZ.get(H);if(U)return U;let _=mZ.get(K.req);if(_&&o9(H))return{kind:"answered",..._};return{kind:"refused",error:await YJ.from(H),stored:await this.storeUnanswered(J,Q,W)}},async(H)=>{return this.reportHookFailure(H),{kind:"refused",error:new YJ("The turn started for a joined message failed.",{status:500}),stored:await this.storeUnanswered(J,Q,W)}});if(y.has(K.req))l$.set(K.req,{run:Q,answer:V});async function*Y(){let H=-1;for await(let P of Q.frames())H=P.seq,yield P;let U=await z.catch(()=>null),_=await V;if(_.kind==="refused"){if(U?.body?.cancel().catch(T),_.stored&&W.localId)yield{seq:++H,event:{type:"message-id",localId:W.localId,messageId:_.stored.id,message:_.stored}};let P=_.error.status===429;yield{seq:++H,event:{type:"error",error:{code:P?"rate_limited":"unknown",message:`Your message was not answered: ${_.error.message}`,retryable:P}}};return}if(!U?.body)return;try{for await(let P of MZ(U.body))yield P}finally{U.body.cancel().catch(T)}}let D=(async()=>{await Q.result().catch(T);let H=await V;if(H.kind==="answered")await H.run.result().catch(T)})(),N=d$(Y());return uZ.set(N,D),lZ.set(N,V),N}async storeUnanswered(J,$,Q){await t.get($);let Z=R8(Q.event?Q.event.text:Q.text,Q.files,Q.event);Z.turn=Z.id;try{return await this.store.appendMessages(J,[Z]),Z}catch(W){return this.reportHookFailure(W),null}}async attach(J=new w){let $=await zJ(J,AJ);if($.error)return m($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:eZ(J,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=Q.emptyMiss===!0;if(!await this.threadInScope(J,Z))return X8(Z,W);let X=typeof Q.runId==="string"?Q.runId:void 0,K=X&&this.liveRuns.isRunning(X)&&this.liveRuns.threadOf(X)===Z?{runId:X}:await this.liveRuns.find({threadId:Z});if(K&&!this.liveRuns.mayAccess(K.runId,await this.runOwner(J)))return a();if(!K)return X8(Z,W);let G=typeof Q.runId==="string"?Q.runId:void 0,z=G&&G!==K.runId?void 0:P6(J,Q);try{return d$(this.liveRuns.replay(K.runId,z))}catch(V){if(V instanceof VJ)return M(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof LJ)return M(404,{code:V.code,message:V.message});throw V}}async watch(J=new w){let $=await zJ(J,AJ);if($.error)return m($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:eZ(J,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"watch needs a threadId: it is the thread whose runs are announced."});if(await this.authorizeRequest(J,{route:"attach",threadId:Z}),!await this.threadInScope(J,Z))return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let W=await this.runOwner(J),X=this.liveRuns,K=$6(X),G=null,z=null,V=0,Y=()=>{if(z?.stop(),!G)return;let N=K.get(Z);if(N?.delete(G),N&&N.size===0)K.delete(Z);G=null},D=new ReadableStream({start(N){z=D8(N);let H=(_)=>{if(!X.mayAccess(_,W))return;try{N.enqueue(new TextEncoder().encode(Y8({seq:++V,event:{type:"run-start",runId:_,threadId:Z}}))),z?.touch()}catch{Y()}};G=H;let U=K.get(Z);if(!U)U=new Set,K.set(Z,U);U.add(H);for(let{runId:_}of X.running({threadId:Z}))H(_)},cancel(){Y()}});return J.rawRequest?.signal?.addEventListener("abort",Y,{once:!0}),new Response(D,{status:200,headers:H8()})}async stop(J=new w){let $=await zJ(J,AJ);if($.error)return m($);let Q=$.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner(J),W=typeof Q.runId==="string"?Q.runId:void 0;if(!W&&typeof Q.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Q.clientRunId)??void 0,!W){let K=nJ.get(Q.clientRunId);if(K){if(K.owner!==null&&K.owner!==Z)return a();return K.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Q.threadId==="string"){let K=this.liveRuns.running({threadId:Q.threadId});if(K.length>1){let G=K.filter((V)=>this.liveRuns.mayAccess(V.runId,Z));if(G.length===0)return a();let z=typeof Q.reason==="string"?Q.reason:void 0;for(let V of G){let Y=this.liveRuns.get(V.runId);if(Y)EJ(Y,{reason:z})}return{stopped:!0}}W=(await this.liveRuns.find({threadId:Q.threadId}))?.runId}let X=W?this.liveRuns.get(W):null;if(!X)return{stopped:!1};if(!this.liveRuns.mayAccess(X.runId,Z))return a();return EJ(X,{reason:typeof Q.reason==="string"?Q.reason:void 0}),{stopped:!0}}attachmentScope(J,$,Q){let Z=this.hooks?.attachmentScope;if(Z)return Z(J,$,Q);let W=J.ctx()?.user,X=W?.id??W?.publicId;if(X!==void 0&&X!==null&&String(X)!=="")return{key:`user:${String(X)}`};if($)return{key:`thread:${$}`};return null}attachmentRetention(J,$){return this.hooks?.attachmentRetention?.(J,$)??null}definesRetention(){return this.attachmentRetention!==tJ.prototype.attachmentRetention||Boolean(this.hooks?.attachmentRetention)}async sweepAttachments(J={}){let $=J.now??new Date,Q=J.limit??500;if(!this.attachments.expired||!this.attachments.delete)throw Error("sweepAttachments() needs an attachment store with expired() and delete(). Implement both on the controller's `attachments` store.");let Z={deleted:0,failed:0},W=this.deletionTargets();for(let X of await this.attachments.expired($,Q))try{await n$(X,W),Z.deleted++}catch(K){Z.failed++,this.reportHookFailure(K)}for(let X of await this.fileOwners.expired?.($,Q)??[])try{await this.deleteProviderFile(X),Z.deleted++}catch(K){Z.failed++,this.reportHookFailure(K)}return Z}deletionTargets(){return{store:this.attachments,storage:this.attachmentStorage,provider:this.agent.provider,fileOwners:this.fileOwners}}async deleteProviderFile(J){let $=this.agent.provider;if(!$.deleteFile)throw Error(`Cannot delete provider file ${J}: the agent's provider has no deleteFile().`);await $.deleteFile(J),await this.fileOwners.delete?.(J)}async expireTurn(J){let $=this.deletionTargets(),Q=new Set,Z=new Set,W=async(X)=>{if(Q.has(X.id))return;if(Q.add(X.id),X.fileId)Z.add(X.fileId);try{await n$(X,$)}catch(K){this.reportHookFailure(K)}};for(let X of J.made)if(X.deleteAfterTurn)await W(X);for(let X of J.files){if(X.attachmentId&&J.scoped){let K=await J.scoped.get(X.attachmentId).catch(()=>null);if(K?.deleteAfterTurn)await W(K)}if(X.fileId&&!Z.has(X.fileId)){Z.add(X.fileId);let K=await this.fileOwners.get(X.fileId);if(K?.deleteAfterTurn&&K.owner===J.owner)try{await this.deleteProviderFile(X.fileId)}catch(G){this.reportHookFailure(G)}}}}attachmentLimits(J){let $=this.hooks?.attachmentLimits;if($)return $(J);return null}checkUpload(J,$,Q){return this.hooks?.checkUpload?.(J,$,Q)}attachmentDestination(J,$,Q){let Z=this.hooks?.attachmentDestination;if(Z)return Z(J,$,Q);return"both"}async attachmentsFor(J,$,Q={body:{}}){let Z=await this.attachmentScope(J,$,Q);if(!Z)return null;return new J$(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new w){let $=this.voice;if(!$)return i$();let Q=await zJ(J,AJ);if(Q.error)return m(Q);let{sdp:Z,threadId:W,pushToTalk:X}=Q.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return M(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let K=aJ(Q.body,_6),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:G,body:K});let z=J.ctx?.()?.user??null,V=await $.start({req:J,body:K,threadId:G,user:z,pushToTalk:X===!0}),Y=Date.now(),D,N=async(F)=>{if(F!==void 0)console.error("[gemi/ai] a voice session could not start.",F);if(D)await $.realtime.hangup(D).catch((O)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",O)});try{await V.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:V.threadId??G??"",reason:"start_failed",startedAt:Y,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)}},H=V.threadId??G;if(!H)return await N(void 0),M(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(H!==G)await this.authorizeRequest(J,{route:"stream",threadId:H,body:K})}catch(F){throw await N(void 0),F}let U=crypto.randomUUID(),_=V.tools??[];try{if(V.mcp)_=[..._,...await E$(V.mcp,{user:z,sessionId:U})]}catch(F){return await N(F),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...V.session,tools:[...UJ($.delegate),...V.session?.tools??[],..._.map((F)=>F.tool)],...X===!0?{turnDetection:null}:{}},C;try{C=await $.realtime.createCall({sdp:Z,session:P,safetyIdentifier:V.safetyIdentifier})}catch(F){await N(F);let O=F instanceof WQ&&F.code==="rate_limited";return M(O?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=C.callId;try{await this.voiceStore.create({id:U,callId:C.callId,threadId:H,owner:await this.runOwner(J),body:K,startedAt:Y});let{threadId:F,session:O,safetyIdentifier:R,mcp:f,tools:x,...I}=V;return{sessionId:s.start({...I,tools:_,controller:this.constructor,threadId:H,user:z,body:K,call:{realtime:$.realtime,callId:C.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:P}).sessionId,sdp:C.sdpAnswer,threadId:H,delegate:$.delegate?.name??_J,endsAt:Y+(V.limits?.maxDurationMs??900000)}}catch(F){return await N(F),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new w){if(!this.voice)return i$();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await zJ(J,AJ);if(Q.error)return m(Q);let Z=aJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),s.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new w){let $=this.voice;if(!$)return i$();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Q.body}),Q.endedAt!==void 0)return{ended:!1};let Z=s.get(Q.id);if(Z)await Z.end("hangup");else await $.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let $=J.params?.sessionId,Q=typeof $==="string"&&$?await this.voiceStore.get($):null;if(!Q)return M(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return a();return Q}async upload(J=new w){let $=await J.rawRequest.formData(),Q=$.get("file");if(!(Q instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=Q instanceof File&&Q.name?Q.name:"upload",W=Q.type||"application/octet-stream",X=X6($.get("body")),K=$.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof K==="string"&&K.length>0?K:void 0,body:X});let G=G6(await this.attachmentLimits(J),Q,Z,W);if(G)throw new e$(G.code,G.message);await this.scopeStore(J,X);let z=typeof K==="string"&&K.length>0&&await this.store.loadThread(K)!==null?K:void 0,V=await this.runOwner(J),Y=null,D=(x)=>this.fileOwners.record(x,{owner:V,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),...Y}),N={body:X,threadId:z},H=await this.checkUpload({name:Z,size:Q.size,mimeType:W},J,N);if(H)throw new e$(H.code||"upload_refused",H.message);let U=await this.attachmentDestination(Q,J,N),_=O6(U,$.get("destination")),P=await this.attachmentScope(J,z,{body:X});Y=sJ(await this.attachmentRetention(J,{route:"upload",threadId:z,body:X}),this.turnAttachmentMaxAgeMs);let C=_!=="provider"&&!P;if(C){if(_==="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()`.');L6()}if(_==="provider"||!P){let x=await sZ(this.agent.provider,Q);await D(x);let I={fileId:x,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(C)I.downgraded="no_scope";return I}let F=_8(),O=await this.attachmentStorage.put({name:O8(F,Z),body:Q,contentType:W}),R=_==="both"?await sZ(this.agent.provider,Q):void 0;if(R)await D(R);let f={id:F,scopeKey:P.key,fileId:R,objectName:O,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:_,...Y};return await this.attachments.put(P,f),{fileId:R,attachmentId:F,name:Z,mimeType:W,size:Q.size,destination:_}}async foreignFile(J,$){let Q=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of Q){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return C6()}return null}onMessage(J,$){return this.hooks?.onMessage?.(J,$)}onToolCall(J,$){return this.hooks?.onToolCall?.(J,$)}onToolResult(J,$,Q){return this.hooks?.onToolResult?.(J,$,Q)}onAwaitingInput(J,$){return this.hooks?.onAwaitingInput?.(J,$)}redactError(J,$,Q){let Z=this.hooks?.redactError;if(Z)return Z(J,$,Q);return QQ(J,$)}onError(J,$){return this.hooks?.onError?.(J,$)}onProviderRetry(J,$){return this.hooks?.onProviderRetry?.(J,$)}onStreamComplete(J,$){return this.hooks?.onStreamComplete?.(J,$)}reportHookFailure(J){let $=this.hooks?.reportHookFailure;if($)try{return $(J)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,$){switch(J.type){case"tool-call":if(!J.part.partial&&!J.resent)await this.onToolCall({toolCallId:J.part.toolCallId,name:String(J.part.name),input:J.part.input},$);return;case"tool-result":{let Q=J.part;await this.onToolResult(Q,$,{toolCallId:Q.toolCallId,name:String(Q.name),input:A8(Q)});return}case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(F8(J.error),$);return;default:return}}async readThread(J,$={}){let Z=await($.scope===null||$.scope===void 0?this.store:W8(this.store,$.scope)).loadThread(J);if(!Z)return null;let{messages:W}=await this.settleThread(J,Z,{write:!1});return W}isRunLive(J,$){return this.liveRuns.get(J)!==null}async settleThread(J,$,{write:Q}){let Z=(z)=>this.isRunLive(z,J),W=await IZ($,Z),X=W.messages,K=[],G=new Map(W.settled.map((z)=>[z.id,z]));if(A6(X)||Q)try{let z=await bZ(X,{threadId:J,store:i.store,isRunLive:Z,outputSchemaFor:(V)=>this.toolNamed(V)?.outputSchema,modelOutputFor:(V,Y)=>M8(this.toolNamed(V),Y,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});X=z.messages,K=z.jobs;for(let V of z.settled)G.set(V.id,V);if(Q&&z.orphans.length>0){await vZ(i.store,z.orphans,(Y)=>this.reportHookFailure(Y));let V=new Set(z.orphans.map((Y)=>Y.id));K=K.map((Y)=>V.has(Y.id)?{...Y,orphaned:!0}:Y)}}catch(z){this.reportHookFailure(z)}if(Q&&G.size>0)try{await this.store.appendMessages(J,[...G.values()])}catch(z){this.reportHookFailure(z)}return{messages:X,jobs:K}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??qJ}jobsBlock(J){return NQ(J,this.jobsBlockMax())}toolNamed(J){let $=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let X=$(W.tools);if(X)return X}else if(W.name===J)return W}return};return $(this.agent.tools??[])}follow(J,$){(async()=>{try{for await(let Q of J.frames())$.frame(Q)}catch(Q){this.reportHookFailure(Q)}})()}persistRun(J,$,Q,Z=null,W={id:null,notified:Promise.resolve()},X=null){let K=(Y)=>X?Y.then(()=>this.safely(X)):Y,G=Promise.resolve(),z=(async()=>{let Y;try{Y=await J.result()}catch(N){Z?.close(),await Z?.settled(),G=K(W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:N instanceof Error?N.message:String(N),retryable:!1},$))));return}let D=Y.messages;if(Z?.close(D),await Z?.settled(),$.threadId&&D.length>0)try{await this.store.appendMessages($.threadId,D)}catch(N){this.reportHookFailure(N)}G=K(this.notifyRun(Y,D,$,W))})(),V=z.then(()=>S6(Promise.all([G,Q]).then(()=>{}),this.hookHoldMs));return{stored:z,hooks:V}}async notifyRun(J,$,Q,Z){await Z.notified;for(let W of $){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete(J,Q))}async safely(J){try{await J()}catch($){this.reportHookFailure($)}}}var t$=["turn","clientRunId","threadId","messages","regenerate","ifBusy"],W6=["text","files","toolResults"];function aJ(J,$=j8(J)?t$:[...t$,...W6]){let Q={};for(let[Z,W]of Object.entries(J)){if($.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function X6(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new r$("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new r$("The upload's `body` field must be a JSON object.");return aJ($,t$)}class r$ extends rJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function sZ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof B8&&K6.has(Q.status))throw new T8(XJ(Q).message);throw Q}}var K6=new Set([400,413,415,422]);class e$ extends rJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function G6(J,$,Q,Z){if(!J)return null;let{maxBytes:W,accept:X}=J;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${aZ($.size)}; the limit is ${aZ(W)}.`};if(X&&X.length>0&&!X.some((K)=>V6(K,Q,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify(Q)} is not a type this chat accepts. Accepted: ${X.join(", ")}.`};return null}function V6(J,$,Q){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return $.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function aZ(J){if(J<1024)return`${J} B`;let $=["KB","MB","GB"],Q=J/1024,Z=0;while(Q>=1024&&Z<$.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${$[Z]}`}class T8 extends rJ{constructor(J){super(J);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(J)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:J}}},view:{}}}}async function zJ(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!z6(Q.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number(Q.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>$)return tZ($);let W;try{let K=await Y6(Q,$);if(K===null)return tZ($);W=K}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let X;try{X=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(X===null||typeof X!=="object"||Array.isArray(X))return{body:{},error:"The request body must be a JSON object."};return{body:X}}function z6(J){return V8(J)==="application/json"}async function Y6(J,$){if(!Number.isFinite($)||!J.body)return await J.text();let Q=J.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:z}=await Q.read();if(G)break;if(W+=z.byteLength,W>$)return await Q.cancel().catch(T),null;Z.push(z)}let X=new Uint8Array(W),K=0;for(let G of Z)X.set(G,K),K+=G.byteLength;return new TextDecoder().decode(X)}function tZ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function RJ(J,$,Q){return M(J,{...eJ(G8(J),Q,J),code:$})}function m(J){if(J.status===413)return RJ(413,J.code??"body_too_large",J.error??"");return M(J.status??400,{code:J.code??"invalid_request",message:J.error})}function j8(J){return Boolean(J.turn)&&typeof J.turn==="object"}function D6(J){let $=j8(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=H6($.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray($.toolResults))Q.toolResults=$.toolResults;if(Object.keys(Q).length===0)return{};if($===J.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:Z}=$;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>rZ)return{error:`turn.localId is longer than ${rZ} characters.`};Q.localId=Z}return{turn:Q}}var rZ=200;function H6(J){let $=[];for(let[Q,Z]of J.entries()){let W=`turn.files[${Q}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let X={};for(let Y of["fileId","attachmentId","name","mimeType"]){let D=Z[Y];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${Y} must be a string.`;X[Y]=D}let{fileId:K,attachmentId:G,name:z,mimeType:V}=X;if(K?.startsWith(oJ))return`${W}.fileId holds a gemi attachment id (${K}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(G!==void 0&&!G.startsWith(oJ))return`${W}.attachmentId is not a gemi attachment id: it must start with "${oJ}".`;if(!K&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...K?{fileId:K}:{},...G?{attachmentId:G}:{},...z!==void 0?{name:z}:{},...V!==void 0?{mimeType:V}:{}})}return $}function P6(J,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let Z=Math.floor($.cursor);if(Z>=0)return Z+1;return}let Q=J?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function eZ(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function N6(J){let $=ZQ(J);for(let Q=J.length-1;Q>=0;Q--){let Z=J[Q];if(Z.role!=="user"||$.has(Z.id))continue;let W="",X=[];for(let K of Z.content){if(K.type==="text")W+=K.text;if(K.type==="file")X.push({...K.fileId?{fileId:K.fileId}:{},...K.attachmentId?{attachmentId:K.attachmentId}:{},...K.name?{name:K.name}:{},...K.mimeType?{mimeType:K.mimeType}:{}})}if(!W&&X.length===0)continue;return{index:Q,turn:{...W?{text:W}:{},...X.length>0?{files:X}:{}}}}return null}function J8(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function F6(J){let $=J.event;if(J.text!==void 0||J.turn!==void 0)throw TypeError("AgentController.startTurn takes an `event` or a `text`/`turn`, not both: an event is not a person's message.");if(typeof $!=="object"||$===null||typeof $.name!=="string"||!m9.test($.name))throw TypeError('AgentController.startTurn\'s `event.name` must be letters, digits and `.`, `_`, `:`, `-` (at most 64), like "job-settled".');if($.text!==void 0&&typeof $.text!=="string")throw TypeError("AgentController.startTurn's `event.text` must be a string.");let Q;if($.data!==void 0)try{Q=JSON.parse(JSON.stringify($.data))}catch(Z){throw TypeError(`AgentController.startTurn's \`event.data\` is not JSON: ${String(Z)}`)}return{name:$.name,...$.text?{text:$.text}:{},...Q!==void 0?{data:Q}:{}}}function $8(J){return M(409,{code:E8,message:`Thread ${J} has a run going, and this turn was not to interrupt it.`})}function a(){return M(403,eJ("permission","This run belongs to someone else.",403))}function C6(){return M(403,eJ("permission","A file in this turn was uploaded by someone else.",403))}function U6(J){if(!Array.isArray(J))return[];let $=[];for(let Q of J){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}var _6=["sdp","threadId","pushToTalk"];function i$(){return M(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function M(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function O6(J,$){if(typeof $!=="string"||$.length===0)return J;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===J||J==="both"&&$==="storage")return $;if(J==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${J}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var Q8=!1;function L6(){if(Q8)return;Q8=!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 B6=2147483647;function S6(J,$){let Q=J.then(()=>{},()=>{});if(!($<=B6))return Q;let Z,W=new Promise((X)=>{Z=setTimeout(X,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var Z8=!1;function M6(J){if(Z8||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof JQ))return;Z8=!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 A6(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}function W8(J,$){if(typeof $!=="string"||$==="")throw TypeError("A store scope is a non-empty string.");if(!J.forScope)throw Error("This controller's store cannot be scoped: storeScope() or a turn's `scope` needs a store that implements `forScope` (DatabaseAgentStore or MemoryAgentStore).");return J.forScope($)}function X8(J,$=!1){if($)return new Response(null,{status:204});return M(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`})}export{q6 as windowMessages,UJ as voiceTools,j6 as turnStarts,$0 as toRealtimeUsage,Q9 as toAgentTools,k6 as supportsStrict,x6 as splitTurns,u6 as settleSummaries,E6 as s,QQ as redactError,r6 as parsePartialJson,I6 as messageSize,FJ as measureUsage,E$ as mcpVoiceTools,I$ as liveRuns,OJ as keepSummary,Z0 as isCallNotFound,ZQ as injectedMessageIds,F$ as generate,P9 as evalChain,Z6 as defineAgentHooks,T$ as defaultVoiceStore,p6 as defaultUsageLimitStore,c6 as defaultSummaryStore,t6 as defaultPromptCacheKey,$Q as defaultNonceStore,w$ as defaultFileOwners,$$ as defaultAttachmentStore,h$ as defaultAgentStore,lJ as VoiceHangup,s as VoiceBridge,T6 as Usage,U$ as ToolNamespace,o as ToolError,s6 as ToolArgumentsTooLongError,i6 as Skill,J$ as ScopedAttachments,d6 as SKILLS_NAMESPACE,v$ as RedisReceiptStore,P8 as RedisNonceStore,e6 as RealtimeSideband,WQ as RealtimeRequestError,Q0 as RealtimeClient,DQ as Prompt,N8 as PrismaNonceStore,l6 as PendingEscalation,W0 as OpenAIProvider,B$ as OpenAIImageProvider,k$ as MemoryVoiceSessionStore,m6 as MemoryUsageLimitStore,g6 as MemorySummaryStore,b$ as MemoryReceiptStore,JQ as MemoryNonceStore,iJ as MemoryLiveRuns,dJ as MemoryFileOwners,mJ as MemoryCircuitStore,L8 as MemoryAttachmentStore,BJ as MemoryAgentStore,_Q as MemoryAgentJobStore,bQ as MEMORY_NAMESPACE,LJ as LiveRunNotFoundError,LQ as JobsRequireThreadError,OQ as JobHandle,R6 as JSONSchemaError,U8 as InvalidAttachmentScopeError,jQ as InMemoryAgentMemoryStore,cJ as ImageRequestError,uJ as ImageProvider,_$ as ImageModel,VJ as FrameCursorEvictedError,CJ as FallbackProvider,fQ as FakeAgentMemoryStore,hJ as Eval,j$ as DatabaseAgentStore,z$ as DatabaseAgentMemoryStore,G$ as DatabaseAgentJobStore,J0 as DEFAULT_TRANSCRIPTION_MODEL,TQ as DEFAULT_MEMORY_MAX_TOKENS,qQ as DEFAULT_MEMORY_LIMITS,b6 as DEFAULT_MAX_SUMMARY_TOKENS,n6 as DEFAULT_MAX_RUN_DURATION_MS,BQ as DEFAULT_JOB_DEADLINE_MS,qJ as DEFAULT_JOBS_CONTEXT_MAX,_J as DEFAULT_DELEGATE_NAME,w6 as DEFAULT_CONTEXT_WINDOW_STEP,f6 as DEFAULT_CONTEXT_WINDOW_NOTE,v6 as DEFAULT_COMPACT_TRIGGER_TOKENS,y6 as DEFAULT_COMPACT_INSTRUCTIONS,h6 as COMPACT_SUMMARY_HEADER,G0 as AzureOpenAIProvider,S$ as AzureOpenAIImageProvider,K0 as AzureAnthropicProvider,C8 as AttachmentNotFoundError,X0 as AnthropicProvider,YJ as AgentTurnError,gJ as AgentTool,o6 as AgentRunError,R$ as AgentProvider,xQ as AgentMemoryRefusedError,IQ as AgentMemoryConflictError,wQ as AgentMemories,i as AgentJobs,K$ as AgentJobDeadlineSweep,SQ as AgentJob,tJ as AgentController,a6 as Agent};
337
337
 
338
- //# debugId=F1658A2AB744EC0C64756E2164756E21
338
+ //# debugId=50ACED55E0D0299864756E2164756E21