gemi 0.123.0 → 0.125.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 (316) hide show
  1. package/dist/ai/AgentController.d.ts +185 -3
  2. package/dist/ai/AgentController.d.ts.map +1 -1
  3. package/dist/ai/client/index.d.ts +1 -1
  4. package/dist/ai/client/index.d.ts.map +1 -1
  5. package/dist/ai/client/index.js +38 -9
  6. package/dist/ai/client/index.js.map +1 -1
  7. package/dist/ai/client/reducer.d.ts.map +1 -1
  8. package/dist/ai/index.d.ts +2 -2
  9. package/dist/ai/index.d.ts.map +1 -1
  10. package/dist/ai/index.js +31 -48
  11. package/dist/ai/index.js.map +6 -15
  12. package/dist/ai/types.d.ts +26 -0
  13. package/dist/ai/types.d.ts.map +1 -1
  14. package/dist/ai/useChat.d.ts +35 -2
  15. package/dist/ai/useChat.d.ts.map +1 -1
  16. package/dist/app/index.js +1 -1
  17. package/dist/auth/AuthController.d.ts.map +1 -1
  18. package/dist/auth/AuthManager.d.ts +11 -0
  19. package/dist/auth/AuthManager.d.ts.map +1 -1
  20. package/dist/auth/AuthServiceProvider.d.ts +2 -0
  21. package/dist/auth/AuthServiceProvider.d.ts.map +1 -1
  22. package/dist/auth/config.d.ts +71 -2
  23. package/dist/auth/config.d.ts.map +1 -1
  24. package/dist/auth/oauth/providers.d.ts +10 -0
  25. package/dist/auth/oauth/providers.d.ts.map +1 -0
  26. package/dist/bun/plugin.js +1 -1
  27. package/dist/bun/preload.js +1 -1
  28. package/dist/{chunk-fyk07w01.js → chunk-0x1s02r1.js} +3 -3
  29. package/dist/{chunk-fyk07w01.js.map → chunk-0x1s02r1.js.map} +1 -1
  30. package/dist/{chunk-ycsrpf47.js → chunk-1jcngq6w.js} +3 -3
  31. package/dist/{chunk-ycsrpf47.js.map → chunk-1jcngq6w.js.map} +1 -1
  32. package/dist/{chunk-gwnmgkq5.js → chunk-1mxb44n9.js} +2 -2
  33. package/dist/{chunk-gwnmgkq5.js.map → chunk-1mxb44n9.js.map} +1 -1
  34. package/dist/{chunk-y67evsdy.js → chunk-1n40bdxf.js} +2 -2
  35. package/dist/{chunk-y67evsdy.js.map → chunk-1n40bdxf.js.map} +1 -1
  36. package/dist/chunk-1xmh61fg.js +5 -0
  37. package/dist/{chunk-tazvfppr.js.map → chunk-1xmh61fg.js.map} +1 -1
  38. package/dist/{chunk-sxa70wgn.js → chunk-3br5zr7a.js} +3 -3
  39. package/dist/{chunk-sxa70wgn.js.map → chunk-3br5zr7a.js.map} +1 -1
  40. package/dist/{chunk-w61sphn5.js → chunk-3kxe9geg.js} +3 -3
  41. package/dist/{chunk-w61sphn5.js.map → chunk-3kxe9geg.js.map} +1 -1
  42. package/dist/{chunk-w0jfqnw9.js → chunk-5fh4pvyt.js} +2 -2
  43. package/dist/{chunk-w0jfqnw9.js.map → chunk-5fh4pvyt.js.map} +1 -1
  44. package/dist/{chunk-hnrzm5pf.js → chunk-6gwxvmjv.js} +3 -3
  45. package/dist/{chunk-hnrzm5pf.js.map → chunk-6gwxvmjv.js.map} +1 -1
  46. package/dist/{chunk-j0cnsgjq.js → chunk-6q6bhkyf.js} +1 -1
  47. package/dist/{chunk-5a4qbtez.js → chunk-6vz75swk.js} +2 -2
  48. package/dist/{chunk-5a4qbtez.js.map → chunk-6vz75swk.js.map} +1 -1
  49. package/dist/chunk-6wgh7nk6.js +15 -0
  50. package/dist/{chunk-z23h4s1a.js.map → chunk-6wgh7nk6.js.map} +6 -5
  51. package/dist/chunk-7vrrgxwm.js +22 -0
  52. package/dist/chunk-7vrrgxwm.js.map +21 -0
  53. package/dist/{chunk-kvas36p6.js → chunk-7zj6bk9a.js} +2 -2
  54. package/dist/{chunk-kvas36p6.js.map → chunk-7zj6bk9a.js.map} +1 -1
  55. package/dist/{chunk-kdjhgtp9.js → chunk-8tvfmy1a.js} +4 -4
  56. package/dist/{chunk-kdjhgtp9.js.map → chunk-8tvfmy1a.js.map} +1 -1
  57. package/dist/{chunk-vd6zn8c4.js → chunk-910p6ne6.js} +2 -2
  58. package/dist/{chunk-vd6zn8c4.js.map → chunk-910p6ne6.js.map} +1 -1
  59. package/dist/{chunk-96a1459v.js → chunk-ap3g6rbw.js} +2 -2
  60. package/dist/{chunk-96a1459v.js.map → chunk-ap3g6rbw.js.map} +1 -1
  61. package/dist/{chunk-4qpypa3h.js → chunk-ayfjjgv2.js} +1 -1
  62. package/dist/chunk-b4x1dt3s.js +10 -0
  63. package/dist/chunk-b4x1dt3s.js.map +43 -0
  64. package/dist/{chunk-aafanq8n.js → chunk-b7a22evs.js} +3 -3
  65. package/dist/{chunk-aafanq8n.js.map → chunk-b7a22evs.js.map} +1 -1
  66. package/dist/{chunk-rjtmgbay.js → chunk-bny9s44t.js} +2 -2
  67. package/dist/{chunk-rjtmgbay.js.map → chunk-bny9s44t.js.map} +1 -1
  68. package/dist/{chunk-k17wx7gz.js → chunk-by5gwr8x.js} +2 -2
  69. package/dist/{chunk-k17wx7gz.js.map → chunk-by5gwr8x.js.map} +1 -1
  70. package/dist/{chunk-53hc0ah1.js → chunk-c0qpv8x7.js} +2 -2
  71. package/dist/{chunk-53hc0ah1.js.map → chunk-c0qpv8x7.js.map} +1 -1
  72. package/dist/{chunk-9t08wbkd.js → chunk-cpem1j1x.js} +2 -2
  73. package/dist/{chunk-9t08wbkd.js.map → chunk-cpem1j1x.js.map} +1 -1
  74. package/dist/{chunk-vwnd4jb5.js → chunk-crnfxn9n.js} +2 -2
  75. package/dist/{chunk-vwnd4jb5.js.map → chunk-crnfxn9n.js.map} +1 -1
  76. package/dist/{chunk-s5jxc63j.js → chunk-cwt8e782.js} +3 -3
  77. package/dist/{chunk-s5jxc63j.js.map → chunk-cwt8e782.js.map} +1 -1
  78. package/dist/{chunk-0tc0j3pf.js → chunk-dxyxd7b3.js} +2 -2
  79. package/dist/{chunk-0tc0j3pf.js.map → chunk-dxyxd7b3.js.map} +1 -1
  80. package/dist/{chunk-nf608sb1.js → chunk-dy58aztm.js} +2 -2
  81. package/dist/{chunk-nf608sb1.js.map → chunk-dy58aztm.js.map} +1 -1
  82. package/dist/chunk-entpqjyn.js +5 -0
  83. package/dist/chunk-entpqjyn.js.map +10 -0
  84. package/dist/{chunk-qen6587t.js → chunk-eq5svwca.js} +2 -2
  85. package/dist/{chunk-qen6587t.js.map → chunk-eq5svwca.js.map} +1 -1
  86. package/dist/{chunk-n1a2zj5z.js → chunk-erzfs4t2.js} +2 -2
  87. package/dist/{chunk-n1a2zj5z.js.map → chunk-erzfs4t2.js.map} +3 -3
  88. package/dist/{chunk-pfm9ngch.js → chunk-ex41d03h.js} +2 -2
  89. package/dist/{chunk-pfm9ngch.js.map → chunk-ex41d03h.js.map} +1 -1
  90. package/dist/{chunk-fxxbwyce.js → chunk-ey1xrbaz.js} +2 -2
  91. package/dist/{chunk-fxxbwyce.js.map → chunk-ey1xrbaz.js.map} +1 -1
  92. package/dist/chunk-eyptwf54.js +57 -0
  93. package/dist/{chunk-gvp6brdt.js.map → chunk-eyptwf54.js.map} +25 -22
  94. package/dist/{chunk-x0jahbqj.js → chunk-g52fcwca.js} +2 -2
  95. package/dist/{chunk-x0jahbqj.js.map → chunk-g52fcwca.js.map} +1 -1
  96. package/dist/{chunk-hs88b8gt.js → chunk-ghcvztxn.js} +2 -2
  97. package/dist/{chunk-hs88b8gt.js.map → chunk-ghcvztxn.js.map} +1 -1
  98. package/dist/{chunk-rjm1kj8n.js → chunk-gp00enrk.js} +1 -1
  99. package/dist/{chunk-08fcqny0.js → chunk-h8w9mzjj.js} +6 -6
  100. package/dist/{chunk-08fcqny0.js.map → chunk-h8w9mzjj.js.map} +7 -7
  101. package/dist/{chunk-9p7eq7bz.js → chunk-hff9w6rt.js} +2 -2
  102. package/dist/{chunk-9p7eq7bz.js.map → chunk-hff9w6rt.js.map} +1 -1
  103. package/dist/{chunk-ay8nat73.js → chunk-hxn0s3zh.js} +2 -2
  104. package/dist/{chunk-ay8nat73.js.map → chunk-hxn0s3zh.js.map} +1 -1
  105. package/dist/{chunk-de7hxe73.js → chunk-hzen9gh4.js} +2 -2
  106. package/dist/{chunk-de7hxe73.js.map → chunk-hzen9gh4.js.map} +1 -1
  107. package/dist/{chunk-xhmtph39.js → chunk-j10a0m7q.js} +1 -1
  108. package/dist/{chunk-wqharhrp.js → chunk-j12hpdxk.js} +1 -1
  109. package/dist/{chunk-bk2aheea.js → chunk-j5rwv09s.js} +2 -2
  110. package/dist/{chunk-bk2aheea.js.map → chunk-j5rwv09s.js.map} +1 -1
  111. package/dist/{chunk-zjej5vqh.js → chunk-jykkqwcy.js} +3 -3
  112. package/dist/{chunk-zjej5vqh.js.map → chunk-jykkqwcy.js.map} +1 -1
  113. package/dist/{chunk-9a9ef0f1.js → chunk-k1ebt28j.js} +2 -2
  114. package/dist/{chunk-9a9ef0f1.js.map → chunk-k1ebt28j.js.map} +1 -1
  115. package/dist/{chunk-q1e3q01h.js → chunk-kcsa57km.js} +2 -2
  116. package/dist/{chunk-q1e3q01h.js.map → chunk-kcsa57km.js.map} +1 -1
  117. package/dist/{chunk-r5tadf14.js → chunk-khdkrfxp.js} +2 -2
  118. package/dist/{chunk-r5tadf14.js.map → chunk-khdkrfxp.js.map} +1 -1
  119. package/dist/{chunk-fsy344zb.js → chunk-knq4ack4.js} +2 -2
  120. package/dist/{chunk-fsy344zb.js.map → chunk-knq4ack4.js.map} +1 -1
  121. package/dist/{chunk-f1thqe6j.js → chunk-m7pghdcy.js} +2 -2
  122. package/dist/{chunk-f1thqe6j.js.map → chunk-m7pghdcy.js.map} +1 -1
  123. package/dist/{chunk-enta97jb.js → chunk-mmqnq1qh.js} +3 -3
  124. package/dist/{chunk-enta97jb.js.map → chunk-mmqnq1qh.js.map} +1 -1
  125. package/dist/{chunk-0qmc7snf.js → chunk-n3z83qhq.js} +2 -2
  126. package/dist/{chunk-0qmc7snf.js.map → chunk-n3z83qhq.js.map} +1 -1
  127. package/dist/{chunk-mxbtcaed.js → chunk-npbf06c1.js} +2 -2
  128. package/dist/{chunk-mxbtcaed.js.map → chunk-npbf06c1.js.map} +1 -1
  129. package/dist/{chunk-6gjvqtcp.js → chunk-p5df4pn7.js} +2 -2
  130. package/dist/{chunk-6gjvqtcp.js.map → chunk-p5df4pn7.js.map} +1 -1
  131. package/dist/{chunk-ywgvxx35.js → chunk-p6jbmcrg.js} +2 -2
  132. package/dist/{chunk-ywgvxx35.js.map → chunk-p6jbmcrg.js.map} +1 -1
  133. package/dist/{chunk-d3ywmeb7.js → chunk-p7mvp5nf.js} +2 -2
  134. package/dist/{chunk-d3ywmeb7.js.map → chunk-p7mvp5nf.js.map} +1 -1
  135. package/dist/{chunk-52xkw2bs.js → chunk-q6ah4yjg.js} +2 -2
  136. package/dist/{chunk-52xkw2bs.js.map → chunk-q6ah4yjg.js.map} +1 -1
  137. package/dist/{chunk-6pxavyh3.js → chunk-r923001x.js} +2 -2
  138. package/dist/{chunk-6pxavyh3.js.map → chunk-r923001x.js.map} +1 -1
  139. package/dist/{chunk-1f1sb3w7.js → chunk-rany5zgk.js} +2 -2
  140. package/dist/{chunk-1f1sb3w7.js.map → chunk-rany5zgk.js.map} +1 -1
  141. package/dist/{chunk-30xxc6r7.js → chunk-rmgkc3a2.js} +2 -2
  142. package/dist/{chunk-30xxc6r7.js.map → chunk-rmgkc3a2.js.map} +1 -1
  143. package/dist/{chunk-ebx5hnqn.js → chunk-rvspb96n.js} +3 -3
  144. package/dist/{chunk-ebx5hnqn.js.map → chunk-rvspb96n.js.map} +1 -1
  145. package/dist/{chunk-kzstewtm.js → chunk-rwmja4zs.js} +2 -2
  146. package/dist/{chunk-kzstewtm.js.map → chunk-rwmja4zs.js.map} +1 -1
  147. package/dist/{chunk-8x73yyfs.js → chunk-s4semb89.js} +1 -1
  148. package/dist/chunk-s4xg69r9.js +24 -0
  149. package/dist/{chunk-vpgbn494.js.map → chunk-s4xg69r9.js.map} +2 -2
  150. package/dist/{chunk-58ffbwdc.js → chunk-stn0a56e.js} +2 -2
  151. package/dist/{chunk-58ffbwdc.js.map → chunk-stn0a56e.js.map} +1 -1
  152. package/dist/{chunk-73v34hw8.js → chunk-sv125fqq.js} +2 -2
  153. package/dist/{chunk-73v34hw8.js.map → chunk-sv125fqq.js.map} +1 -1
  154. package/dist/{chunk-h76mddt3.js → chunk-t2t63wa0.js} +2 -2
  155. package/dist/{chunk-h76mddt3.js.map → chunk-t2t63wa0.js.map} +1 -1
  156. package/dist/{chunk-675kzd7z.js → chunk-t6qpm2j7.js} +2 -2
  157. package/dist/{chunk-675kzd7z.js.map → chunk-t6qpm2j7.js.map} +1 -1
  158. package/dist/chunk-tabsxzg9.js +5 -0
  159. package/dist/chunk-tabsxzg9.js.map +13 -0
  160. package/dist/{chunk-2vc72qez.js → chunk-vhvvjaj3.js} +3 -3
  161. package/dist/{chunk-2vc72qez.js.map → chunk-vhvvjaj3.js.map} +1 -1
  162. package/dist/{chunk-2amj1eyp.js → chunk-x2j84d06.js} +2 -2
  163. package/dist/{chunk-2amj1eyp.js.map → chunk-x2j84d06.js.map} +1 -1
  164. package/dist/{chunk-dmj6ysym.js → chunk-xe2pm36q.js} +2 -2
  165. package/dist/{chunk-dmj6ysym.js.map → chunk-xe2pm36q.js.map} +1 -1
  166. package/dist/{chunk-rkgsvsrj.js → chunk-xfvegbxn.js} +2 -2
  167. package/dist/{chunk-rkgsvsrj.js.map → chunk-xfvegbxn.js.map} +1 -1
  168. package/dist/{chunk-nvngb4ed.js → chunk-y9f2see3.js} +3 -3
  169. package/dist/{chunk-nvngb4ed.js.map → chunk-y9f2see3.js.map} +1 -1
  170. package/dist/{chunk-1kdga1b2.js → chunk-yhht1j7f.js} +2 -2
  171. package/dist/{chunk-1kdga1b2.js.map → chunk-yhht1j7f.js.map} +1 -1
  172. package/dist/{chunk-eevna943.js → chunk-z5nfve1k.js} +2 -2
  173. package/dist/chunk-z5nfve1k.js.map +10 -0
  174. package/dist/{chunk-j8vc3bze.js → chunk-zq5375wd.js} +3 -3
  175. package/dist/{chunk-j8vc3bze.js.map → chunk-zq5375wd.js.map} +1 -1
  176. package/dist/chunks/{ThemeProvider-CgK2mmVV.js → ThemeProvider-CS2a1snV.js} +34 -3
  177. package/dist/chunks/ThemeProvider-CS2a1snV.js.map +1 -0
  178. package/dist/client/Mutation.d.ts +7 -6
  179. package/dist/client/Mutation.d.ts.map +1 -1
  180. package/dist/client/MutationError.d.ts +53 -1
  181. package/dist/client/MutationError.d.ts.map +1 -1
  182. package/dist/client/QueryResource.d.ts +9 -0
  183. package/dist/client/QueryResource.d.ts.map +1 -1
  184. package/dist/client/auth/useEmailCode.d.ts +3 -3
  185. package/dist/client/auth/useForgotPassword.d.ts +1 -1
  186. package/dist/client/auth/useResetPassword.d.ts +1 -1
  187. package/dist/client/auth/useSignIn.d.ts +1 -1
  188. package/dist/client/auth/useSignOut.d.ts +1 -1
  189. package/dist/client/auth/useSignUp.d.ts +1 -1
  190. package/dist/client/index.d.ts +4 -2
  191. package/dist/client/index.d.ts.map +1 -1
  192. package/dist/client/index.js +136 -9
  193. package/dist/client/index.js.map +1 -1
  194. package/dist/client/realtime/RealtimeClient.d.ts +8 -1
  195. package/dist/client/realtime/RealtimeClient.d.ts.map +1 -1
  196. package/dist/client/useMutation.d.ts +18 -8
  197. package/dist/client/useMutation.d.ts.map +1 -1
  198. package/dist/client/useSetQueryData.d.ts +69 -0
  199. package/dist/client/useSetQueryData.d.ts.map +1 -0
  200. package/dist/config/index.js +1 -1
  201. package/dist/console/run.js +2 -2
  202. package/dist/console/run.js.map +1 -1
  203. package/dist/container/index.js +2 -2
  204. package/dist/container/index.js.map +1 -1
  205. package/dist/database/index.js +2 -2
  206. package/dist/database/index.js.map +1 -1
  207. package/dist/email/index.js +2 -2
  208. package/dist/email/index.js.map +1 -1
  209. package/dist/facades/Auth.d.ts +29 -2
  210. package/dist/facades/Auth.d.ts.map +1 -1
  211. package/dist/facades/RateLimiter.d.ts +16 -1
  212. package/dist/facades/RateLimiter.d.ts.map +1 -1
  213. package/dist/facades/index.js +2 -2
  214. package/dist/facades/index.js.map +1 -1
  215. package/dist/foundation/index.js +2 -2
  216. package/dist/foundation/index.js.map +1 -1
  217. package/dist/http/HttpRequest.d.ts +14 -0
  218. package/dist/http/HttpRequest.d.ts.map +1 -1
  219. package/dist/http/McpRouter.d.ts +121 -2
  220. package/dist/http/McpRouter.d.ts.map +1 -1
  221. package/dist/http/RateLimitExceededError.d.ts +24 -0
  222. package/dist/http/RateLimitExceededError.d.ts.map +1 -0
  223. package/dist/http/RateLimitMiddleware.d.ts +2 -5
  224. package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
  225. package/dist/http/index.d.ts +2 -1
  226. package/dist/http/index.d.ts.map +1 -1
  227. package/dist/http/index.js +2 -2
  228. package/dist/http/index.js.map +1 -1
  229. package/dist/http/refusal.d.ts +6 -1
  230. package/dist/http/refusal.d.ts.map +1 -1
  231. package/dist/http/requestContext.d.ts +3 -1
  232. package/dist/http/requestContext.d.ts.map +1 -1
  233. package/dist/http/requestState.d.ts +57 -0
  234. package/dist/http/requestState.d.ts.map +1 -0
  235. package/dist/i18n/dictionaryRuntime.js +2 -2
  236. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  237. package/dist/i18n/index.js +2 -2
  238. package/dist/i18n/index.js.map +2 -2
  239. package/dist/kernel/index.js +2 -2
  240. package/dist/kernel/index.js.map +2 -2
  241. package/dist/orm/index.js +2 -2
  242. package/dist/orm/index.js.map +1 -1
  243. package/dist/server/Server.d.ts.map +1 -1
  244. package/dist/server/health.d.ts +67 -0
  245. package/dist/server/health.d.ts.map +1 -0
  246. package/dist/server/index.d.ts +1 -0
  247. package/dist/server/index.d.ts.map +1 -1
  248. package/dist/server/index.js +2 -2
  249. package/dist/server/index.js.map +5 -4
  250. package/dist/server/shutdown.d.ts +3 -4
  251. package/dist/server/shutdown.d.ts.map +1 -1
  252. package/dist/services/broadcast/BroadcastDriver.d.ts +3 -1
  253. package/dist/services/broadcast/BroadcastDriver.d.ts.map +1 -1
  254. package/dist/services/broadcast/BroadcastManager.d.ts.map +1 -1
  255. package/dist/services/broadcast/BroadcastServiceProvider.d.ts +10 -0
  256. package/dist/services/broadcast/BroadcastServiceProvider.d.ts.map +1 -1
  257. package/dist/services/broadcast/RedisBroadcastDriver.d.ts +155 -0
  258. package/dist/services/broadcast/RedisBroadcastDriver.d.ts.map +1 -0
  259. package/dist/services/broadcast/SocketHub.d.ts +9 -0
  260. package/dist/services/broadcast/SocketHub.d.ts.map +1 -1
  261. package/dist/services/broadcast/config.d.ts +16 -3
  262. package/dist/services/broadcast/config.d.ts.map +1 -1
  263. package/dist/services/broadcast/workerWarning.d.ts +10 -0
  264. package/dist/services/broadcast/workerWarning.d.ts.map +1 -0
  265. package/dist/services/features/gate.d.ts +11 -0
  266. package/dist/services/features/gate.d.ts.map +1 -0
  267. package/dist/services/index.d.ts +6 -5
  268. package/dist/services/index.d.ts.map +1 -1
  269. package/dist/services/index.js +3 -3
  270. package/dist/services/index.js.map +2 -2
  271. package/dist/services/logging/LogManager.d.ts +1 -0
  272. package/dist/services/logging/LogManager.d.ts.map +1 -1
  273. package/dist/services/logging/config.d.ts +23 -1
  274. package/dist/services/logging/config.d.ts.map +1 -1
  275. package/dist/services/logging/consoleSink.d.ts +25 -0
  276. package/dist/services/logging/consoleSink.d.ts.map +1 -0
  277. package/dist/services/mcp/McpRegistry.d.ts +106 -14
  278. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  279. package/dist/services/mcp/http/McpHttpServer.d.ts +41 -2
  280. package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -1
  281. package/dist/services/mcp/toAgentTools.d.ts +21 -3
  282. package/dist/services/mcp/toAgentTools.d.ts.map +1 -1
  283. package/dist/services/queue/WorkerProcess.d.ts.map +1 -1
  284. package/dist/services/queue/work.js +2 -2
  285. package/dist/services/queue/work.js.map +5 -4
  286. package/dist/services/rate-limiter/RateLimiter.d.ts +12 -0
  287. package/dist/services/rate-limiter/RateLimiter.d.ts.map +1 -1
  288. package/dist/services/router/globalMiddleware.d.ts +4 -3
  289. package/dist/services/router/globalMiddleware.d.ts.map +1 -1
  290. package/dist/stats/route-table.js +1 -1
  291. package/dist/support/index.js +2 -2
  292. package/dist/support/index.js.map +1 -1
  293. package/dist/testing/index.js +1 -1
  294. package/dist/vitest/index.js +1 -1
  295. package/package.json +1 -1
  296. package/skills/gemi-react-best-practices/SKILL.md +1 -1
  297. package/skills/gemi-react-best-practices/rules/query-mutate-over-refetch.md +14 -0
  298. package/skills/gemi-react-best-practices/rules/routing-middleware-dsl.md +2 -1
  299. package/dist/chunk-39dx7xrz.js +0 -10
  300. package/dist/chunk-39dx7xrz.js.map +0 -43
  301. package/dist/chunk-d0wr9jk4.js +0 -5
  302. package/dist/chunk-d0wr9jk4.js.map +0 -12
  303. package/dist/chunk-eevna943.js.map +0 -10
  304. package/dist/chunk-gvp6brdt.js +0 -57
  305. package/dist/chunk-kc924zjz.js +0 -5
  306. package/dist/chunk-kc924zjz.js.map +0 -12
  307. package/dist/chunk-tazvfppr.js +0 -5
  308. package/dist/chunk-vpgbn494.js +0 -24
  309. package/dist/chunk-z23h4s1a.js +0 -14
  310. package/dist/chunks/ThemeProvider-CgK2mmVV.js.map +0 -1
  311. /package/dist/{chunk-j0cnsgjq.js.map → chunk-6q6bhkyf.js.map} +0 -0
  312. /package/dist/{chunk-4qpypa3h.js.map → chunk-ayfjjgv2.js.map} +0 -0
  313. /package/dist/{chunk-rjm1kj8n.js.map → chunk-gp00enrk.js.map} +0 -0
  314. /package/dist/{chunk-xhmtph39.js.map → chunk-j10a0m7q.js.map} +0 -0
  315. /package/dist/{chunk-wqharhrp.js.map → chunk-j12hpdxk.js.map} +0 -0
  316. /package/dist/{chunk-8x73yyfs.js.map → chunk-s4semb89.js.map} +0 -0
package/dist/ai/index.js CHANGED
@@ -1,51 +1,34 @@
1
1
  // @bun
2
- import{$b as VZ,Ub as LQ,Vb as P6,Wb as C9,Zb as QZ,_b as ZZ,ac as GZ,bc as JZ,cc as WZ,dc as YZ,ec as XZ,fc as j,gc as F9,hc as KZ,ic as HZ,jc as N6}from"../chunk-d0wr9jk4.js";import{Ac as DZ}from"../chunk-675kzd7z.js";import{Gc as _Q,Rc as qQ}from"../chunk-08fcqny0.js";import{Xf as D6,Xg as w9,Zg as X9,_f as L6,_g as JQ,ah as $Z,ch as U6,og as l0,pg as v9,qg as W9,rg as M9}from"../chunk-z23h4s1a.js";import{dh as F6,fh as J$,gh as W$}from"../chunk-n1a2zj5z.js";import{kh as p9}from"../chunk-kc924zjz.js";import"../chunk-1f1sb3w7.js";import"../chunk-73v34hw8.js";import{Ai as OZ,li as NZ,mi as CZ}from"../chunk-2vc72qez.js";import"../chunk-mxbtcaed.js";import{nj as I9}from"../chunk-hnrzm5pf.js";import"../chunk-kzstewtm.js";import"../chunk-eevna943.js";import"../chunk-1kdga1b2.js";import"../chunk-ay8nat73.js";class h extends Error{status;body;requestId;constructor($,Q,Z){super(`Provider request failed with status ${$}: ${j6(Q)}`);this.name="ProviderHttpError",this.status=$,this.body=Q,this.requestId=Z}}class R9 extends Error{timeoutMs;constructor($){super(`Provider request timed out after ${$}ms`);this.name="ProviderTimeoutError",this.timeoutMs=$}}function j6($){let Q=PQ($);if(Q?.message)return Q.message;if(typeof $==="string")return $.slice(0,500);return"no error body"}function PQ($){if(!$||typeof $!=="object")return null;let Q=$,V=Q.error&&typeof Q.error==="object"?Q.error:$;if(typeof V.message!=="string"&&typeof V.code!=="string"&&typeof V.type!=="string")return null;let G=V.innererror?.code??V.code;return{message:V.message,type:V.type,code:G,param:V.param}}function b($){if(!$||typeof $!=="object")return{};let{status:Q,requestId:Z}=$;return{...typeof Q==="number"&&Q>=100&&Q<=599?{status:Q}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function I($){if($ instanceof R9)return{code:"provider_error",message:$.message,retryable:!0};if(k6($))return{code:"aborted",message:"The request was aborted.",retryable:!1};if($ instanceof h)return A6($.status,PQ($.body),$.message);if($ instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${$.message}`,retryable:!0};if($ instanceof Error)return{code:"provider_error",message:$.message,retryable:!1};return{code:"unknown",message:String($),retryable:!1}}function A6($,Q,Z){let V=Q?.message??Z,G=(Q?.code??"").toLowerCase(),J=(Q?.type??"").toLowerCase(),W=`${G} ${J} ${V}`.toLowerCase();if($===429){let X=G==="insufficient_quota"||W.includes("quota");return{code:"rate_limited",message:V,retryable:!X}}if($>=500||$===408||$===409)return{code:"provider_error",message:V,retryable:!0};if(T6(W))return{code:"context_length_exceeded",message:V,retryable:!1};if(E6(W))return{code:"content_filtered",message:V,retryable:!1};if(Q?.param?.startsWith("tools")||W.includes("invalid schema for function"))return{code:"invalid_tool_input",message:V,retryable:!1};return{code:"provider_error",message:V,retryable:!1}}function T6($){return $.includes("context_length_exceeded")||$.includes("maximum context length")||$.includes("context window")||$.includes("reduce the length")}function E6($){return $.includes("content_filter")||$.includes("content_policy_violation")||$.includes("responsibleaipolicyviolation")||$.includes("content management policy")}function k6($){if(!$||typeof $!=="object")return!1;let Q=$;return Q.name==="AbortError"||Q.code==="ABORT_ERR"}class w extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function c($,Q){if(Q.aborted)return Promise.reject(new w);return new Promise((Z,V)=>{let G=()=>V(new w);Q.addEventListener("abort",G,{once:!0}),$.then(Z,V).finally(()=>Q.removeEventListener("abort",G))})}function R(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function M($,Q){if(!Q)return $;let Z={inputTokens:$.inputTokens+(Q.inputTokens??0),outputTokens:$.outputTokens+(Q.outputTokens??0),totalTokens:$.totalTokens+(Q.totalTokens??0)};if(Q.reasoningTokens!==void 0||$.reasoningTokens!==void 0)Z.reasoningTokens=($.reasoningTokens??0)+(Q.reasoningTokens??0);if(Q.cachedInputTokens!==void 0||$.cachedInputTokens!==void 0)Z.cachedInputTokens=($.cachedInputTokens??0)+(Q.cachedInputTokens??0);if(Q.imageInputTokens!==void 0||$.imageInputTokens!==void 0)Z.imageInputTokens=($.imageInputTokens??0)+(Q.imageInputTokens??0);if(Q.imageOutputTokens!==void 0||$.imageOutputTokens!==void 0)Z.imageOutputTokens=($.imageOutputTokens??0)+(Q.imageOutputTokens??0);return Z}function S9($){if(!$.trim())return{};try{return JSON.parse($)}catch{}let Q=[],Z=!1,V=!1;for(let W of $){if(Z){if(V)V=!1;else if(W==="\\")V=!0;else if(W==='"')Z=!1;continue}if(W==='"')Z=!0;else if(W==="{")Q.push("}");else if(W==="[")Q.push("]");else if(W==="}"||W==="]")Q.pop()}let G=$;if(Z)G+='"';G=G.replace(/[,:]\s*$/,"");let J=Q.reverse().join("");try{return JSON.parse(G+J)}catch{try{return JSON.parse(G.replace(/,?\s*"[^"]*"\s*$/,"")+J)}catch{return{}}}}function j9($){return{name:"output",schema:$.toJSONSchema(),strict:W9($)}}function A9($,Q){let Z=$.safeParse(S9(Q));if(Z.ok===!0)return{ok:!0,value:Z.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Z.errors.join(", ")}`,retryable:!0}}}function T9($){if($.length>0)$[0];return $}function Y9($,Q,Z){let V=$.content[$.content.length-1];if(V&&V.type===Q){V.text=(V.text??"")+Z;return}$.content.push(Q==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function E9($,Q,Z){let V=$.content[$.content.length-1];if(V&&V.type==="reasoning"&&V.id===Q){V.text=(V.text??"")+Z;return}$.content.push(Q?{type:"reasoning",id:Q,text:Z}:{type:"reasoning",text:Z})}function Y$($){return K9($)}async function K9($,Q={}){let Z=`gen_${crypto.randomUUID()}`,V=await I6($);if(Q.settled?.(V),!V.ok){if($.logErrors!==!1&&V.error.code!=="aborted")x6(Z,V.error,Q.origin);if($.throwOnError)throw new H9({runId:Z,messages:V.messages,finishReason:V.finishReason,usage:V.usage,error:V.error})}return V}function x6($,Q,Z){let V=`[gemi/ai] generate() failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`,G={...Z,generateId:$,error:Q},J=!1;try{X9.error(V,G),J=!0}catch{}if(!J||Bun.env.NODE_ENV==="development")console.error(V,G)}async function I6($){let Q=$.messages??[];if(Q.length===0&&!$.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...Q];if($.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:$.prompt}],createdAt:new Date().toISOString()});let V={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},G=$.signal??new AbortController().signal,J=R(),W="stop",X,K={},Y="";try{let D=$.provider.stream({messages:[...Z],systemPrompt:$.instructions?.trim()?$.instructions:void 0,output:j9($.output),reasoning:$.reasoning,maxOutputTokens:$.maxOutputTokens,temperature:$.temperature,signal:$.signal})[Symbol.asyncIterator]();try{for(;;){let L=await c(Promise.resolve(D.next()),G);if(L.done)break;let F=L.value;switch(F.type){case"output-delta":Y+=F.delta;break;case"text-delta":Y9(V,"text",F.delta);break;case"reasoning-delta":E9(V,F.id,F.delta);break;case"finish":if(J=M(J,F.usage),!X)W=F.reason;break;case"error":W="error",X=F.error,K=b(F);break}}}finally{if(G.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(z){if(z instanceof w||G.aborted)W="aborted",X=w6(G);else W="error",X=$.provider.normalizeError(z),K=b(z)}let H=!1,B;if(!X)if(W==="length")X={code:"invalid_output",message:"The model ran out of output tokens before finishing its structured answer, so it was cut off. Raise maxOutputTokens, or ask for a shorter answer.",retryable:!0};else if(!Y.trim())X={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let z=A9($.output,Y);if(z.ok===!0)H=!0,B=z.value;else X=z.error}if(H)V.content.push({type:"output",value:B});else if(Y)Y9(V,"text",Y);for(let z of V.content)if((z.type==="text"||z.type==="reasoning")&&typeof z.text==="string")z.text=T9(z.text);if(V.finishReason=W,V.usage=J,Z.push(V),H)return{ok:!0,output:B,messages:Z,usage:J,finishReason:W};return{ok:!1,error:{...X,...K},messages:Z,usage:J,finishReason:W}}function w6($){return $.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}class z9 extends j{id;code="attachment_not_found";constructor($){super(`No attachment ${$}.`);this.id=$;this.name="AttachmentNotFoundError"}}class g extends j{code="invalid_attachment_scope";constructor($){super($);this.name="InvalidAttachmentScopeError"}}function X$($){if(!$||typeof $.key!=="string"||$.key.length===0)throw new g("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return $}var v="gemi_att_";function K$(){return`${v}${crypto.randomUUID()}`}class p{store;storage;scope;constructor($,Q,Z){this.store=$;this.storage=Q;this.scope=Z;X$(Z)}get scopeKey(){return this.scope.key}async get($){let Q=await this.store.find(this.scope,$);if(!Q||Q.scopeKey!==this.scope.key)throw new z9($);return Q}async read($){return await this.readRecord($,await this.get($))}async readRecord($,Q){if(!Q.objectName)throw new z9($);return await this.storage.read({name:Q.objectName})}async file($){let Q=await this.get($),V=(await this.readRecord($,Q)).body,G=V instanceof Blob?V:V?await new Response(V).blob():new Blob([]);return new File([G],Q.name,{type:Q.mimeType})}async put($,Q={}){let Z=K$(),V=Q.mimeType??$.type??"",G=Q.name??($ instanceof File?$.name:Z),J=await this.storage.put({name:H$(Z,G),body:$,contentType:V||void 0}),W={id:Z,scopeKey:this.scope.key,objectName:J,name:G,mimeType:V||"application/octet-stream",size:$.size,createdAt:new Date().toISOString(),destination:Q.fileId?"both":"storage",...Q.fileId?{fileId:Q.fileId}:{}};return await this.store.put(this.scope,W),W}}function H$($,Q){let Z=/\.([A-Za-z0-9]{1,8})$/.exec(Q);return`attachments/${$}${Z?`.${Z[1].toLowerCase()}`:""}`}class k9{rows=new Map;async put($,Q){X$($),this.rows.set(Q.id,{...Q,scopeKey:$.key})}async find($,Q){X$($);let Z=this.rows.get(Q);if(!Z||Z.scopeKey!==$.key)return null;return Z}get size(){return this.rows.size}}var t=new k9;class B9{jobs=new Map;async create($){if(this.jobs.has($.id))throw Error(`A background job with the id ${$.id} already exists.`);let Q=Date.now(),{deadlineMs:Z,...V}=$,G={...structuredClone(V),state:"running",createdAt:Q,updatedAt:Q,deadlineAt:Q+Z};return this.jobs.set(G.id,G),this.trim(G.threadId),structuredClone(G)}async get($){let Q=this.jobs.get($);return Q?structuredClone(Q):null}async listForThread($,Q={}){let Z=[];for(let V of this.jobs.values()){if(V.threadId!==$)continue;if(Q.states&&!Q.states.includes(V.state))continue;Z.push(V)}return Z.sort(NQ),(Q.limit===void 0?Z:Z.slice(0,Q.limit)).map((V)=>structuredClone(V))}async transition($,Q,Z){let V=this.jobs.get($);if(!V||!Q.includes(V.state))return!1;let G=structuredClone(Z),J=Date.now();if(Object.assign(V,G,{updatedAt:J}),G.state&&G.state!=="running"&&V.settledAt===void 0)V.settledAt=G.settledAt??J;return!0}async overdue($,Q){let Z=[];for(let V of this.jobs.values())if(V.state==="running"&&V.deadlineAt<=$)Z.push(V);return Z.sort((V,G)=>V.deadlineAt-G.deadlineAt),Z.slice(0,Math.max(0,Q)).map((V)=>structuredClone(V))}async now(){return Date.now()}trim($){let Q=[...this.jobs.values()].filter((Z)=>Z.threadId===$&&Z.state!=="running").sort(NQ);for(let Z of Q.slice(200))this.jobs.delete(Z.id)}}function NQ($,Q){return Q.createdAt-$.createdAt||($.id<Q.id?1:$.id>Q.id?-1:0)}var MQ=Symbol.for("gemi.ai.JobHandle");class b9{id;toolCallId;summary;deadlineAt;[MQ]=!0;constructor($,Q,Z,V){this.id=$;this.toolCallId=Q;this.summary=Z;this.deadlineAt=V}}function RQ($){return typeof $==="object"&&$!==null&&$[MQ]===!0}class D9 extends j{code="jobs_require_thread";constructor($){super($,{retryable:!1});this.name="JobsRequireThreadError"}}var a=new B9,b6=["running","ok","error"],y={get store(){return a},use($){a=$},get($){return a.get($)},async settle($,Q){return x9(a,$,Q)},async fail($,Q){return x9(a,$,{error:Q})},async sweep($={}){let Q=a,Z=$.limit??100,V=await z$(Q),G=0;for(let J of await Q.overdue(V,Z))if(await B$(Q,J))G++;return G}};async function z$($){return $.now?await $.now():Date.now()}function B$($,Q){return $.transition(Q.id,["running"],{state:"error",error:{code:"timeout",message:`The background job for "${Q.toolName}" did not finish before its deadline, so it was given up on. Its result, if it ever arrives, is ignored.`,toolCallId:Q.toolCallId,retryable:!0}})}async function x9($,Q,Z){let V=await $.get(Q);if(!V||V.state!=="running")return!1;let G=Z.usage?M(V.usage??R(),Z.usage):void 0;if("error"in Z)return $.transition(Q,["running"],{state:"error",error:f6(V,Z.error),...G?{usage:G}:{}});return $.transition(Q,["running"],{state:"ok",output:SQ(Z.output,V),...G?{usage:G}:{}})}function f6($,Q){if(typeof Q==="string")return{code:"tool_error",message:Q,toolCallId:$.toolCallId,retryable:!0};if(Q instanceof Error){let Z={code:"tool_error",message:Q.message,toolCallId:$.toolCallId,retryable:Q instanceof j?Q.retryable:!0};if(!(Q instanceof j))console.error(`The background job ${$.job??"(tracked)"} for "${$.toolName}" failed.`,Q);return F9(Z,{source:"tool",toolName:$.toolName,cause:Q})}return{code:Q.code??"tool_error",message:String(Q.message),toolCallId:$.toolCallId,retryable:Q.retryable??!0}}function SQ($,Q){if($===void 0)return null;try{return JSON.parse(JSON.stringify($))}catch(Z){throw Error(`The output of the background job for "${Q.toolName}" is not JSON: ${String(Z)}`)}}var D$=3600000;function jQ($){let Q=null,Z=(V,G,J={})=>{if($.async===void 0)throw new j(`"${$.toolName}" called ctx.jobs, but the tool does not declare \`async\`. Add \`async: { deadlineMs }\` to its definition.`,{retryable:!1});if(!$.jobs||!$.threadId)throw new D9(`"${$.toolName}" can only run in the background on a conversation the server keeps (a turn with a threadId), and this one has none.`);if($.depth>0)throw new D9(`"${$.toolName}" can only run in the background from the top-level agent, not from a sub-agent.`);if(Q)throw new j(`"${$.toolName}" started a background job already: a tool call has at most one.`,{retryable:!1});let W=J.deadlineMs??$.async.deadlineMs??D$;if(!Number.isFinite(W)||W<=0)throw new j(`A job's deadlineMs must be a positive number; got ${W}.`);let{jobs:X,threadId:K}=$;return Q=(async()=>{let Y=y.store,H=(await Y.listForThread(K,{limit:50})).find((D)=>D.toolCallId===$.toolCallId);if(H)return CQ(H);let B=async()=>{let D=await Y.create({id:`ajob_${crypto.randomUUID()}`,threadId:K,runId:$.runId,toolCallId:$.toolCallId,toolName:$.toolName,owner:X.owner,job:V?V.name:null,...J.summary!==void 0?{summary:SQ(J.summary,$)}:{},attachmentScope:$.attachments?.scopeKey??null,deadlineMs:W});if(V)try{await v6(V,{jobId:D.id,args:G})}catch(L){if(Y.transaction)throw L;throw await Y.transition(D.id,["running"],{state:"error",error:{code:"tool_error",message:`The background job for "${$.toolName}" could not be queued.`,toolCallId:$.toolCallId,retryable:!0}}).catch(()=>{}),L}return D},z=Y.transaction?await Y.transaction(B):await B();return CQ(z)})(),Q};return{start:(V,G,J)=>Z(V,G,J),track:(V)=>Z(null,void 0,V)}}function CQ($){return new b9($.id,$.toolCallId,$.summary,$.deadlineAt)}function v6($,Q){if($.name==="unset"||!$.name)throw Error("Cannot start an AgentJob with no `static name`.");return I9(qQ).push($,JSON.stringify([Q]))}class F$ extends _Q{attachments=t;attachmentStorage=w9;constructor(){super();let $=this.run;this.run=(Q)=>this.$runEnvelope(Q,$)}onDeadletter($,...Q){let Z=Q[0];if(!Z?.jobId)return;x9(y.store,Z.jobId,{error:$}).catch((V)=>{console.error(`Could not record the failure of background job ${Z.jobId}.`,V)})}async $runEnvelope($,Q){let Z=y.store,V=await Z.get($.jobId);if(!V||V.state!=="running")return;let G=new AQ(V,this),J;try{J=await Q.call(this,$.args,G)}catch(W){throw await OQ(Z,V.id,G.usage),W}if(this.$outcome)return await OQ(Z,V.id,G.usage),J;return await x9(Z,V.id,{output:J,usage:G.usage}),J}}async function OQ($,Q,Z){if(Z.totalTokens===0&&Z.inputTokens===0&&Z.outputTokens===0)return;let V=await $.get(Q);if(!V)return;await $.transition(Q,b6,{usage:M(V.usage??R(),Z)}).catch(()=>{})}class AQ{id;threadId;toolCallId;toolName;owner;summary;signal=new AbortController().signal;usage=R();attachments;constructor($,Q){this.id=$.id,this.threadId=$.threadId,this.toolCallId=$.toolCallId,this.toolName=$.toolName,this.owner=$.owner,this.summary=$.summary;let Z=$.attachmentScope?new p(Q.attachments,Q.attachmentStorage,{key:$.attachmentScope}):null,V=()=>{if(!Z)throw new g("The run that started this job had no attachment scope, so the job cannot store or read files. See `attachmentScope()` on the controller.");return Z};this.attachments={put:(G,J={})=>V().put(G,J),get:(G)=>V().get(G),read:(G)=>V().read(G),file:(G)=>V().file(G)}}generate($){return K9($,{origin:{threadId:this.threadId,toolCallId:this.toolCallId,jobId:this.id},settled:(Q)=>{this.usage=M(this.usage,Q.usage)}})}async generateImage($,Q){let{name:Z,...V}=Q,G=await $.generate({...V,signal:this.signal});return this.park($,G,Z)}async editImage($,Q){let{name:Z,images:V,mask:G,...J}=Q,W=async(K)=>typeof K==="string"?await this.attachments.file(K):K,X=await $.edit({...J,images:await Promise.all(V.map(W)),...G?{mask:await W(G)}:{},signal:this.signal});return this.park($,X,Z)}async park($,Q,Z){this.usage=M(this.usage,Q.usage);let V=Q.mimeType==="image/jpeg"?"jpg":"png";return{attachment:await this.attachments.put(Q.image,{name:Z??`${$.name}.${V}`,mimeType:Q.mimeType}),size:Q.size,mimeType:Q.mimeType,usage:Q.usage}}}function m($){let Q=new Set;for(let Z of $)for(let V of Z.content??[]){if(V.type!=="tool-call")continue;for(let G of V.attachments??[])if(G&&"shown"in G&&G.shown)Q.add(G.shown.messageId)}return Q}function L9($){if($.length===0)return[];let Q=m($),Z=[0];for(let V=1;V<$.length;V++){let G=$[V];if(G.role==="user"&&!Q.has(G.id))Z.push(V)}return Z}function y6($){let Q=L9($);return Q.map((Z,V)=>$.slice(Z,Q[V+1]??$.length))}function EQ($){try{return JSON.stringify($).length}catch{return 0}}var h6=4,kQ=10,xQ="[Earlier turns of this conversation are not shown.]";function r($,Q={}){let Z=[...$],V=L9(Z),G=g6(Q),J=f9(Q.maxTurns)??1/0,W=Math.max(1,Math.floor(f9(Q.step)??kQ));if(V.length<=1||J>=V.length&&G===1/0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let X=Array.from({length:Z.length+1},()=>0);if(G!==1/0)for(let U=Z.length-1;U>=0;U--)X[U]=X[U+1]+EQ(Z[U]);let K=(U)=>V.length-U<=J&&X[V[U]]<=G,Y=-1;for(let U=0;U<V.length;U+=W)if(K(U)){Y=U;break}if(Y<0){for(let U=0;U<V.length;U++)if(K(U)){Y=U;break}}if(Y<0)Y=V.length-1;if(Y===0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let H=V[Y],B=Z.slice(0,H),z=B.filter((U)=>U.role==="system"),D=u6(B,Z.slice(H)),L={turns:Y,messages:B.length-z.length},F=typeof Q.note==="function"?Q.note(L):Q.note===void 0?xQ:Q.note;if(F){let U=D[0];D[0]={...U,content:[{type:"text",text:F},...U.content]}}return{messages:[...z,...D],start:H,omittedTurns:L.turns,omittedMessages:L.messages}}function f9($){return typeof $==="number"&&$>0?$:void 0}function g6($){let Q=f9($.maxBytes)??1/0,Z=f9($.maxTokens);return Math.min(Q,Z===void 0?1/0:Z*h6)}function TQ($,Q){let Z=Array.isArray($?.namespaces)?$.namespaces:[],V=Array.isArray($?.loaded)?$.loaded:[];return Q.namespace?Z.includes(Q.namespace):V.includes(String(Q.name))}function L$($){return Array.isArray($.toolSearches)?$.toolSearches:[]}function u6($,Q){let Z=[];for(let Y of $)for(let H of Y.content??[])if(H.type==="tool-call")Z.push(...L$(H));if(Z.length===0)return Q;let V=[],G=new Set,J;if(Q.forEach((Y,H)=>{(Y.content??[]).forEach((B,z)=>{if(B.type!=="tool-call"||B.partial)return;if(V.push(...L$(B)),V.some((L)=>TQ(L,B)))return;let D=Z.filter((L)=>TQ(L,B));if(D.length===0)return;for(let L of D)G.add(L);J??={message:H,part:z}})}),!J)return Q;let W=Z.filter((Y)=>G.has(Y)),X=[...Q],K=X[J.message];return X[J.message]={...K,content:K.content.map((Y,H)=>H===J.part&&Y.type==="tool-call"?{...Y,toolSearches:[...W,...L$(Y)]}:Y)},X}var fQ=1000,c6=24000,p6=20000,vQ=1e5,m6=120000,yQ=["You keep a running summary of a conversation between a user and an AI assistant.","The assistant will continue the conversation with only your summary and the latest turns, so the summary has to carry everything from the earlier turns it may still need.","You are given the summary so far (possibly empty) and the turns that came after it. Answer the updated summary, which replaces the old one.","Keep: the user's goals, preferences and constraints; decisions made and why; facts, names, ids, numbers, dates, file names and URLs that may matter later; what tools were used and their important results; open questions and unfinished work.","Drop greetings, repetition and anything later turns superseded. Do not invent anything, and do not answer the user.","Write terse prose or bullet points, in the language of the conversation."].join(" "),hQ="[Summary of the earlier turns of this conversation, which are not shown:]",l6=8;class N${ttlMs;threads=new Map;lastSweep=0;constructor($=86400000){this.ttlMs=$}async loadSummaries($){this.sweep();let Q=this.threads.get($);if(!Q)return[];return Q.touchedAt=Date.now(),Q.summaries.slice()}async saveSummary($,Q){this.sweep();let Z=this.threads.get($)??{summaries:[],touchedAt:Date.now()};Z.summaries=h9(Z.summaries,Q),Z.touchedAt=Date.now(),this.threads.set($,Z)}delete($){this.threads.delete($)}sweep($=Date.now()){if($-this.lastSweep<60000)return;this.lastSweep=$;for(let[Q,Z]of this.threads)if($-Z.touchedAt>this.ttlMs)this.threads.delete(Q)}}function h9($,Q){return[Q,...$.filter((Z)=>Z.cutMessageId!==Q.cutMessageId)].slice(0,l6)}var C$=new N$;function gQ($){let Q=$;return typeof Q?.loadSummaries==="function"&&typeof Q?.saveSummary==="function"}function uQ($,Q,Z){let V=u(Z.maxSummaryTokens)??fQ,G=(K)=>Math.max(1,K-V),J={...Q,...u(Q.maxTokens)?{maxTokens:G(Q.maxTokens)}:{},...u(Q.maxBytes)?{maxBytes:Math.max(1,Q.maxBytes-V*P$)}:{}},W=d6(Q,Z),X={...J,note:!1,...W?{maxTokens:Math.min(J.maxTokens??1/0,G(W))}:{}};return{plain:J,cut:r($,X),maxSummaryTokens:V}}function d6($,Q){if(Q.triggerTokens===!1)return;let Z=u(Q.triggerTokens||void 0);if(Z)return Z;if(u($.maxTokens)||u($.maxBytes))return;return vQ}async function cQ($){let{history:Q,window:Z,compact:V}=$,{plain:G,cut:J,maxSummaryTokens:W}=uQ(Q,Z,V);if(J.omittedTurns===0)return J.messages;let X=`${Q[J.start].id}:${J.start}`,K=$.memo?.get(X);if(K===void 0){try{K=await t6($,J.start,W)}catch(D){if($.signal.aborted)throw D;K=null}if(!$.signal.aborted)$.memo?.set(X,K)}if(!K)return r(Q,G).messages;let Y=Q.length-J.start,H=J.messages.slice(0,J.messages.length-Y),B=J.messages.slice(J.messages.length-Y),z=Q[J.start];return[...H,{id:`summary_${z.id}`,role:"user",content:[{type:"text",text:`${hQ}
3
- ${K.text}`}],createdAt:z.createdAt},...B]}var IQ="\x00next-turn";function pQ($){let Q=i6($).finally(()=>y9.delete(Q));return y9.add(Q),Q}var y9=new Set;async function i6($){try{let Q={id:IQ,role:"user",content:[{type:"text",text:""}],createdAt:new Date().toISOString()},Z=[...$.history,Q],V=[...$.stored,Q],{cut:G,maxSummaryTokens:J}=uQ(Z,$.window,$.compact);if(G.omittedTurns===0||Z[G.start].id===IQ)return;let W=mQ({...$,history:Z,stored:V},G.start);if((await g9($.store,$.threadId)).some(W.matches))return;await lQ(W,{...$,history:Z,stored:V},G.start,J).promise}catch{}}async function n6(){while(P9.size>0||y9.size>0)await Promise.allSettled([...y9,...[...P9.values()].map(($)=>$.promise)])}var P9=new Map,l=new Map,o6=1000;function s6($,Q){l.set($,M(l.get($)??R(),Q));while(l.size>o6)l.delete(l.keys().next().value)}function wQ($,Q){let Z=l.get($);if(!Z)return;l.delete($),Q(Z)}function mQ($,Q){let Z=$.history[Q].id,V=G8($.stored,Q),G=V[Q];return{key:`${$.threadId}\x00${Z}\x00${G}`,fingerprints:V,matches:(J)=>J?.cutMessageId===Z&&J.fingerprint===G}}async function t6($,Q,Z){let V=mQ($,Q),G=(await g9($.store,$.threadId)).find(V.matches);if(G)return wQ(V.key,$.onUsage),G;let J=lQ(V,$,Q,Z);if(J.owed)$.onUsage(J.owed),J.owed=void 0;J.payers.push($.onUsage);try{return await a6(J.promise,$.signal)}finally{J.payers.splice(J.payers.indexOf($.onUsage),1),wQ(V.key,$.onUsage)}}function lQ($,Q,Z,V){let G=P9.get($.key);if(G)return G;let J={promise:void 0,payers:[],owed:void 0},W=(X)=>{let K=J.payers[0];if(K)K(X);else J.owed=M(J.owed??R(),X)};return J.promise=(async()=>{let{store:X,threadId:K}=Q,Y=u(Q.compact.lockWaitMs)??p6,H=null;if(X.lockSummary){try{H=await X.lockSummary(K,Q.history[Z].id,Y+60000)}catch{H=null}if(!H)return e6(Q,$.matches,Y)}try{let B=await g9(X,K),z=B.find($.matches);if(z)return z;return await $8(Q,B,$.fingerprints,Z,V,W)}finally{if(H)await H().catch(()=>{})}})().catch(()=>null).finally(()=>{if(P9.delete($.key),J.owed)s6($.key,J.owed);J.owed=void 0}),P9.set($.key,J),J}function a6($,Q){if(Q.aborted)return Promise.reject(Q.reason);return new Promise((Z,V)=>{let G=()=>V(Q.reason);Q.addEventListener("abort",G,{once:!0}),$.then((J)=>{Q.removeEventListener("abort",G),Z(J)},(J)=>{Q.removeEventListener("abort",G),V(J)})})}async function g9($,Q){try{let Z=await $.loadSummaries(Q);return Array.isArray(Z)?Z.filter(r6):[]}catch{return[]}}function r6($){let Q=$;return!!Q&&typeof Q.cutMessageId==="string"&&typeof Q.text==="string"&&typeof Q.fingerprint==="string"}async function e6($,Q,Z){let V=Date.now()+Z;while(Date.now()<V){await new Promise((J)=>setTimeout(J,250));let G=(await g9($.store,$.threadId)).find(Q);if(G)return G}return null}async function $8($,Q,Z,V,G,J){let{history:W,compact:X}=$,K=L9(W),Y=K.indexOf(V),H=new Map(K.map((O)=>[W[O].id,O])),B,z=0;for(let O of Q){let A=H.get(O.cutMessageId);if(A===void 0||A>=V||A<=z)continue;if(O.fingerprint!==Z[A])continue;B=O,z=A}let D=(u(X.chunkTokens)??c6)*P$,L=Q8(W,K,z,V,D),F=G*P$,U=`${X.instructions??yQ} Keep the summary under about ${Math.round(G*0.75)} words.`,P=B?.text??"",q=R();for(let O of L){let A=await Y$({provider:X.provider??$.provider,instructions:U,prompt:`Summary so far:
4
- ${P||"(none yet: these are the first turns of the conversation)"}
5
-
6
- The turns that came after it:
7
- ${O}`,output:v9.object({summary:v9.string()}),reasoning:X.reasoning??"low",signal:AbortSignal.timeout(m6)});if(q=M(q,A.usage),J(A.usage),!A.ok)return null;P=U9(A.output.summary.trim(),F)}if(!P)return null;let _={cutMessageId:W[V].id,text:P,turns:Y<0?0:Y,messages:V,fingerprint:Z[V],createdAt:new Date().toISOString(),usage:q};try{await $.store.saveSummary($.threadId,_)}catch{}return _}var P$=4;function Q8($,Q,Z,V,G){let J=new Set,W=new Set(Q);for(let B=0;B<$.length;B++)if($[B].role==="user"&&!W.has(B)&&B!==0)J.add($[B].id);let X=Math.max(500,Math.min(20000,Math.floor(G/2))),K=[],Y="",H=Q.filter((B)=>B>=Z&&B<V);if(H.forEach((B,z)=>{let D=H[z+1]??V,L=[];for(let U=B;U<D;U++){let P=Z8($[U],J.has($[U].id),X);if(P)L.push(P)}let F=L.join(`
8
- `);if(!F)return;if(Y&&Y.length+F.length+2>G)K.push(Y),Y="";Y=Y?`${Y}
9
-
10
- ${F}`:F}),Y)K.push(Y);return K}function Z8($,Q,Z){if($.role==="system")return"";let V=Q?"Tool (file shown)":$.role==="user"?"User":"Assistant",G=($.content??[]).map((J)=>V8(J,Z)).filter(Boolean);return G.length>0?`${V}: ${G.join(`
11
- `)}`:""}function V8($,Q){switch($.type){case"text":return U9($.text??"",Q);case"file":return`[file: ${$.name??$.mimeType??$.fileId??"attachment"}]`;case"tool-call":return`[called ${$.namespace?`${$.namespace}.${String($.name)}`:String($.name)}(${U9(U$($.input),Math.min(Q,1000))})]`;case"tool-result":{let Z=$.status==="ok"?U$($.output):$.status==="error"?`error: ${$.error?.message??""}`:$.status==="running"?`a background job (${$.job?.id??"unknown"}) that was still running`:`${$.status}${$.reason?`: ${$.reason}`:""}`;return`[${String($.name)} returned: ${U9(Z,Math.min(Q,2000))}]`}case"output":return`[structured answer: ${U9(U$($.value),Math.min(Q,2000))}]`;default:return""}}function U$($){if(typeof $==="string")return $;try{return JSON.stringify($)??""}catch{return String($)}}function U9($,Q){return $.length<=Q?$:`${$.slice(0,Q)}\u2026[cut]`}function u($){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):void 0}function G8($,Q){let Z=["0"],V="";for(let G=0;G<Q;G++){let J;try{J=JSON.stringify($[G])??""}catch{J=String($[G]?.id)}V=bQ(`${V}|${bQ(J)}`),Z.push(V)}return Z}function bQ($){let Q=3735928559,Z=1103547991;for(let V=0;V<$.length;V++){let G=$.charCodeAt(V);Q=Math.imul(Q^G,2654435761),Z=Math.imul(Z^G,1597334677)}return Q=Math.imul(Q^Q>>>16,2246822507)^Math.imul(Z^Z>>>13,3266489909),Z=Math.imul(Z^Z>>>16,2246822507)^Math.imul(Q^Q>>>13,3266489909),(4294967296*(2097151&Z)+(Q>>>0)).toString(36)}class d extends Error{pending;path;nested;constructor($){super(`A nested agent run is waiting on the user for ${$.pending.length} tool call(s).`);this.name="PendingEscalation",this.pending=$.pending,this.path=$.path,this.nested=$.nested}}class i{name;description;inputSchema;outputSchema;requiresApproval;deferred;answeredBy;timeoutMs;async;execute;constructor($){this.name=$.name,this.description=$.description,this.inputSchema=$.inputSchema,this.outputSchema=$.outputSchema,this.requiresApproval=$.requiresApproval===!0,this.deferred=$.deferred===!0,this.answeredBy=$.answeredBy==="client"?"client":"server",this.execute=$.execute??void 0,this.timeoutMs=$.timeoutMs,this.async=$.async}static create($){if(typeof $.inputSchema!=="function")j$($.inputSchema,`The tool "${$.name}"`,"inputSchema");if($.timeoutMs!==void 0)c9($.timeoutMs,`The tool "${$.name}"`,"timeoutMs");if($.async?.deadlineMs!==void 0)c9($.async.deadlineMs,`The tool "${$.name}"`,"async.deadlineMs");if($.async&&$.answeredBy==="client")throw Error(`The tool "${$.name}" is answered by the client and cannot be \`async\`: background jobs are for tools the server runs.`);return new i($)}static ask($){return i.create({name:$.name,description:$.description,inputSchema:R$,outputSchema:$.outputSchema,answeredBy:"client"})}}var R$={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse($){let Q=R$.safeParse($);if(Q.ok===!1)throw Error(Q.errors.join(", "));return Q.value},safeParse($){if(typeof $!=="object"||$===null||typeof $.question!=="string")return{ok:!1,errors:["question: expected a string"]};return{ok:!0,value:{question:$.question}}}};class e{name;description;tools;deferred;constructor($){this.name=$.name,this.description=$.description,this.tools=$.tools,this.deferred=$.deferred===!0}static create($){return new e($)}}class S${name;description;instructions;files;constructor($){this.name=$.name,this.description=$.description,this.instructions=$.instructions,this.files=$.files}static create($){return new S$($)}}var N9="skills",J8="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.";function j$($,Q,Z){let V=$?.toJSONSchema?.();if(V?.type==="object")return;let G=!V?"no JSON Schema":V.anyOf?"a union (`anyOf`) \u2014 `s.union(...)`":V.type!==void 0?`a schema of type ${JSON.stringify(V.type)}`:"an unconstrained schema (`s.json()`)";throw Error(`${Q} declares an \`${Z}\` whose root is ${G}, but the provider only accepts an object there (OpenAI rejects \`anyOf\` or a non-object at the root of tool parameters and structured output). Wrap it in an object, e.g. \`s.object({ value: s.union([...]) })\`, and read \`.value\` off the result.`)}function c9($,Q,Z){if(typeof $==="number"&&$>0)return;throw Error(`${Q} sets \`${Z}\` to ${String($)}, but it has to be a positive number of milliseconds. Use \`null\` for no limit.`)}function dQ($){if($===void 0)return;if($===null||!Number.isFinite($))return null;return $}var W8=2147483647;function iQ($,Q){if($===null||$>W8)return()=>{};let Z=setTimeout(Q,$);return()=>clearTimeout(Z)}function O$($){if($<1000)return`${$}ms`;if($<60000)return`${+($/1000).toFixed(1)}s`;return`${+($/60000).toFixed(1)}m`}var A$={type:"object",properties:{},required:[],additionalProperties:!1},T$=600000;class H9 extends Error{code;retryable;status;requestId;toolCallId;runId;result;constructor($){super($.error.message);this.name="AgentRunError",this.code=$.error.code,this.retryable=$.error.retryable,this.status=$.error.status,this.requestId=$.error.requestId,this.toolCallId=$.error.toolCallId,this.runId=$.runId,this.result=$}}var Y8=8,X8=3;class E${name;tools;skills;provider;output;instructions;maxSteps;maxDepth;reasoning;maxRunDurationMs;jobs;config;constructor($){this.name=$.name,this.instructions=$.instructions,this.provider=$.provider,this.tools=$.tools??[],this.skills=$.skills??[],this.output=$.output,this.maxSteps=$.maxSteps??Y8,this.maxDepth=$.maxDepth??X8,this.reasoning=$.reasoning,this.jobs=$.jobs??{};let Q=dQ($.maxRunDurationMs);this.maxRunDurationMs=Q===void 0?T$:Q;let{registry:Z,providerTools:V}=K8(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:Z,providerTools:V,output:$.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning,maxOutputTokens:$.maxOutputTokens,temperature:$.temperature,logErrors:$.logErrors??!0,maxRunDurationMs:Q,contextWindow:$.contextWindow,prepareStep:$.prepareStep?[$.prepareStep]:[]}}static create($){if($.output)j$($.output,`The agent "${$.name}"`,"output");if($.maxRunDurationMs!=null)c9($.maxRunDurationMs,`The agent "${$.name}"`,"maxRunDurationMs");let Q=$.jobs?.contextBlock;if(Q&&Q.max!==void 0&&!(Number.isInteger(Q.max)&&Q.max>0))throw Error(`The agent "${$.name}" sets \`jobs.contextBlock.max\` to ${String(Q.max)}, but it has to be a whole number above 0. Use \`contextBlock: false\` for no block.`);return new E$($)}stream($){let Q={...this.config,provider:$.provider??this.config.provider,maxSteps:$.maxSteps??this.config.maxSteps,reasoning:$.reasoning??this.config.reasoning,maxOutputTokens:$.maxOutputTokens??this.config.maxOutputTokens,temperature:$.temperature??this.config.temperature,maxRunDurationMs:$.maxRunDurationMs!==void 0?dQ($.maxRunDurationMs):this.config.maxRunDurationMs,contextWindow:$.contextWindow===!1?void 0:$.contextWindow??this.config.contextWindow,prepareStep:$.prepareStep?[...this.config.prepareStep,$.prepareStep]:this.config.prepareStep};if($.maxRunDurationMs!=null)c9($.maxRunDurationMs,`Agent.stream for "${this.name}"`,"maxRunDurationMs");return new BZ(Q,$)}}function q$($){let Q=$.inputSchema;return{name:$.tool.name,description:$.tool.description,parameters:Q?Q.toJSONSchema():A$,strict:Q?W9(Q):!0,deferred:$.deferred}}function _$($){return typeof $.inputSchema==="function"?void 0:$.inputSchema}function K8($,Q){let Z=new Map,V=[],G=(J)=>{if(Z.has(J.tool.name))throw Error(`Two tools are named "${J.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(J.tool.name,J)};for(let J of $){if(J instanceof e){if(J.name===N9)throw Error(`"${N9}" is reserved for the namespace skills are lowered into. Rename the namespace \u2014 silently shadowing it would make every skill unreachable with no error to read.`);let X=[];for(let K of J.tools){let Y={tool:K,namespace:J.name,deferred:J.deferred||K.deferred,inputSchema:_$(K)};G(Y),X.push(q$(Y))}V.push({name:J.name,description:J.description,tools:X});continue}let W={tool:J,deferred:J.deferred,inputSchema:_$(J)};G(W),V.push(q$(W))}if(Q.length>0){let J=[];for(let W of Q){let X=H8(W);G({tool:X,namespace:N9,deferred:!1,inputSchema:_$(X)}),J.push({name:W.name,description:W.description,parameters:A$,strict:!0,deferred:!1})}V.push({name:N9,description:J8,tools:J})}return{registry:Z,providerTools:V}}function H8($){return i.create({name:$.name,description:$.description,inputSchema:{toJSONSchema:()=>A$,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Z=[typeof $.instructions==="function"?await $.instructions():$.instructions];for(let V of $.files??[])Z.push(`--- ${V} ---
12
- ${await z8(V)}`);return Z.join(`
13
-
14
- `)}})}async function z8($){try{return await Bun.file($).text()}catch(Q){return`(could not be read: ${Q.message})`}}function B8($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}function nQ($,Q){let Z=[...$],V=new Map(Z.map((G,J)=>[G.id,J]));for(let G of Q){let J=V.get(G.id);if(J===void 0)V.set(G.id,Z.length),Z.push(G);else Z[J]=G}return Z}function u9($){let Q=new Set;for(let V of $)for(let G of V.content)if(G.type==="tool-result")Q.add(G.toolCallId);let Z=new Set;for(let V of $)for(let G of V.content)if(G.type==="tool-call"&&!Q.has(G.toolCallId))Z.add(G.toolCallId);return Z}function oQ($){for(let Q=$.length-1;Q>=0;Q--){let Z=$[Q].content;for(let V=Z.length-1;V>=0;V--){let G=Z[V];if(G.type==="output"&&G.partial!==!0)return G.value}}return}function sQ($,Q){return Q===void 0?`"${$}"`:`"${$}" labelled "${Q}"`}function zZ($){return $.content.map((Q)=>Q.type==="text"?Q.text:`<${Q.type}>`).join("")}function D8($){if($.prompt!==void 0)return`user:${$.prompt}`;let Q=$.messages?.[0];return Q?`${Q.role}:${zZ(Q)}`:null}var tQ=1;function F8($,Q,Z){let V=Z.mimeType||Q.type||"";if(V&&$.attachment.mimeType!==V)return`was ${JSON.stringify($.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(V)} on the replay`;let G=Boolean(Z.showModel);if(G!==Boolean($.shown))return G?"was stored without showModel on the turn that escalated and asks for showModel on the replay":"was stored with showModel on the turn that escalated and asks for a plain put on the replay";return null}function L8($,Q,Z){if($.agent!==Q.name||$.label!==Z.label)return`was ${sQ($.agent,$.label)} on the turn that escalated and is ${sQ(Q.name,Z.label)} on the replay`;let V=D8(Z),G=$.messages[0],J=G?`${G.role}:${zZ(G)}`:null;if(V!==null&&J!==null&&V!==J)return`was started with ${JSON.stringify(J)} on the turn that escalated and with ${JSON.stringify(V)} on the replay`;return null}function aQ($,Q){let Z=$??[];if(Z.length<Q.length)return null;for(let V=0;V<Q.length;V++)if(Z[V]!==Q[V])return null;return Z.slice(Q.length)}class M${read;create;fill;index=0;replayable;constructor($,Q,Z){this.read=$;this.create=Q;this.fill=Z;this.replayable=$()?.length??0}next(){let $=this.index++;return{at:$,recorded:$<this.replayable?this.read()?.[$]:void 0,write:(Q)=>{let Z=this.read()??this.create();if(this.fill)for(let V=Z.length;V<$;V++)Z[V]=this.fill();Z[$]=Q}}}}class BZ{runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];compactMemo=new Map;lastStep;produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=R();finishReason="stop";failure;output;stopReason;timedOutAfter;cancelDeadline=()=>{};settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor($,Q){this.config=$,this.params=Q,this.context=Q.context??{},this.runId=Q.runId??`run_${crypto.randomUUID()}`,this.history=[...Q.messages];let Z=Q.nesting;if(this.depth=Z?.depth??0,this.maxDepth=Z?.maxDepth??$.maxDepth,this.chain=Z?.chain??[$.name],this.signingRunId=Z?.signingRunId??this.runId,this.pathPrefix=Z?.signingPath??[],this.onPending=Z?.onPending??"escalate",Q.signal)if(Q.signal.aborted)this.controller.abort();else Q.signal.addEventListener("abort",()=>this.stop(),{once:!0});let V=$.maxRunDurationMs!==void 0?$.maxRunDurationMs:Z?null:T$;this.cancelDeadline=iQ(V,()=>this.expire(V)),this.settled=this.execute(),p9.getStore()?.waitUntil(this.settled)}emit($){if(this.ended)return;this.buffer.push({seq:++this.seq,event:$}),this.wake()}wake(){let $=[...this.waiters];this.waiters.clear();for(let Q of $)Q()}nextFrame(){return new Promise(($)=>this.waiters.add($))}async*frames($=0){let Q=$>0?$-1:0;for(;;){while(Q<this.buffer.length)yield this.buffer[Q++];if(this.ended)return;await this.nextFrame()}}async*[Symbol.asyncIterator](){for await(let $ of this.frames())yield $.event}toResponse($){let Q=this.frames($?.from),Z=new TextEncoder,V=!1,G,J=new ReadableStream({start:async(W)=>{G=$Z(W);try{for await(let X of Q){if(V)break;W.enqueue(Z.encode(`id: ${X.seq}
15
- data: ${JSON.stringify(X.event)}
16
-
17
- `)),G.touch()}}catch{}G.stop();try{W.close()}catch{}},cancel:()=>{V=!0,G.stop()}});return new Response(J,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result($){if(!$?.throwOnError)return this.settled;return this.settled.then((Q)=>{if(Q.error)throw new H9({...Q,error:Q.error});return Q})}stop($){if(this.ended||this.controller.signal.aborted)return;this.stopReason=$?.reason,this.controller.abort()}expire($){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=$,this.stopReason=`The run reached its time limit of ${O$($)} and was stopped.`,this.controller.abort(new DOMException(this.stopReason,"TimeoutError"))}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{let Q=await this.resolveToolSchemas(),Z=Q?[]:await this.ingestTurn();if(Q)this.fail(Q),this.finishReason="error";else if(Z.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:Z});else await this.loop()}catch(Q){if(Q instanceof w||this.controller.signal.aborted)await this.finalizeAborted();else this.fail(this.config.provider.normalizeError(Q),b(Q)),await this.finalizeMessage("error"),this.finishReason="error"}this.cancelDeadline(),this.emit({type:"usage",usage:this.usage}),this.emit({type:"run-end",runId:this.runId,finishReason:this.finishReason}),this.ended=!0,this.wake(),this.precompact();let $=this.finishReason==="error"?this.failure:void 0;if($&&this.config.logErrors)this.logFailure($);return{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,output:this.output,...$?{error:$}:{}}}async resolveToolSchemas(){let $=[...this.config.registry.values()].filter((K)=>!K.inputSchema);if($.length===0)return;let Q={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,signal:this.controller.signal},Z=new Map,V=await Promise.all($.map(async(K)=>{try{let Y=K.tool.inputSchema,H=await Y(Q);j$(H,`The tool "${K.tool.name}"`,"inputSchema"),Z.set(K.tool.name,H);return}catch(Y){return`"${K.tool.name}": ${Y instanceof Error?Y.message:String(Y)}`}}));if(this.controller.signal.aborted)throw new w;let G=V.filter((K)=>K!==void 0);if(G.length>0)return{code:"tool_error",message:`Could not resolve the input schema of ${G.join("; ")}`,retryable:!1};let J=new Map;for(let[K,Y]of this.config.registry)J.set(K,Z.has(K)?{...Y,inputSchema:Z.get(K)}:Y);let W=(K)=>Z.has(K.name)?q$(J.get(K.name)):K,X=this.config.providerTools.map((K)=>("tools"in K)?{...K,tools:K.tools.map(W)}:W(K));this.config={...this.config,registry:J,providerTools:X};return}fail($,Q={}){let Z={...$,...Q};this.failure=Z,this.emit({type:"error",error:this.redact(Z,{source:"run",failure:Z})})}redact($,Q){let Z=KZ(this.params.redactError,$,Q,(V)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:V}));return HZ(Z,$),Z}logFailure($){let Q=`[gemi/ai] agent "${this.config.name}" run failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`;this.writeLog(Q,{error:$})}logToolFailure($,Q){let Z=Q instanceof Error?Q.message:String(Q);this.writeLog(`[gemi/ai] agent "${this.config.name}" tool "${String($.name)}" threw: ${Z}`,{toolCallId:$.toolCallId,error:Q})}writeLog($,Q){let Z={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},...Q},V=!1;try{X9.error($,Z),V=!0}catch{}if(!V||Bun.env.NODE_ENV==="development")console.error($,Z)}async loop(){let $=Math.max(1,this.config.maxSteps);for(let Q=1;Q<=$;Q++){let Z=this.startMessage(),V=await this.runStep(Z,Q);if(this.lastStep={reason:V.reason,usage:Z.usage},V.error){this.fail(V.error,V.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let G=Z.content.filter((W)=>W.type==="tool-call");if(G.length===0){this.finishReason=V.reason,await this.finalizeMessage(V.reason);return}let J=await this.runTools(Z,G,Q);if(J.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:J});return}if(Q===$){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(V.reason)}}startMessage(){let $={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()};return this.current=$,this.history.push($),this.produced.push($),this.emit({type:"message-start",messageId:$.id,role:"assistant"}),$}async finalizeMessage($){let Q=this.current;if(!Q)return;this.current=null;let Z=this.outputTruncated;if(this.outputTruncated=!1,Q.finishReason=$,Z)Q.outputTruncated=!0;for(let V of Q.content)if(V.type==="text"||V.type==="reasoning"){if(typeof V.text==="string")V.text=T9(V.text)}this.emit({type:"message-end",messageId:Q.id,finishReason:$,...Z?{outputTruncated:!0}:{},...Q.usage?{usage:Q.usage}:{}}),await this.report(Q),await this.reportDeferred()}async report($){if(!this.params.onMessage)return;try{await this.params.onMessage($)}catch{}}async runStep($,Q){let Z=this.controller.signal,V=this.config.provider,G=await this.prepareRequest($,Q);if("error"in G)return{reason:"error",error:G.error};let J={reason:"stop"},W=new Map,X=[],K=()=>{if(X.length===0)return{};let D=X;return X=[],{toolSearches:D}},Y="",B=V.stream({messages:G.messages,systemPrompt:G.instructions,tools:this.config.providerTools.length>0?this.config.providerTools:void 0,output:this.config.output?j9(this.config.output):void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:Z})[Symbol.asyncIterator]();for(;;){let D=await c(Promise.resolve(B.next()),Z);if(D.done)break;let L=D.value;switch(L.type){case"text-delta":{Y9($,"text",L.delta),this.emit({type:"text-delta",messageId:$.id,delta:L.delta});break}case"reasoning-delta":{E9($,L.id,L.delta),this.emit({type:"reasoning-delta",messageId:$.id,delta:L.delta,id:L.id});break}case"output-delta":{Y+=L.delta,this.emit({type:"output-delta",messageId:$.id,delta:L.delta,snapshot:S9(Y)});break}case"tool-search":{X.push({namespaces:L.namespaces,loaded:L.loaded,...L.arguments!==void 0?{arguments:L.arguments}:{}}),this.emit({type:"tool-search",loaded:L.loaded});break}case"tool-call-delta":{let F=W.get(L.toolCallId)??{name:L.name,args:""};F.args+=L.argsDelta,F.name=L.name||F.name,F.namespace=L.namespace||F.namespace,W.set(L.toolCallId,F),this.emit({type:"tool-call",messageId:$.id,part:{type:"tool-call",toolCallId:L.toolCallId,name:F.name,input:S9(F.args),partial:!0,...F.namespace?{namespace:F.namespace}:{}}});break}case"tool-call":{let F=L.namespace||W.get(L.toolCallId)?.namespace;W.delete(L.toolCallId);let U={type:"tool-call",toolCallId:L.toolCallId,name:L.name,input:eQ(L.args),...F?{namespace:F}:{},...K()};$.content.push(U),this.emit({type:"tool-call",messageId:$.id,part:U});break}case"finish":{if(this.usage=M(this.usage,L.usage),$.usage=M($.usage??R(),L.usage),!J.error)J={reason:L.reason};break}case"error":{J={reason:"error",error:L.error,detail:b(L)};break}case"file-rejected":{this.markFileRejected(L.fileId,L.message,b(L));break}}}for(let[D,L]of W){let F={type:"tool-call",toolCallId:D,name:L.name,input:eQ(L.args),...L.namespace?{namespace:L.namespace}:{},...K()};$.content.push(F),this.emit({type:"tool-call",messageId:$.id,part:F})}let z=J.reason==="length";if(z)this.outputTruncated=!0;if(this.config.output&&Y&&!J.error&&!z){let D=A9(this.config.output,Y);if(D.ok===!0)this.output=D.value,$.content.push({type:"output",value:D.value});else this.emit({type:"error",error:D.error})}return J}compactJobParams($,Q){let Z=this.config.contextWindow;if(!Z?.compact||!this.params.threadId||this.depth!==0)return;let V=Z.compact===!0?{}:Z.compact;return{history:$,stored:this.history.filter((G)=>G!==Q),window:Z,compact:V,threadId:this.params.threadId,provider:this.config.provider,store:V.store||this.params.summaryStore||C$}}precompact(){let $=this.config.contextWindow;if(!$?.compact||$.compact!==!0&&$.compact.background===!1)return;try{let Q=this.compactJobParams(this.historyForProvider(void 0),void 0);if(Q)pQ(Q)}catch{}}async prepareRequest($,Q){let Z=this.historyForProvider($),V=this.config.contextWindow,G=this.compactJobParams(Z,$),J=!V?Z:G?await cQ({...G,signal:this.controller.signal,onUsage:(X)=>{this.usage=M(this.usage,X)},memo:this.compactMemo}):r(Z,V).messages,W=await this.systemPrompt();for(let X of this.config.prepareStep){let K;try{K=await X({step:Q,messages:[...J],history:[...Z],instructions:W,usage:this.usage,...this.lastStep?.usage?{lastStepUsage:this.lastStep.usage}:{},...this.lastStep?{lastFinishReason:this.lastStep.reason}:{},runId:this.runId,threadId:this.params.threadId,agent:this.config.name,depth:this.depth,context:this.context,signal:this.controller.signal})}catch(Y){if(Y instanceof w||this.controller.signal.aborted)throw Y;return{error:{code:"unknown",message:`prepareStep threw: ${Y instanceof Error?Y.message:String(Y)}`,retryable:!1}}}if(!K)continue;if(K.messages!==void 0){if(!Array.isArray(K.messages))return{error:{code:"unknown",message:"prepareStep answered `messages` that is not an array.",retryable:!1}};J=K.messages}if(K.instructions!==void 0)W=K.instructions||void 0}return{messages:J,instructions:W}}async systemPrompt(){let $=[this.config.instructions,this.params.instructions].filter((Q)=>Boolean(Q&&Q.trim()));return $.length>0?$.join(`
18
-
19
- `):void 0}async runTools($,Q,Z){let V=[],G=[];for(let J of Q){let W=this.config.registry.get(String(J.name));if(!W){this.addResult($,{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(J.name)}".`,toolCallId:J.toolCallId,retryable:!0}});continue}let X=W.inputSchema.safeParse(J.input);if(X.ok===!1){this.addResult($,{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(J.name)}": ${X.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}});continue}J.input=X.value;let K=rQ(W.tool);if(K){if(this.onPending==="deny"){this.addResult($,this.deniedByPolicy(J));continue}V.push({toolCallId:J.toolCallId,name:J.name,input:X.value,kind:K,signature:QZ(this.claimsFor(J.toolCallId,String(J.name),K,X.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}G.push(this.executeTool(W,$.id,J,X.value,Z).then(async(Y)=>{this.addResult($,Y),await this.settleShown(J.toolCallId)}).catch((Y)=>{if(Y instanceof d){if(this.onPending==="deny"){this.addResult($,this.deniedByPolicy(J));return}V.push(...Y.pending);return}}))}return await c(Promise.all(G).then(()=>{return}),this.controller.signal),V}claimsFor($,Q,Z,V){return{runId:this.signingRunId,toolCallId:$,name:Q,kind:Z,input:V,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0,subject:this.params.subject??null}}deniedByPolicy($){return{type:"tool-result",toolCallId:$.toolCallId,name:$.name,status:"denied",cause:"refused",reason:`"${String($.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool($,Q,Z,V,G,J){let W=$.tool.timeoutMs;if(W===void 0)return this.runToolBody($,Q,Z,V,G,J,this.controller.signal,()=>!1);let X=new AbortController,K=this.controller.signal,Y=()=>X.abort(K.reason);if(K.aborted)Y();else K.addEventListener("abort",Y,{once:!0});let H=!1,B=this.runToolBody($,Q,Z,V,G,J,X.signal,()=>H),z=()=>{},D=new Promise((L)=>{z=iQ(W,()=>{let F=`"${String(Z.name)}" did not finish within ${O$(W)} (timeoutMs: ${W}) and was cancelled.`;X.abort(new DOMException(F,"TimeoutError")),L({type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"timeout",message:F,toolCallId:Z.toolCallId,retryable:!0}})})});B.catch(()=>{});try{return await Promise.race([B,D])}finally{H=!0,z()}}async runToolBody($,Q,Z,V,G,J,W,X){let K=this.toolFiles(Z,W),Y={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:W,step:G,depth:this.depth,resumed:J!==void 0,attachments:K.attachments,generateImage:K.generateImage,editImage:K.editImage,turn:this.toolTurn(Q),runAgent:this.nestedRunner(Q,Z,W,J),generate:(H)=>this.generateForTool(H,W,Z.toolCallId),jobs:jQ({jobs:this.depth===0?this.params.jobs:void 0,threadId:this.params.threadId,runId:this.runId,toolCallId:Z.toolCallId,toolName:String(Z.name),depth:this.depth,async:$.tool.async,attachments:this.params.attachments??null})};try{let H=$.tool.execute(V,Y),B;if(B8(H)){let z=await H.next();while(!z.done){if(X())throw H.return(void 0).catch(()=>{}),new w;this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:z.value}),z=await H.next()}B=z.value}else B=await H;if(RQ(B)){if(B.toolCallId!==Z.toolCallId)throw new j(`"${String(Z.name)}" returned the handle of a job another tool call started. Return the handle from this call's own ctx.jobs.`,{retryable:!1});return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"running",job:{id:B.id,...B.summary!==void 0?{summary:B.summary}:{}}}}return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:B}}catch(H){if(H instanceof w||this.controller.signal.aborted)throw new w;if(H instanceof d)throw H;let B=H instanceof j;if(!B&&this.config.logErrors)this.logToolFailure(Z,H);let z={code:"tool_error",message:H instanceof Error?H.message:String(H),toolCallId:Z.toolCallId,retryable:B?H.retryable:!0};return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:this.redact(z,{source:"tool",toolName:String(Z.name),cause:H})}}}async generateForTool($,Q,Z){let V=this.controller.signal;return K9({...$,signal:$.signal?AbortSignal.any([Q,$.signal]):Q},{origin:{agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},toolCallId:Z},settled:(G)=>{if(this.usage=M(this.usage,G.usage),V.aborted)throw new w}})}nestedRunner($,Q,Z,V){let G=new M$(()=>Q.nested,()=>Q.nested=[]);return async(J,W={})=>{let{at:X,recorded:K,write:Y}=G.next();if(K){let H=L8(K,J,W);if(H)throw new j(`Nested run ${X} of "${String(Q.name)}" ${H}. `+"runAgent is memoized by call index, so a body whose runAgent calls depend on a condition that changed between turns cannot be resumed \u2014 the answer would be paired with a different sub-run. "+"Make the sequence of runAgent calls, and what each one is asked, the same every time this tool runs, or branch on ctx.resumed.");if(K.finishReason!=="awaiting-input")return{runId:K.runId,agent:K.agent,messages:K.messages,finishReason:K.finishReason??"stop",usage:K.usage??R(),output:oQ(K.messages),nested:K}}return this.runNested($,Q,Z,J,W,Y,K,V?.answers??[])}}async runNested($,Q,Z,V,G,J,W,X){let K=[...this.chain,V.name];if(this.chain.includes(V.name))throw new j(`"${V.name}" is already running further up this chain: ${K.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let Y=this.depth+1;if(Y>this.maxDepth)throw new j(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${Y}: ${K.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let H=G.label,B=[...this.pathPrefix,Q.toolCallId],z=this.onPending==="deny"?"deny":G.onPending??"escalate",D=W!==void 0,L=D?u9(W.messages):new Set,F=D?X.filter((C)=>{let N=aQ(C.path,B);if(N===null)return!1;return L.has(N.length>0?N[0]:C.toolCallId)}):[],U=V.stream({messages:D?W.messages:G.messages??[],turn:D?{toolResults:F}:G.prompt?{text:G.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:Z,threadId:this.params.threadId,redactError:this.params.redactError,nonces:this.params.nonces,receipts:this.params.receipts,subject:this.params.subject,instructions:G.instructions,maxOutputTokens:G.maxOutputTokens,temperature:G.temperature,runId:D?W.runId:void 0,nesting:{depth:Y,maxDepth:this.maxDepth,chain:K,signingRunId:this.signingRunId,signingPath:B,onPending:z}}),P=[],q=(C)=>this.emit({type:"nested-event",toolCallId:Q.toolCallId,runId:U.runId,agent:V.name,label:H,event:C}),_=(async()=>{for await(let C of U){if(C.type==="awaiting-input")P=C.pending;if(q(C),C.type==="run-start"&&!D)for(let N of G.messages??[])q({type:"message",message:N});if(C.type==="error")this.emit({type:"error",error:C.error,nested:{toolCallId:Q.toolCallId,runId:U.runId,agent:V.name}})}})(),O=(async()=>{let C=await U.result();await _;let N=D?nQ(W.messages,C.messages):nQ(G.messages??[],C.messages),T={runId:U.runId,agent:V.name,label:H,messages:N,finishReason:C.finishReason,usage:D?M(W.usage??R(),C.usage):C.usage,...C.finishReason==="awaiting-input"?{signature:GZ({runId:this.signingRunId,path:B,nestedRunId:U.runId,open:[...u9(N)],input:Q.input,subject:this.params.subject??null})}:{}};return J(T),this.usage=M(this.usage,C.usage),{result:C,record:T}})(),A=O.then(()=>{return},()=>{return});this.nestedSettling.add(A);let k,x;try{({result:k,record:x}=await O)}finally{this.nestedSettling.delete(A)}if(this.controller.signal.aborted)throw new w;if(k.finishReason==="awaiting-input"){if(P.length===0)throw new j(`"${V.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:$,part:Q,resent:!0}),new d({pending:P,path:B,nested:x})}return{runId:x.runId,agent:V.name,messages:x.messages,finishReason:k.finishReason,usage:x.usage??R(),output:k.output??oQ(x.messages),...k.error?{error:k.error}:{},nested:x}}addResult($,Q){$.content.push(Q),this.emit({type:"tool-result",messageId:$.id,part:Q})}toolFiles($,Q){let Z=this.params.attachments??null,V=new M$(()=>$.attachments,()=>$.attachments=[],()=>({failed:!0})),G=()=>{if(!Z)throw new g("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return Z},J=async(Y,H,B)=>{let z=G(),D=H.mimeType||Y.type||"",L=H.name??(Y instanceof File?Y.name:"attachment"),F;if(H.showModel){let P=this.config.provider;if(!P.capabilities.fileInput)throw new j(`"${String($.name)}" asked to show a file to ${P.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);F=await P.upload(new File([Y],L,{type:D||void 0}))}return{attachment:await z.put(Y,{name:L,mimeType:D,fileId:F}),...B?{generated:B}:{},...F?{shown:{fileId:F,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},W=(Y,H,B)=>{let z=Y.generated?"image":"put";if(z===H)return;throw new j(`Attachment ${B} of "${String($.name)}" was ${z==="image"?"a generated image":"a stored file"} on the first attempt and is ${H==="image"?"a generated image":"a stored file"} now. ctx.attachments.put, ctx.generateImage and ctx.editImage share one memo indexed by call order within a tool call, so the sequence has to be the same every time this tool runs. Branch on ctx.resumed if it cannot be.`)},X=async(Y,H,B)=>{let{at:z,recorded:D,write:L}=V.next();if(D&&"attachment"in D){if(W(D,"image",z),D.shown)this.queueShown($.toolCallId,D);return{attachment:D.attachment,size:D.generated.size,mimeType:D.attachment.mimeType,usage:D.generated.usage}}let F=await B();this.usage=M(this.usage,F.usage);let U=F.mimeType==="image/jpeg"?"jpg":"png",P=await J(F.image,{name:H.name??`${Y.name}.${U}`,mimeType:F.mimeType,...H.showModel?{showModel:!0}:{}},{size:F.size,usage:F.usage});if(L(P),P.shown)this.queueShown($.toolCallId,P);return{attachment:P.attachment,size:F.size,mimeType:F.mimeType,usage:F.usage}},K=async(Y)=>typeof Y==="string"?await G().file(Y):Y;return{generateImage:(Y,H)=>X(Y,H,()=>Y.generate({...H,signal:Q})),editImage:(Y,H)=>X(Y,H,async()=>{let{images:B,mask:z,...D}=H;return await Y.edit({...D,images:await Promise.all(B.map(K)),...z?{mask:await K(z)}:{},signal:Q})}),attachments:{get:(Y)=>G().get(Y),read:(Y)=>G().read(Y),file:(Y)=>G().file(Y),put:async(Y,H={})=>{let{at:B,recorded:z,write:D}=V.next();if(z&&"attachment"in z){W(z,"put",B);let F=F8(z,Y,H);if(F)throw new j(`Attachment ${B} of "${String($.name)}" ${F}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(z.shown)this.queueShown($.toolCallId,z);return z.attachment}let L=await J(Y,H);if(D(L),L.shown)this.queueShown($.toolCallId,L);return L.attachment}}}}toolTurn($){let Q=this.history.findIndex((J)=>J.id===$),Z=m(this.history),V;for(let J=Q-1;J>=0;J--){let W=this.history[J];if(W.role!=="user"||Z.has(W.id))continue;V=W;break}let G=[];for(let J of V?.content??[]){if(J.type!=="file")continue;let W=J.attachmentId;if(typeof W!=="string"||!W.startsWith(v))continue;if(!G.includes(W))G.push(W)}return Object.freeze({attachments:Object.freeze(G)})}queueShown($,Q){let Z=Q.shown;if(!Z)return;let V=this.shownQueue.get($)??[];if(V.some((G)=>G.id===Z.messageId))return;V.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:Q.attachment.name,mimeType:Q.attachment.mimeType,attachmentId:Q.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set($,V)}async settleShown($){let Q=this.shownQueue.get($);if(!Q||Q.length===0)return;if(this.shownQueue.delete($),this.ended||this.controller.signal.aborted)return;for(let Z of Q){if(this.history.some((V)=>V.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider($){let Q=this.history.filter((J)=>J!==$),Z=m(Q),V=[];for(let J of Q){if(!Z.has(J.id))continue;for(let W of J.content)if(W.type==="file")V.push(W)}if(V.length<=tQ)return Q;let G=new Set(V.slice(0,V.length-tQ));return Q.map((J)=>{if(!J.content.some((W)=>W.type==="file"&&G.has(W)))return J;return{...J,content:J.content.map((W)=>W.type==="file"&&G.has(W)?{type:"text",text:`[A ${W.mimeType||"file"} produced by a tool (attachment ${W.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:W)}})}async ingestTurn(){let $=this.params.turn,Q=this.openCalls(),Z=[];if(Q.length>0){let V=new Set,G=new Set,J=new Map;for(let W of $?.toolResults??[]){let X=`${(W.path??[]).join("/")}#${W.toolCallId}`;if(G.has(X))continue;G.add(X);let K=(z)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:W.toolCallId,retryable:!1}}),Y=aQ(W.path,this.pathPrefix);if(Y===null){K(`The answer for "${W.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(Y.length>0){let z=Y[0],D=Q.find((U)=>U.call.toolCallId===z);if(!D){K(`No pending tool call with id "${z}" to deliver a nested answer to.`);continue}let L=this.parkedBelow(D.call,Y,W.toolCallId);if(L.ok===!1){let U=`The answer for "${W.toolCallId}" is addressed under "${z}", which`;K(L.reason==="unparked"?`${U} has no sub-agent run waiting on that question.`:L.reason==="expired"?`${U} parked a sub-agent run that has since expired. Ask again.`:`${U} carries a record of a parked sub-agent run the server did not sign.`);continue}let F=J.get(z);if(!F){if(!await this.spend(XZ,L.signature)){K(`The answer for "${W.toolCallId}" is addressed under "${z}", which has already been re-entered on that record. Ask again.`);continue}F=[],J.set(z,F),V.add(z)}F.push(W);continue}let H=Q.find((z)=>z.call.toolCallId===W.toolCallId);if(!H){K(`No pending tool call with id "${W.toolCallId}".`);continue}let B=await this.resolveAnswer(H,W,Z);if(B===null)continue;if(V.add(W.toolCallId),B!=="open")this.attachToHistory(H,B),await this.settleShown(W.toolCallId)}for(let[W,X]of J){let K=Q.find((H)=>H.call.toolCallId===W),Y=await this.reenter(K,X,Z);if(Y)this.attachToHistory(K,Y),await this.settleShown(W)}for(let W of Q){if(V.has(W.call.toolCallId))continue;this.attachToHistory(W,{type:"tool-result",toolCallId:W.call.toolCallId,name:W.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if($&&($.text||$.files&&$.files.length>0)){let V={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...$.text?[{type:"text",text:$.text}]:[],...($.files??[]).map((G)=>({type:"file",...G.fileId?{fileId:G.fileId}:{},name:G.name,mimeType:G.mimeType,...G.attachmentId?{attachmentId:G.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};if(this.history.push(V),this.produced.push(V),this.depth>0)this.emit({type:"message",message:V});else if($.localId)this.emit({type:"message-id",localId:$.localId,messageId:V.id,message:V});if(await this.report(V),this.params.onTurn)try{await this.params.onTurn(V)}catch{}}return Z}parkedBelow($,Q,Z){let V=Q.length>1?Q[1]:Z,G=[...this.pathPrefix,$.toolCallId],J=($.nested??[]).find((X)=>X.finishReason==="awaiting-input"&&u9(X.messages).has(V));if(!J)return{ok:!1,reason:"unparked"};if(typeof J.signature!=="string")return{ok:!1,reason:"unsigned"};let W=JZ(J.signature,{path:G,nestedRunId:J.runId,open:[...u9(J.messages)],input:$.input,subject:this.params.subject??null});if(W.ok===!1)return{ok:!1,reason:W.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:J.signature}}async reenter($,Q,Z){let V=String($.call.name),G=this.config.registry.get(V);if(!G||!G.tool.execute)return{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${V}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:$.call.toolCallId,retryable:!1}};let J=G.inputSchema.safeParse($.call.input);if(J.ok===!1)return{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${V}": ${J.errors.join(", ")}`,toolCallId:$.call.toolCallId,retryable:!0}};let W=this.amendCall($);W.input=J.value;try{return await c(this.executeTool(G,$.message.id,W,J.value,0,{answers:Q}),this.controller.signal)}catch(X){if(X instanceof d)return Z.push(...X.pending),null;throw X}}amendCall($){let Q=this.amend($.message),Z=Q.content.indexOf($.call),V={...$.call,nested:($.call.nested??[]).map((G)=>({...G})),...$.call.attachments?{attachments:$.call.attachments.map((G)=>({...G}))}:{}};if(Z>=0)Q.content[Z]=V;return this.unreported.add(Q),V}openCalls(){let $=new Set;for(let Z of this.history)for(let V of Z.content)if(V.type==="tool-result")$.add(V.toolCallId);let Q=[];for(let Z of this.history)for(let V of Z.content)if(V.type==="tool-call"&&!$.has(V.toolCallId))Q.push({message:Z,call:V});return Q}async spend($,Q){try{return await $(Q,this.params.nonces??C9)}catch(Z){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not spend a nonce`,{error:Z}),!1}}async recordReceipt($,Q){let Z=await Q;try{await $.store.complete($.id,Z,$.expiresAt)}catch(V){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record a tool receipt`,{error:V})}return Z}async resolveAnswer($,Q,Z){let V=$.call,G=String(V.name),J=this.config.registry.get(G),W=(B)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:B,toolCallId:V.toolCallId,retryable:!1}}),null};if(!J)return W(`The tool "${G}" no longer exists, so its answer cannot be checked.`);let X=rQ(J.tool);if(!X)return W(`"${G}" is a server tool with no pending question.`);if(typeof Q.signature!=="string"||Q.signature.length===0)return W(`The answer for "${G}" carried no signature.`);let K=ZZ(Q.signature);if(!K)return W(`The signature for "${G}" is malformed.`);let Y=VZ(Q.signature,{...this.claimsFor(V.toolCallId,G,X,V.input),runId:K.runId});if(Y.ok===!1)return W(Y.reason==="expired"?`The approval for "${G}" has expired. Ask again.`:`The answer for "${G}" does not match the call the server made.`);let H;if(this.params.receipts&&X==="approval"&&"approve"in Q&&Q.approve===!0){let B=this.params.receipts,z=WZ(this.config.name,{...this.claimsFor(V.toolCallId,G,X,V.input),runId:K.runId}),D;try{D=await B.claim(z,K.expiresAt)}catch(L){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not claim a tool receipt`,{error:L}),W(`The approval for "${G}" could not be checked. Ask again.`)}if(D.status==="replay")return{...D.result,toolCallId:V.toolCallId,name:V.name};if(D.status==="blocked")return{type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"error",error:{code:"tool_error",message:`"${G}" was already approved and started, and its result is not recorded yet: it is still running, or it stopped before finishing. It was not run again.`,toolCallId:V.toolCallId,retryable:!1}};H={store:B,id:z,expiresAt:K.expiresAt}}if(!await this.spend(YZ,Q.signature))return await H?.store.release(H.id).catch((B)=>{this.writeLog(`[gemi/ai] agent "${this.config.name}" could not release a tool receipt`,{error:B})}),W(`The answer for "${G}" has already been used. Ask again.`);if("approve"in Q){if(X!=="approval")return W(`"${G}" is answered by the client, not approved.`);if(Q.approve===!0){let B=this.amendCall($),z=this.executeTool(J,$.message.id,B,B.input,0);try{return await c(H?this.recordReceipt(H,z):z,this.controller.signal)}catch(D){if(D instanceof d)return Z.push(...D.pending),"open";throw D}}return{type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"refused",reason:Q.reason}}if("output"in Q){if(X==="approval")return W(`"${G}" is approved, not answered: the server produces its result.`);let B=J.tool.outputSchema,z=B?B.safeParse(Q.output):{ok:!0,value:Q.output};if(z.ok===!1)return{type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${G}" did not match its output schema: ${z.errors.join(", ")}`,toolCallId:V.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"ok",output:z.value}}return W(`The answer for "${G}" carried neither an approval nor an output.`)}attachToHistory($,Q){let Z=this.amend($.message);Z.content.push(Q),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:Q})}markFileRejected($,Q,Z){for(let W of this.history){if(!W.content.some((Y)=>Y.type==="file"&&Y.fileId===$&&!Y.providerRejected))continue;let K=this.produced.includes(W)?W:this.amend(W);if(K.content=K.content.map((Y)=>Y.type==="file"&&Y.fileId===$&&!Y.providerRejected?{...Y,providerRejected:!0}:Y),K!==this.current)this.unreported.add(K)}if(!this.config.logErrors)return;let V=`[gemi/ai] agent "${this.config.name}": the provider refused file ${$}${Z.status!==void 0?` (${Z.status})`:""}; it was left out of the request and will not be sent again: ${Q}`,G={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},fileId:$,...Z},J=!1;try{X9.warning(V,G),J=!0}catch{}if(!J||Bun.env.NODE_ENV==="development")console.warn(V,G)}amend($){let Q=this.amended.get($.id);if(Q)return Q;let Z={...$,content:[...$.content]},V=this.history.indexOf($);if(V>=0)this.history[V]=Z;return this.produced.push(Z),this.amended.set($.id,Z),Z}async reportDeferred(){let $=[...this.unreported];this.unreported.clear();for(let Q of $)await this.report(Q)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let Q of this.openCalls()){if(Q.message===this.current)continue;this.attachToHistory(Q,{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let $=this.current;if($){let Q=new Set($.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...$.content]){if(Z.type!=="tool-call"||Q.has(Z.toolCallId))continue;delete Z.partial,this.addResult($,{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"stopped",reason:this.stopReason})}}if(this.timedOutAfter!==void 0){this.fail({code:"timeout",message:`The run did not finish within its time limit of ${O$(this.timedOutAfter)} (maxRunDurationMs: ${this.timedOutAfter}) and was stopped.`,retryable:!0}),this.finishReason="error",await this.finalizeMessage("error");return}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function rQ($){if($.answeredBy==="client")return $.inputSchema===R$?"question":"client";return $.requiresApproval?"approval":null}function eQ($){if(!$||!$.trim())return{};try{return JSON.parse($)}catch{return $}}class k$ extends DZ{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await y.sweep({limit:100})===100);}}var m9=20;function LZ($,Q){if(Q<=0||$.length===0)return null;let Z=(J,W)=>W.createdAt-J.createdAt||(J.id<W.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.",...[...$.filter((J)=>J.state==="running").sort(Z),...$.filter((J)=>J.state!=="running").sort(Z)].slice(0,Q).map((J)=>{let W=[`- ${J.id} (${J.toolName})`];if(J.state==="running")W.push(`running since ${x$(J.createdAt)}`);else if(J.state==="ok")W.push(`finished at ${x$(J.settledAt??J.updatedAt)}`);else{let X=J.error?`${J.error.code}: ${FZ(J.error.message,200)}`:"failed";W.push(`failed at ${x$(J.settledAt??J.updatedAt)} (${X})`)}if(J.summary!==void 0)W.push(`summary: ${FZ(JSON.stringify(J.summary),300)}`);if(J.orphaned)W.push("its tool call was lost when the turn that started it was cut short");return W.join("; ")}),"</jobs>"].join(`
20
- `)}function x$($){return new Date($).toISOString().replace(/\.\d{3}Z$/,"Z")}function FZ($,Q){return $.length<=Q?$:`${$.slice(0,Q-1)}\u2026`}class w${table;sql;dialect;connection;constructor($,Q={}){let Z=Q.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Z))throw Error(`The agent jobs table name "${Z}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Z,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of U8(this.dialect,this.table))await this.sql.unsafe($)}async transaction($){if(this.connection===void 0||this.joinable())return $();return OZ(this.sql,()=>$(),{connection:this.connection})}async create($){let Q=this.q(),Z=this.clock(Q);await Q`
2
+ import{$b as p,Ac as S9,Bc as M9,Cc as A9,Dc as R9,Ec as T9,Fc as j9,Gc as k9,Hc as E9,Ic as q9,Jc as x9,Kc as w9,Lc as QQ,Mc as I9,Nc as h$,Oc as b9,Pc as v9,Qc as QJ,Rc as jJ,Sc as f9,Tc as h9,Uc as y9,Vb as HQ,Vc as g9,Wb as q$,Wc as u9,Xb as DQ,Xc as c9,_b as q,ac as TJ,bc as zQ,cc as x$,dc as w$,ec as I$,fc as b,gc as b$,hc as LJ,ic as v$,jc as f$,kc as CJ,lc as MQ,mc as AQ,oc as RQ,pc as w,qc as H$,rc as D$,sc as TQ,uc as jQ,vc as h,wc as IQ,xc as g,yc as R,zc as BQ}from"../chunk-7vrrgxwm.js";import{nd as PQ}from"../chunk-t6qpm2j7.js";import"../chunk-h8w9mzjj.js";import{Ng as R$,Nh as k$,Qg as j$,Qh as rJ,Uh as E$,eh as C9,fh as O9,gh as _9,hh as d}from"../chunk-6wgh7nk6.js";import{Vh as T$,Xh as FJ,Yh as NJ}from"../chunk-erzfs4t2.js";import{di as n}from"../chunk-tabsxzg9.js";import"../chunk-rany5zgk.js";import"../chunk-sv125fqq.js";import{fj as OQ,gj as _Q,uj as SQ}from"../chunk-vhvvjaj3.js";import"../chunk-npbf06c1.js";import{hk as J$}from"../chunk-6gwxvmjv.js";import"../chunk-rwmja4zs.js";import"../chunk-z5nfve1k.js";import"../chunk-yhht1j7f.js";import"../chunk-hxn0s3zh.js";class _J extends PQ{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await w.sweep({limit:100})===100);}}var r=20;function NQ(J,Q){if(Q<=0||J.length===0)return null;let $=(G,V)=>V.createdAt-G.createdAt||(G.id<V.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((G)=>G.state==="running").sort($),...J.filter((G)=>G.state!=="running").sort($)].slice(0,Q).map((G)=>{let V=[`- ${G.id} (${G.toolName})`];if(G.state==="running")V.push(`running since ${SJ(G.createdAt)}`);else if(G.state==="ok")V.push(`finished at ${SJ(G.settledAt??G.updatedAt)}`);else{let K=G.error?`${G.error.code}: ${FQ(G.error.message,200)}`:"failed";V.push(`failed at ${SJ(G.settledAt??G.updatedAt)} (${K})`)}if(G.summary!==void 0)V.push(`summary: ${FQ(JSON.stringify(G.summary),300)}`);if(G.orphaned)V.push("its tool call was lost when the turn that started it was cut short");return V.join("; ")}),"</jobs>"].join(`
3
+ `)}function SJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function FQ(J,Q){return J.length<=Q?J:`${J.slice(0,Q-1)}\u2026`}class AJ{table;sql;dialect;connection;constructor(J,Q={}){let $=Q.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The agent jobs table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);this.table=$,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of p$(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return SQ(this.sql,()=>J(),{connection:this.connection})}async create(J){let Q=this.q(),$=this.clock(Q);await Q`
21
4
  INSERT INTO ${this.name(Q)}
22
5
  (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
23
6
  orphaned, attachment_scope, created_at, updated_at, deadline_at)
24
7
  VALUES
25
- (${$.id}, ${$.threadId}, ${$.runId}, ${$.toolCallId}, ${$.toolName},
26
- ${$.owner}, ${$.job}, ${l9($.summary)}, 'running', 0, ${$.attachmentScope},
27
- ${Z}, ${Z}, ${Z} + ${this.ms(Q,$.deadlineMs)})
28
- `;let V=await this.get($.id);if(!V)throw Error(`The background job ${$.id} was not found after it was written.`);return V}async get($){let Q=this.q(),Z=await Q`SELECT * FROM ${this.name(Q)} WHERE id = ${$}`;return Z[0]?I$(Z[0]):null}async listForThread($,Q={}){let Z=this.q(),V=Q.states===void 0?Z`1 = 1`:Q.states.length===0?Z`1 = 0`:Z`state IN (${UZ(Z,Q.states)})`;return(Q.limit===void 0?await Z`
29
- SELECT * FROM ${this.name(Z)}
30
- WHERE thread_id = ${$} AND ${V}
8
+ (${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
9
+ ${J.owner}, ${J.job}, ${e(J.summary)}, 'running', 0, ${J.attachmentScope},
10
+ ${$}, ${$}, ${$} + ${this.ms(Q,J.deadlineMs)})
11
+ `;let Z=await this.get(J.id);if(!Z)throw Error(`The background job ${J.id} was not found after it was written.`);return Z}async get(J){let Q=this.q(),$=await Q`SELECT * FROM ${this.name(Q)} WHERE id = ${J}`;return $[0]?MJ($[0]):null}async listForThread(J,Q={}){let $=this.q(),Z=Q.states===void 0?$`1 = 1`:Q.states.length===0?$`1 = 0`:$`state IN (${LQ($,Q.states)})`;return(Q.limit===void 0?await $`
12
+ SELECT * FROM ${this.name($)}
13
+ WHERE thread_id = ${J} AND ${Z}
31
14
  ORDER BY created_at DESC, id DESC
32
- `:await Z`
33
- SELECT * FROM ${this.name(Z)}
34
- WHERE thread_id = ${$} AND ${V}
15
+ `:await $`
16
+ SELECT * FROM ${this.name($)}
17
+ WHERE thread_id = ${J} AND ${Z}
35
18
  ORDER BY created_at DESC, id DESC
36
19
  LIMIT ${Math.max(0,Math.floor(Q.limit))}
37
- `).map(I$)}async transition($,Q,Z){if(Q.length===0)return!1;let V=this.q(),G=this.clock(V),J=[V`updated_at = ${G}`];if(Z.state!==void 0)J.push(V`state = ${Z.state}`);if("output"in Z)J.push(V`output = ${l9(Z.output)}`);if("error"in Z)J.push(V`error = ${l9(Z.error)}`);if("usage"in Z)J.push(V`${this.column(V,"usage")} = ${l9(Z.usage)}`);if("orphaned"in Z)J.push(V`orphaned = ${Z.orphaned?1:0}`);if(Z.state!==void 0&&Z.state!=="running")J.push(Z.settledAt!==void 0?V`settled_at = COALESCE(settled_at, ${this.ms(V,Z.settledAt)})`:V`settled_at = COALESCE(settled_at, ${G})`);let W=J.reduce((K,Y)=>V`${K}, ${Y}`),X=await V`
38
- UPDATE ${this.name(V)} SET ${W}
39
- WHERE id = ${$} AND state IN (${UZ(V,Q)})
40
- `;return PZ(X)>0}async overdue($,Q){let Z=this.q();return(await Z`
41
- SELECT * FROM ${this.name(Z)}
42
- WHERE state = 'running' AND deadline_at <= ${this.ms(Z,$)}
20
+ `).map(MJ)}async transition(J,Q,$){if(Q.length===0)return!1;let Z=this.q(),W=this.clock(Z),G=[Z`updated_at = ${W}`];if($.state!==void 0)G.push(Z`state = ${$.state}`);if("output"in $)G.push(Z`output = ${e($.output)}`);if("error"in $)G.push(Z`error = ${e($.error)}`);if("usage"in $)G.push(Z`${this.column(Z,"usage")} = ${e($.usage)}`);if("orphaned"in $)G.push(Z`orphaned = ${$.orphaned?1:0}`);if($.state!==void 0&&$.state!=="running")G.push($.settledAt!==void 0?Z`settled_at = COALESCE(settled_at, ${this.ms(Z,$.settledAt)})`:Z`settled_at = COALESCE(settled_at, ${W})`);let V=G.reduce((Y,X)=>Z`${Y}, ${X}`),K=await Z`
21
+ UPDATE ${this.name(Z)} SET ${V}
22
+ WHERE id = ${J} AND state IN (${LQ(Z,Q)})
23
+ `;return CQ(K)>0}async overdue(J,Q){let $=this.q();return(await $`
24
+ SELECT * FROM ${this.name($)}
25
+ WHERE state = 'running' AND deadline_at <= ${this.ms($,J)}
43
26
  ORDER BY deadline_at, id
44
27
  LIMIT ${Math.max(0,Math.floor(Q))}
45
- `).map(I$)}async now(){let $=this.q(),[Q]=await $`SELECT ${this.clock($)} AS now`;return Number(Q.now)}async prune($){let Q=this.q(),Z=await Q`
28
+ `).map(MJ)}async now(){let J=this.q(),[Q]=await J`SELECT ${this.clock(J)} AS now`;return Number(Q.now)}async prune(J){let Q=this.q(),$=await Q`
46
29
  DELETE FROM ${this.name(Q)}
47
- WHERE state <> 'running' AND settled_at <= ${this.clock(Q)} - ${this.ms(Q,$)}
48
- `;return PZ(Z)}joinable(){if(this.connection===void 0)return;let $=NZ();if($===void 0||CZ()!==this.connection)return;return $}q(){return this.joinable()??this.sql}column($,Q){let Z=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Z?`\`${Q}\``:`"${Q}"`)}name($){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Q?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,Q){let Z=Math.max(0,Math.round(Q));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${Z} AS SIGNED)`:$`CAST(${Z} AS BIGINT)`}}function UZ($,Q){return Q.map((Z)=>$`${Z}`).reduce((Z,V)=>$`${Z}, ${V}`)}function l9($){return $===void 0?null:JSON.stringify($)}function d9($){if($===null||$===void 0)return;return JSON.parse(String($))}function I$($){let Q=d9($.summary),Z=d9($.output),V=d9($.error),G=d9($.usage);return{id:String($.id),threadId:String($.thread_id),runId:String($.run_id),toolCallId:String($.tool_call_id),toolName:String($.tool_name),owner:$.owner===null||$.owner===void 0?null:String($.owner),job:$.job===null||$.job===void 0?null:String($.job),...Q!==void 0?{summary:Q}:{},state:String($.state),...Z!==void 0?{output:Z}:{},...V!==void 0?{error:V}:{},...G!==void 0?{usage:G}:{},...Number($.orphaned)===1?{orphaned:!0}:{},attachmentScope:$.attachment_scope===null||$.attachment_scope===void 0?null:String($.attachment_scope),createdAt:Number($.created_at),updatedAt:Number($.updated_at),deadlineAt:Number($.deadline_at),...$.settled_at===null||$.settled_at===void 0?{}:{settledAt:Number($.settled_at)}}}function PZ($){let Q=$;return Math.max(Number(Q.count??0),Number(Q.affectedRows??0))}function U8($,Q){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Q}\` (
30
+ WHERE state <> 'running' AND settled_at <= ${this.clock(Q)} - ${this.ms(Q,J)}
31
+ `;return CQ($)}joinable(){if(this.connection===void 0)return;let J=OQ();if(J===void 0||_Q()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,Q){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${Q}\``:`"${Q}"`)}name(J){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,Q){let $=Math.max(0,Math.round(Q));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${$} AS SIGNED)`:J`CAST(${$} AS BIGINT)`}}function LQ(J,Q){return Q.map(($)=>J`${$}`).reduce(($,Z)=>J`${$}, ${Z}`)}function e(J){return J===void 0?null:JSON.stringify(J)}function JJ(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function MJ(J){let Q=JJ(J.summary),$=JJ(J.output),Z=JJ(J.error),W=JJ(J.usage);return{id:String(J.id),threadId:String(J.thread_id),runId:String(J.run_id),toolCallId:String(J.tool_call_id),toolName:String(J.tool_name),owner:J.owner===null||J.owner===void 0?null:String(J.owner),job:J.job===null||J.job===void 0?null:String(J.job),...Q!==void 0?{summary:Q}:{},state:String(J.state),...$!==void 0?{output:$}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number(J.orphaned)===1?{orphaned:!0}:{},attachmentScope:J.attachment_scope===null||J.attachment_scope===void 0?null:String(J.attachment_scope),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),deadlineAt:Number(J.deadline_at),...J.settled_at===null||J.settled_at===void 0?{}:{settledAt:Number(J.settled_at)}}}function CQ(J){let Q=J;return Math.max(Number(Q.count??0),Number(Q.affectedRows??0))}function p$(J,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Q}\` (
49
32
  \`id\` VARCHAR(191) NOT NULL,
50
33
  \`thread_id\` VARCHAR(191) NOT NULL,
51
34
  \`run_id\` VARCHAR(191) NOT NULL,
@@ -68,10 +51,10 @@ data: ${JSON.stringify(X.event)}
68
51
  INDEX \`${Q}_thread_id_created_at_idx\`(\`thread_id\`, \`created_at\`),
69
52
  INDEX \`${Q}_state_deadline_at_idx\`(\`state\`, \`deadline_at\`),
70
53
  PRIMARY KEY (\`id\`)
71
- ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let Z=$==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',V=$==="sqlite"?"":`,
54
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let $=J==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',Z=J==="sqlite"?"":`,
72
55
 
73
56
  CONSTRAINT "${Q}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${Q}" (
74
- ${Z}
57
+ ${$}
75
58
  "thread_id" TEXT NOT NULL,
76
59
  "run_id" TEXT NOT NULL,
77
60
  "tool_call_id" TEXT NOT NULL,
@@ -88,18 +71,18 @@ data: ${JSON.stringify(X.event)}
88
71
  "created_at" BIGINT NOT NULL,
89
72
  "updated_at" BIGINT NOT NULL,
90
73
  "deadline_at" BIGINT NOT NULL,
91
- "settled_at" BIGINT${V}
92
- )`,`CREATE INDEX IF NOT EXISTS "${Q}_thread_id_created_at_idx" ON "${Q}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_state_deadline_at_idx" ON "${Q}"("state", "deadline_at")`]}var P8=/^[A-Za-z0-9_-]{1,64}$/;function N8($,Q){let Z=C8(Q)?Q:{filter:Q},V=Z.deferred===!0,G=$.descriptors(Z.filter);if(!Z.namespaces)return G.map((H)=>b$($,H,V));let J=Object.entries(Z.namespaces),W=new Set($.descriptors().flatMap((H)=>H.tags));for(let[H,B]of J){if(!P8.test(H))throw Error(`toAgentTools: "${H}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof B?.description!=="string"||B.description.trim()==="")throw Error(`toAgentTools: the namespace "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!W.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let X=new Map(J.map(([H])=>[H,[]])),K=[];for(let H of G){let B=J.find(([z])=>H.tags.includes(z))?.[0];if(B===void 0)K.push(b$($,H,V));else X.get(B).push(b$($,H,!1))}let Y=[];for(let[H,B]of J){let z=X.get(H);if(z.length===0)continue;Y.push(e.create({name:H,description:B.description,tools:z,deferred:B.deferred??V}))}return[...Y,...K]}function C8($){return typeof $==="object"&&$!==null&&(("filter"in $)||("namespaces"in $)||("deferred"in $))}function b$($,Q,Z){return i.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:Z,execute:(V,G)=>{let J=p9.getStore()?.req;if(!J)throw new j(`"${Q.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return $.execute({kind:"local",req:J},Q.name,V,G)}})}function O8($){if($==="auto")return;let Q=/^(\d+)x(\d+)$/.exec($);if(!Q)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify($)}.`);let Z=Number(Q[1]),V=Number(Q[2]);if(Z%16!==0||V%16!==0)throw Error(`Image size ${$} is not supported: width and height must both be divisible by 16.`);if(Math.max(Z/V,V/Z)>3)throw Error(`Image size ${$} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function _Z($,Q){if($.size!==void 0)try{O8($.size)}catch(Z){throw Error(`${Q}: ${Z.message}`)}if($.background==="transparent"&&$.format==="jpeg")throw Error(`${Q}: a transparent background needs "png"; JPEG has no alpha channel.`);if($.compression!==void 0){let Z=$.compression;if(!Number.isInteger(Z)||Z<0||Z>100)throw Error(`${Q}: compression is an integer from 0 to 100; got ${Z}.`)}}function qZ($,Q){if($ instanceof File)return $;let Z=$.type||"image/png",V=Z==="image/jpeg"?"jpg":Z.split("/")[1]??"png";return new File([$],`${Q}.${V}`,{type:Z})}class f${name;provider;settings;constructor($){let{name:Q,provider:Z,...V}=$;_Z(V,`ImageModel "${Q}"`),this.name=Q,this.provider=Z,this.settings=V}static create($){return new f$($)}async generate($){let Q=this.merge($);return MZ(await this.provider.generate({prompt:$.prompt,...Q,signal:$.signal}))}async edit($){let Q=this.merge($);return MZ(await this.provider.edit({prompt:$.prompt,...Q,images:$.images.map((Z,V)=>qZ(Z,`image-${V}`)),...$.mask?{mask:qZ($.mask,"mask")}:{},signal:$.signal}))}merge($){let Q={...this.settings,...$.size!==void 0?{size:$.size}:{},...$.quality!==void 0?{quality:$.quality}:{},...$.background!==void 0?{background:$.background}:{},...$.format!==void 0?{format:$.format}:{},...$.compression!==void 0?{compression:$.compression}:{}};return _Z(Q,`ImageModel "${this.name}"`),Q}}function MZ($){return{image:new Blob([$.bytes],{type:$.mimeType}),mimeType:$.mimeType,size:$.size,usage:$.usage}}function n($){return typeof process>"u"?void 0:process.env?.[$]}var _8="preview";function RZ($){let Q=$.trim().replace(/\/+$/,"");if(!Q)return"";return`${Q.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function q8($){return/^\d{4}-\d{2}-\d{2}/.test($)?"":"/v1"}function i9($,Q={}){return{base:($.baseURL??n("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let V=$.apiKey??n("OPENAI_API_KEY");return{...V?{authorization:`Bearer ${V}`}:{},...$.headers}},timeoutMs:$.timeoutMs??Q.timeoutMs??120000,maxRetries:$.maxRetries??2}}function M8($){let Q=$.baseURL??$.endpoint??n("AZURE_OPENAI_ENDPOINT");if(Q)return RZ(Q);let Z=$.resourceName??n("AZURE_OPENAI_RESOURCE_NAME")??n("AZURE_RESOURCE_NAME");return Z?RZ(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function n9($,Q={}){let Z=$.apiVersion??n("AZURE_OPENAI_API_VERSION")??_8;return{base:`${M8($)}${q8(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if($.getToken)return{authorization:`Bearer ${await $.getToken()}`,...$.headers};let V=$.apiKey??n("AZURE_OPENAI_API_KEY");return{...V?{"api-key":V}:{},...$.headers}},timeoutMs:$.timeoutMs??Q.timeoutMs??120000,maxRetries:$.maxRetries??2}}var R8=500,jZ=20000;function S8($,Q){if(!$)return;let Z=$.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let V=Date.parse(Z);if(Number.isNaN(V))return;return Math.max(0,V-Q)}function SZ($,Q){let Z=Math.min(jZ,R8*2**$);return Math.round(Z*(0.5+Q()*0.5))}function j8($){return $===429||$===408||$===409||$>=500}function A8($,Q){return j8($)&&I(Q).retryable}function AZ($){return $.reason??new DOMException("The operation was aborted.","AbortError")}function T8($,Q){return new Promise((Z,V)=>{let G=setTimeout(Z,$);Q?.addEventListener("abort",()=>{clearTimeout(G),V(AZ(Q))},{once:!0})})}async function O9($,Q,Z){let V=Z.fetchImpl??((H,B)=>fetch(H,B)),G=Z.sleep??T8,J=Z.random??Math.random,W=Z.now??Date.now,X=Math.max(0,Z.maxRetries),K=async(H)=>{let B=Z.signal;if(!B)return await G(H);B.throwIfAborted();let z;try{await Promise.race([G(H,B),new Promise((D,L)=>{z=()=>L(AZ(B)),B.addEventListener("abort",z,{once:!0})})])}finally{if(z)B.removeEventListener("abort",z)}},Y;for(let H=0;H<=X;H++){Z.signal?.throwIfAborted();let B=new AbortController,z=()=>B.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",z,{once:!0});let D=!1,L=Z.timeoutMs>0?setTimeout(()=>{D=!0,B.abort()},Z.timeoutMs):void 0,F;try{F=await V($,{...Q,signal:B.signal})}catch(_){if(L!==void 0)clearTimeout(L);if(Z.signal?.removeEventListener("abort",z),Z.signal?.aborted)throw _;if(Y=D?new R9(Z.timeoutMs):_,D&&Z.retryTimeouts===!1)throw Y;if(H===X)throw Y;await K(SZ(H,J));continue}if(L!==void 0)clearTimeout(L);if(F.ok)return F;Z.signal?.removeEventListener("abort",z);let U=await E8(F),P=new h(F.status,U,F.headers.get("x-request-id")??void 0);if(H===X||!A8(F.status,P))throw P;let q=S8(F.headers.get("retry-after"),W());await K(q===void 0?SZ(H,J):Math.min(q,jZ)),Y=P}throw Y??Error("Provider request failed with no response.")}async function E8($){let Q;try{Q=await $.text()}catch{return null}try{return JSON.parse(Q)}catch{return Q}}var v$=300000;function y$($){return{generationsUrl:`${$.base}/images/generations${$.query}`,editsUrl:`${$.base}/images/edits${$.query}`,headers:$.headers,timeoutMs:$.timeoutMs,maxRetries:$.maxRetries}}class o9 extends Error{code;retryable;constructor($,Q={}){super($.message,Q);this.name="ImageRequestError",this.code=$.code,this.retryable=$.retryable}}var k8={png:"image/png",jpeg:"image/jpeg"};function x8($){let Q=Number($?.input_tokens??0),Z=Number($?.output_tokens??0),V={inputTokens:Q,outputTokens:Z,totalTokens:Number($?.total_tokens??Q+Z)},G=$?.input_tokens_details?.image_tokens;if(typeof G==="number")V.imageInputTokens=G;let J=$?.output_tokens_details?.image_tokens;if(typeof J==="number")V.imageOutputTokens=J;return V}function I8($){let Q=atob($),Z=new Uint8Array(Q.length);for(let V=0;V<Q.length;V++)Z[V]=Q.charCodeAt(V);return Z}function w8($){let Z=$?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new o9({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let V=typeof $.output_format==="string"?$.output_format:"png";return{bytes:I8(Z),mimeType:k8[V]??`image/${V}`,size:typeof $.size==="string"?$.size:"",...typeof $.background==="string"?{background:$.background}:{},usage:x8($.usage)}}async function TZ($,Q,Z,V){let G;try{G=await O9($,Q,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:V.signal,fetchImpl:Z.fetchImpl})}catch(J){if(V.signal?.aborted)throw J;throw new o9(I(J),{cause:J})}return w8(await G.json())}async function EZ($,Q,Z={}){return await TZ($.generationsUrl,{method:"POST",headers:{...await $.headers(),"content-type":"application/json"},body:JSON.stringify(Q)},$,Z)}async function kZ($,Q,Z={}){return await TZ($.editsUrl,{method:"POST",headers:await $.headers(),body:Q},$,Z)}class s9{static models(){return[]}modelName(){return this.model}async generate($){return await EZ(this.endpoint(),this.body($),{signal:$.signal})}async edit($){let Q=new FormData;for(let[Z,V]of Object.entries(this.body($)))if(V!==void 0)Q.set(Z,String(V));for(let Z of $.images)Q.append("image[]",Z,Z.name);if($.mask)Q.set("mask",$.mask,$.mask.name);return await kZ(this.endpoint(),Q,{signal:$.signal})}body($){return{model:this.modelName(),prompt:$.prompt,...$.size?{size:$.size}:{},...$.quality?{quality:$.quality}:{},...$.background?{background:$.background}:{},...$.format?{output_format:$.format}:{},...$.compression!==void 0?{output_compression:$.compression}:{}}}normalizeError($){return I($)}}var xZ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class h$ extends s9{model;config;constructor($,Q={}){super();this.model=$,this.config=Q}static model($,Q){return new h$($,Q)}static models(){return xZ}endpoint(){return y$(i9(this.config,{timeoutMs:v$}))}}class g$ extends s9{model;config;constructor($,Q={}){super();this.model=$,this.config=Q}static model($,Q){return new g$($,Q)}static models(){return xZ}modelName(){return this.config.deployment??this.model}endpoint(){return y$(n9(this.config,{timeoutMs:v$}))}}var bZ=3;function u$($){let Q=new Map;for(let Z of $)for(let V of Z.content??[]){if(V.type!=="file"||!V.fileId||Q.has(V.fileId))continue;Q.set(V.fileId,{name:V.name,mimeType:V.mimeType})}return Q}function fZ($,Q,Z=new Map){if(!(Q instanceof h))return[];if(Q.status!==400&&Q.status!==404)return[];let V=f8(Q.body);if(!V)return[];let G=b8($.input);if(G.length===0)return[];let J=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(V.param??"");if(J){let Y=$.input[Number(J[1])],H=p$(Y)[Number(J[2])],B=H&&typeof H.file_id==="string"?H.file_id:void 0;if(B)return[B]}let W=V.message??"",X=wZ(G.map((Y)=>Y.fileId).filter((Y)=>v8(W,Y)));if(X.length>0)return X;let K=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(W);if(K){let Y=K[1].toLowerCase()==="image type"?"input_image":"input_file",H=K[2].toLowerCase(),B=wZ(G.filter((D)=>D.type===Y).map((D)=>D.fileId)),z=B.filter((D)=>(Z.get(D)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(z.length===1)return z;if(z.length===0&&B.length===1)return B}return[]}function vZ($,Q,Z=new Map){return{...$,input:$.input.map((V)=>{let G=p$(V);if(!G.some((J)=>IZ(J,Q)))return V;return{...V,content:G.map((J)=>IZ(J,Q)?{type:"input_text",text:c$(Z.get(String(J.file_id))?.name)}:J)}})}}function c$($){return`[${$?`attachment ${JSON.stringify($)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function IZ($,Q){return typeof $.file_id==="string"&&Q.has($.file_id)}function p$($){let Q=$?.content;return Array.isArray(Q)?Q:[]}function b8($){let Q=[];for(let Z of $)for(let V of p$(Z))if(typeof V.file_id==="string"&&V.file_id)Q.push({type:String(V.type),fileId:V.file_id});return Q}function f8($){if(!$||typeof $!=="object")return null;let Q=$,Z=Q.error&&typeof Q.error==="object"?Q.error:$;return{message:typeof Z.message==="string"?Z.message:void 0,param:typeof Z.param==="string"?Z.param:void 0}}function v8($,Q){let Z=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Z}($|[^A-Za-z0-9_-])`).test($)}function wZ($){return[...new Set($)]}async function*y8($){let Q="",Z="",V=[],G,J=()=>{if(V.length===0&&!Z)return null;let K={event:Z,data:V.join(`
93
- `),id:G};return Z="",V=[],G=void 0,K.data?K:null},W=(K)=>{let Y=K.endsWith("\r")?K.slice(0,-1):K;if(Y==="")return J();if(Y.startsWith(":"))return null;let H=Y.indexOf(":"),B=H===-1?Y:Y.slice(0,H),z=H===-1?"":Y.slice(H+1);if(z.startsWith(" "))z=z.slice(1);if(B==="event")Z=z;else if(B==="data")V.push(z);else if(B==="id")G=z;return null};for await(let K of $){Q+=K;let Y=Q.indexOf(`
94
- `);while(Y!==-1){let H=Q.slice(0,Y);Q=Q.slice(Y+1);let B=W(H);if(B)yield B;Y=Q.indexOf(`
95
- `)}}if(Q.length>0){let K=W(Q);if(K)yield K}let X=J();if(X)yield X}async function*yZ($,Q={}){let Z=new Map,V=new Set,G,J=!1,W,X=(K,Y)=>({type:"finish",reason:K,usage:Y,...W?{model:W}:{}});for await(let K of y8($)){if(K.data==="[DONE]")break;let Y;try{Y=JSON.parse(K.data)}catch{continue}let H=typeof Y.type==="string"?Y.type:K.event,B=Y.response?.model;if(typeof B==="string"&&B)W=B;switch(H){case"response.output_text.delta":{let z=String(Y.delta??"");if(!z)break;yield Q.structuredOutput?{type:"output-delta",delta:z}:{type:"text-delta",delta:z};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let z=String(Y.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:Y.item_id};break}case"response.output_item.added":{let z=Y.item;if(!z)break;if(z.type==="function_call"){let D=String(z.id??Y.item_id??z.call_id??"");Z.set(D,{callId:String(z.call_id??D),name:String(z.name??""),namespace:typeof z.namespace==="string"&&z.namespace?z.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let z=Z.get(String(Y.item_id??""));if(!z)break;let D=String(Y.delta??"");if(!D)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:D,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(Y.item_id??""),D=Z.get(z);if(!D)break;D.done=!0,yield{type:"tool-call",toolCallId:D.callId,name:D.name,args:String(Y.arguments??""),...D.namespace?{namespace:D.namespace}:{}};break}case"response.output_item.done":{let z=Y.item;if(!z)break;if(z.type==="function_call"){let D=String(z.id??Y.item_id??z.call_id??""),L=Z.get(D);if(L?.done)break;let F=(typeof z.namespace==="string"?z.namespace:"")||L?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??D),name:String(z.name??L?.name??""),args:String(z.arguments??""),...F?{namespace:F}:{}},L)L.done=!0;break}if(z.type==="tool_search_call"||z.type==="tool_search_output"){if(z.type==="tool_search_call"&&z.arguments!==void 0)G=z.arguments;let D=h8(z);if(D.loaded.length===0&&D.namespaces.length===0)break;let L=String(z.tool_search_call_id??z.id??"");if(V.has(L))break;V.add(L);let F=G;G=void 0,yield{type:"tool-search",...D,...F!==void 0&&F!==null?{arguments:F}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(Y.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{J=!0,yield X("stop",m$(Y.response?.usage));break}case"response.incomplete":{J=!0;let z=m$(Y.response?.usage),D=Y.response?.incomplete_details?.reason;if(D==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:g8(Y.response?.content_filters),retryable:!1}},yield X("error",z);break}yield X(D==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{J=!0;let z=Y.response?.error??Y.error??Y;yield{type:"error",error:u8(z)},yield X("error",m$(Y.response?.usage));break}}if(J)return}if(!J)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield X("error",$9())}function h8($){let Q=[],Z=[];return hZ($.results??$.tools??$.loaded??$.output,Q,Z,0),{loaded:l$(Q),namespaces:l$(Z)}}function hZ($,Q,Z,V){if(!Array.isArray($)||V>4)return;for(let G of $){if(typeof G==="string"){Q.push(G);continue}if(!G||typeof G!=="object")continue;let J=G,W=typeof J.name==="string"?J.name:typeof J.tool_name==="string"?J.tool_name:"",X=J.tools??J.functions;if(Array.isArray(X)){if(W)Z.push(W);hZ(X,Q,Z,V+1);continue}if(W)Q.push(W)}}function l$($){return $.filter((Q,Z)=>$.indexOf(Q)===Z)}function g8($){if(!Array.isArray($))return"The provider's content filter blocked this request.";let Z=[];for(let V of $){if(!V||typeof V!=="object")continue;let G=V,J=G.content_filter_results;if(!J||typeof J!=="object")continue;for(let[W,X]of Object.entries(J))if(X&&typeof X==="object"&&X.filtered===!0)Z.push(`${W} (${String(G.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${l$(Z).join(", ")}.`}function u8($){let Q=typeof $?.message==="string"?$.message:"The provider stream failed.",Z=String($?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:Q,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:Q,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:Q,retryable:!1};return{code:"provider_error",message:Q,retryable:!0}}function $9(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function m$($){if(!$)return $9();let Q=Number($.input_tokens??0),Z=Number($.output_tokens??0),V={inputTokens:Q,outputTokens:Z,totalTokens:Number($.total_tokens??Q+Z)},G=$.output_tokens_details?.reasoning_tokens;if(typeof G==="number")V.reasoningTokens=G;let J=$.input_tokens_details?.cached_tokens;if(typeof J==="number")V.cachedInputTokens=J;return V}async function*gZ($){if(!$)return;let Q=$.getReader(),Z=new TextDecoder;try{while(!0){let{done:G,value:J}=await Q.read();if(G)break;if(J)yield Z.decode(J,{stream:!0})}let V=Z.decode();if(V)yield V}finally{Q.releaseLock()}}function d$($){return{responsesUrl:`${$.base}/responses${$.query}`,filesUrl:`${$.base}/files${$.query}`,headers:$.headers,timeoutMs:$.timeoutMs,maxRetries:$.maxRetries}}async function*i$($,Q,Z){let V,G=Q,J=new Set;for(let W=0;V===void 0;W++)try{V=await O9($.responsesUrl,{method:"POST",headers:{...await $.headers(),"content-type":"application/json"},body:JSON.stringify(G)},{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(X){let K=W<bZ?fZ(G,X,Z.files).filter((H)=>!J.has(H)):[];if(K.length>0){let H=I(X).message;for(let B of K)J.add(B),yield{type:"file-rejected",fileId:B,message:H,...b(X)};G=vZ(G,new Set(K),Z.files);continue}let Y=I(X);if(Y.code!=="aborted")yield{type:"error",error:Y,...b(X)};yield{type:"finish",reason:Y.code==="aborted"?"aborted":"error",usage:$9()};return}try{yield*yZ(gZ(V.body),{structuredOutput:Z.structuredOutput})}catch(W){let X=I(W);if(X.code==="aborted"){yield{type:"finish",reason:"aborted",usage:$9()};return}yield{type:"error",error:X},yield{type:"finish",reason:"error",usage:$9()}}}async function n$($,Q,Z="user_data"){let V=new FormData;V.set("purpose",Z),V.set("file",Q);let J=await(await O9($.filesUrl,{method:"POST",headers:await $.headers(),body:V},{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,fetchImpl:$.fetchImpl})).json();if(!J?.id)throw Error("The provider accepted the upload but returned no file id.");return J.id}function o$($){let Q=c8($);if(Q.startsWith("gpt-3.5")||Q.startsWith("text-")||Q.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=p8(Q);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:uZ(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),fileInput:Z.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:uZ(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function uZ($){if($.kind==="o")return $.major>=5;return $.major>5||$.major===5&&$.minor>=2}function c8($){return $.trim().toLowerCase()}function p8($){let Q=/^gpt-(\d+)(?:\.(\d+))?/.exec($);if(Q?.[1])return{kind:"gpt",major:Number(Q[1]),minor:Number(Q[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec($);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function t$($,Q){let{capabilities:Z}=Q,V={model:Q.model,input:m8($.messages,Z,$.tools),stream:!0};if($.systemPrompt)V.instructions=$.systemPrompt;let G=e8($.tools,Z);if(G.length>0){if(V.tools=G,!Z.parallelToolCalls)V.parallel_tool_calls=!1}if($.output)V.text={format:{type:"json_schema",name:$.output.name,schema:$.output.schema,strict:$.output.strict}};if($.reasoning&&Z.reasoning)V.reasoning=$.reasoning==="none"?{effort:"none"}:{effort:$.reasoning,summary:"auto"};if(typeof $.temperature==="number")V.temperature=$.temperature;if(typeof $.maxOutputTokens==="number")V.max_output_tokens=$.maxOutputTokens;return V}function m8($,Q,Z){let V=[],G=new Map;if(Q.toolSearch){for(let J of Z??[])if(t9(J))G.set(J.name,J)}for(let J of $){let W=J.role,X=[],K=()=>{if(X.length===0)return;V.push({type:"message",role:W,content:X}),X=[]};for(let Y of J.content??[])switch(Y.type){case"text":{if(!Y.text)break;X.push(Q9(W,Y.text));break}case"output":{if(Y.partial)break;X.push(Q9(W,JSON.stringify(Y.value)));break}case"file":{if(W==="assistant")break;let H=i8(Y);if(!Q.fileInput){if(H)X.push(Q9(W,s$(Y,!1)));break}if(Y.fileId?.startsWith(v))throw Error(`FilePart.fileId holds a gemi attachment id (${Y.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!Y.fileId&&!H)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(Y.providerRejected){if(H)X.push(Q9(W,s$(Y,!1)));X.push(Q9(W,c$(Y.name)));break}if(H)X.push(Q9(W,s$(Y,!!Y.fileId)));if(Y.fileId)X.push(n8(Y));break}case"reasoning":{K();let H=t8(Y);if(H)V.push(H);break}case"tool-call":{if(Y.partial)break;if(K(),Q.toolSearch&&Array.isArray(Y.toolSearches))for(let B of Y.toolSearches)V.push(...r8(B,Z??[]));let H={type:"function_call",call_id:Y.toolCallId,name:String(Y.name),arguments:JSON.stringify(Y.input??{})};if(Y.namespace&&G.has(Y.namespace))H.namespace=Y.namespace;V.push(H);break}case"tool-result":{K(),V.push({type:"function_call_output",call_id:Y.toolCallId,output:a8(Y)});break}}K()}return d8(V)}var l8="No result was recorded for this tool call. Assume it did not complete.";function d8($){let Q=new Set,Z=new Set,V=[];for(let J of $){if(J.type==="function_call"){let W=String(J.call_id);if(Q.has(W))continue;Q.add(W)}else if(J.type==="function_call_output"){let W=String(J.call_id);if(!Q.has(W)||Z.has(W))continue;Z.add(W)}V.push(J)}if(Z.size===Q.size)return V;let G=[];for(let J of V){if(G.push(J),J.type!=="function_call")continue;let W=String(J.call_id);if(Z.has(W))continue;Z.add(W),G.push({type:"function_call_output",call_id:W,output:l8})}return G}function Q9($,Q){return{type:$==="assistant"?"output_text":"input_text",text:Q}}function i8($){let Q=$.attachmentId;return typeof Q==="string"&&Q.startsWith(v)?Q:void 0}function s$($,Q){let Z=[`id=${JSON.stringify($.attachmentId)}`];if($.name)Z.push(`name=${JSON.stringify($.name)}`);if($.mimeType)Z.push(`mimeType=${JSON.stringify($.mimeType)}`);let V=`attachment ${Z.join(" ")}`;return Q?`[${V}]`:`[${V} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function n8($){let Q=$.mimeType?.trim().toLowerCase()??"";return{type:(Q?Q.startsWith("image/")&&Q!=="image/svg+xml":o8($.name))?"input_image":"input_file",file_id:$.fileId}}function o8($){let Q=/\.([a-z0-9]+)$/.exec($?.trim().toLowerCase()??"");return Q?.[1]!==void 0&&s8.has(Q[1])}var s8=new Set(["jpeg","jpg","png","gif","webp"]);function t8($){if(!$.id)return null;let Q={type:"reasoning",id:$.id};return Q.summary=$.text?[{type:"summary_text",text:$.text}]:[],Q}function a8($){if($.status==="ok")return typeof $.output==="string"?$.output:JSON.stringify($.output??null);if($.status==="running"){let Q=$.job?.summary===void 0?"":` Started with: ${JSON.stringify($.job.summary)}.`;return`Started background job ${$.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${Q}`}if($.status==="denied"){let Q=$.reason?` Reason given: ${$.reason}`:"";if($.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${Q}`;if($.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${Q}`;return`The user declined this tool call, so it did not run.${Q}`}return`The tool call failed and produced no result. Error (${$.error?.code??"unknown"}): ${$.error?.message??"no message"}`}function r8($,Q){let Z=new Set(cZ($?.loaded)),V=cZ($?.namespaces),G=new Set(V),J=[];for(let X of Q)if(t9(X)){if(!G.has(X.name))continue;let K=X.tools.filter((Y)=>Z.size===0||Z.has(Y.name));if(K.length===0)continue;J.push({type:"namespace",name:X.name,description:X.description,tools:K.map((Y)=>Z9(Y,!0))})}else if(X.deferred&&Z.has(X.name))J.push(Z9(X,!0));if(J.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:$.arguments&&typeof $.arguments==="object"?$.arguments:{paths:V.length>0?V:[...Z]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:J}]}function cZ($){return Array.isArray($)?$.filter((Q)=>typeof Q==="string"):[]}function t9($){return Array.isArray($.tools)}function e8($,Q){if(!$||$.length===0)return[];if(!Q.toolSearch){let G=[];for(let J of $)if(t9(J))for(let W of J.tools)G.push(Z9(W,!1));else G.push(Z9(J,!1));return G}let Z=[],V=!1;for(let G of $)if(t9(G)){let J=G.tools.map((W)=>{if(W.deferred)V=!0;return Z9(W,!0)});Z.push({type:"namespace",name:G.name,description:G.description,tools:J})}else{if(G.deferred)V=!0;Z.push(Z9(G,!0))}if(V)Z.push({type:"tool_search"});return Z}function Z9($,Q){let Z={type:"function",name:$.name,description:$.description,parameters:$.parameters,strict:$.strict};if(Q&&$.deferred)Z.defer_loading=!0;return Z}class V9{static models(){return[]}normalizeError($){return I($)}}var pZ=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class a$ extends V9{model;capabilities;config;constructor($,Q={}){super();this.model=$,this.capabilities=o$($),this.config=Q}static model($,Q){return new a$($,Q)}static models(){return pZ}stream($){let Q=t$($,{model:this.model,capabilities:this.capabilities});return i$(this.endpoint(),Q,{signal:$.signal,structuredOutput:Boolean($.output),files:u$($.messages)})}upload($){return n$(this.endpoint(),$)}endpoint(){return d$(i9(this.config))}}class r$ extends V9{model;capabilities;config;constructor($,Q={}){super();this.model=$,this.capabilities=o$($),this.config=Q}static model($,Q){return new r$($,Q)}static models(){return pZ}stream($){let Q=t$($,{model:this.deployment(),capabilities:this.capabilities});return i$(this.endpoint(),Q,{signal:$.signal,structuredOutput:Boolean($.output),files:u$($.messages)})}upload($){return n$(this.endpoint(),$,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return d$(n9(this.config))}}class a9{now;entries=new Map;constructor($=Date.now){this.now=$}allow($,Q){let Z=this.entries.get($);if(Z?.openUntil===void 0)return!0;let V=this.now();if(V<Z.openUntil)return!1;if(Z.probeUntil!==void 0&&V<Z.probeUntil)return!1;return Z.probeUntil=V+Q.cooldownMs,!0}record($,Q,Z){let V=this.entries.get($)??{failures:0},G=V.openUntil!==void 0;if(Q==="success")return this.entries.delete($),G?"closed":void 0;if(Q==="none"){delete V.probeUntil;return}if(V.failures+=1,this.entries.set($,V),G||V.failures>=Z.failures)return V.openUntil=this.now()+Z.cooldownMs,delete V.probeUntil,G?void 0:"open";return}state($){let Q=this.entries.get($);if(Q?.openUntil===void 0)return"closed";return this.now()<Q.openUntil?"open":"half-open"}}function $0($){switch($.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}var mZ=Symbol("timed-out");class _9 extends V9{model;capabilities;entries;options;circuit;constructor($,Q={}){super();if($.length===0)throw Error("FallbackProvider needs at least one provider.");for(let V of $)if(V.timeoutMs!==void 0&&!(V.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${V.provider.model} must be a positive number, got ${V.timeoutMs}.`);this.entries=[...$];let Z=Q.circuit;if(Z){let V=Z.failures??3,G=Z.cooldownMs??30000;if(!Number.isInteger(V)||V<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${V}.`);if(!(G>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${G}.`);let J=new Set;for(let X of $){let K=e$(X);if(J.has(K))throw Error(`FallbackProvider: two legs share the circuit key "${K}". Give one of them a \`circuitKey\`.`);J.add(K)}let W=Z.store??new a9;this.options={...Q,circuit:{...Z,store:W}},this.circuit={policy:{failures:V,cooldownMs:G},store:W,...Z.onStateChange?{onStateChange:Z.onStateChange}:{}}}else this.options=Q,this.circuit=void 0;this.model=$[0].provider.model,this.capabilities=Q0($.map((V)=>V.provider.capabilities))}static chain($,Q){return new _9($,Q)}from($){if(!Number.isInteger($)||$<0||$>=this.entries.length)throw RangeError(`FallbackProvider.from(${$}): the chain has ${this.entries.length} entries.`);return new _9(this.entries.slice($),this.options)}leg($){let Q=this.from($).entries[0];return new _9([Q],this.options)}upload($){return this.entries[0].provider.upload($)}normalizeError($){return this.entries[0].provider.normalizeError($)}stream($){return this.run($)}async*run($){let Q,Z=$.signal,V=0;for(let G=0;G<this.entries.length;G++){let J=this.entries[G],W=G===this.entries.length-1,X=J.provider.model;if(this.circuit&&!W&&!await this.allow(J))continue;V+=1;let K=!1,Y=async(N)=>{if(K)return;K=!0,await this.record(G,J,N)},H=new AbortController,B=()=>H.abort(Z?.reason);if(Z?.aborted)H.abort(Z.reason);else Z?.addEventListener("abort",B,{once:!0});let z=[],D=!1,L=!1,F,U,P,q=!1,_,O=!1,A=(N)=>{let T=Q?M(M(R(),Q),N.usage):N.usage;return Q=void 0,{...N,usage:T}};try{_=J.provider.stream({...$,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let N=!0;for(;;){let T=N&&J.timeoutMs!==void 0?await Z0(_.next(),J.timeoutMs):await _.next();if(T===mZ){q=!0,P={error:{code:"provider_error",message:`${X} sent nothing within ${J.timeoutMs}ms.`,retryable:!0}};break}if(N=!1,T.done){O=!0;break}let S=T.value;if(S.type==="finish"&&S.model)U=S.model;if(D){if(S.type==="finish")F=M(F??R(),S.usage),L=!0,yield A(S);else{if(S.type==="error")P={error:S.error};yield S}continue}if($0(S)){D=!0,await Y("success"),yield*z.splice(0),yield S;continue}if(S.type==="error")P={error:S.error,...S.status!==void 0?{status:S.status}:{},...S.requestId!==void 0?{requestId:S.requestId}:{}};else if(S.type==="finish"){if(F=M(F??R(),S.usage),S.reason==="error"&&!P)P={error:{code:"provider_error",message:`${X} ended the call with an error and did not say which.`,retryable:!1}}}z.push(S)}}catch(N){let T=J.provider.normalizeError(N);if(D){if(T.code!=="aborted")yield{type:"error",error:T,...b(N)};this.report({index:G,model:X,responseModel:U,attempt:V,usage:F,outcome:$Q(T),error:T}),yield A({type:"finish",reason:T.code==="aborted"?"aborted":"error",usage:R(),...U?{model:U}:{}});return}P={error:T,...b(N)}}finally{if(Z?.removeEventListener("abort",B),!O)H.abort(),_?.return?.()?.catch(()=>{})}if(D){if(!L&&Q)yield{type:"finish",reason:P?"error":"stop",usage:Q},Q=void 0;this.report({index:G,model:X,responseModel:U,attempt:V,usage:F,outcome:P?$Q(P.error):"ok",...P?{error:P.error}:{}});return}if(Z?.aborted){await Y("none"),this.report({index:G,model:X,responseModel:U,attempt:V,usage:F,outcome:"aborted"}),yield A({type:"finish",reason:"aborted",usage:F??R(),...U?{model:U}:{}});return}if(!P){await Y("success"),this.report({index:G,model:X,responseModel:U,attempt:V,usage:F,outcome:"ok"});for(let N of z)yield N.type==="finish"?A(N):N;return}let k=!W&&P.error.code!=="aborted"&&this.shouldFallBack(P.error,{index:G,model:X,timedOut:q,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}});if(await Y(k?"failure":"none"),this.report({index:G,model:X,responseModel:U,attempt:V,usage:F,outcome:k?"fallback":$Q(P.error),error:P.error}),k){if(F)Q=M(Q??R(),F);continue}let x=!1,C;for(let N of z){if(N.type==="finish"){C=N;continue}if(N.type==="error")x=!0;yield N}if(!x&&P.error.code!=="aborted")yield{type:"error",error:P.error,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}};yield A({type:"finish",reason:P.error.code==="aborted"?"aborted":C?.reason??"error",usage:F??R(),...U?{model:U}:{}});return}}async allow($){if(!this.circuit)return!0;try{return await this.circuit.store.allow(e$($),this.circuit.policy)}catch{return!0}}async record($,Q,Z){if(!this.circuit)return;let V=e$(Q),G;try{G=await this.circuit.store.record(V,Z,this.circuit.policy)}catch{return}if(!G)return;try{this.circuit.onStateChange?.({index:$,model:Q.provider.model,key:V,state:G})}catch{}}shouldFallBack($,Q){let Z=this.options.fallbackOn??((V)=>V.retryable);try{return Z($,Q)}catch{return!1}}report($){if($.usage===void 0)delete $.usage;if($.responseModel===void 0)delete $.responseModel;try{this.options.onUsage?.($)}catch{}}}function e$($){return $.circuitKey??$.provider.model}function $Q($){return $.code==="aborted"?"aborted":"failed"}function Q0($){return{reasoning:$.every((Q)=>Q.reasoning),structuredOutput:$.every((Q)=>Q.structuredOutput),fileInput:$.every((Q)=>Q.fileInput),parallelToolCalls:$.every((Q)=>Q.parallelToolCalls),toolSearch:$.every((Q)=>Q.toolSearch)}}function Z0($,Q){let Z,V=new Promise((G)=>{Z=setTimeout(()=>G(mZ),Q)});return Promise.race([$,V]).finally(()=>clearTimeout(Z))}async function V0($,Q,Z={}){let V=Z.samples??1;if(!Number.isInteger(V)||V<1)throw RangeError(`evalChain: samples must be a positive integer, got ${V}.`);let G=[];for(let J=0;J<$.entries.length;J++){let W=$.leg(J),X={index:J,model:W.model,results:[],errors:[]};for(let K=0;K<V;K++)try{X.results.push(await Q(W,{index:J,sample:K}))}catch(Y){X.errors.push({sample:K,error:Y})}G.push(X)}return G}class G9 extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor($,Q,Z){super(`Frame ${Q} of run ${$} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=$;this.requested=Q;this.oldest=Z}}class q9 extends Error{runId;code="live_run_not_found";constructor($){super(`No live run ${$} in this process.`);this.runId=$}}class r9{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor($={}){this.ttlMs=$.ttlMs??60000,this.maxFrames=$.maxFrames??4096,this.maxAgeMs=$.maxAgeMs===void 0?3600000:$.maxAgeMs}register($,Q={}){let Z={run:$,threadId:Q.threadId,owner:Q.owner??null,clientRunId:Q.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set($.runId,Z),Q.threadId)this.byThread.set(Q.threadId,$.runId);if(Q.clientRunId)this.byClientRun.set(Q.clientRunId,$.runId);return this.scheduleExpiry(Z,Q.maxRunDurationMs),this.pump(Z,Q)}findByClientRunId($){let Q=this.byClientRun.get($);return Q&&this.runs.has(Q)?Q:null}async find($){let Q=this.byThread.get($.threadId);if(!Q)return null;let Z=this.runs.get(Q);if(!Z)return null;return{runId:Q,seq:Z.lastSeq}}get($){return this.runs.get($)?.run??null}ownerOf($){return this.runs.get($)?.owner??null}mayAccess($,Q){let Z=this.ownerOf($);return Z===null||Z===Q}isRunning($){let Q=this.runs.get($);return!!Q&&!Q.ended&&!Q.evicted}replay($,Q){let Z=this.runs.get($);if(!Z)throw new q9($);if(Q!==void 0&&Q<Z.lostBefore)throw new G9($,Q,Z.lostBefore);let V=Z.frames[0]?.seq;return this.drain(Z,$,Q??V??Z.lastSeq+1)}clear(){for(let $ of this.runs.values()){if($.evictAt)clearTimeout($.evictAt);if($.expireAt)clearTimeout($.expireAt);$.ended=!0,this.notify($)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump($,Q){let Z=Promise.resolve();try{for await(let V of $.run.frames()){if($.evicted){let J=Q.onEvent;if(J)Z=Z.then(()=>J(V.event)).catch((W)=>QQ(Q,W));continue}if($.frames.push(V),$.lastSeq=V.seq,$.frames.length>this.maxFrames){let J=$.frames.shift();if(J)$.lostBefore=J.seq+1}this.notify($);let G=Q.onEvent;if(G)Z=Z.then(()=>G(V.event)).catch((J)=>QQ(Q,J))}}catch(V){QQ(Q,V)}finally{if($.ended=!0,$.expireAt)clearTimeout($.expireAt),$.expireAt=null;this.notify($),this.scheduleEviction($),await Z}}async*drain($,Q,Z){let V=Z;while(!0){let G=$.version;for(;;){if(V<$.lostBefore)throw new G9(Q,V,$.lostBefore);let J=$.frames,W=J[0]?.seq;if(W===void 0)break;let X=Math.max(0,V-W);if(X>=J.length)break;let K=J[X];yield K,V=K.seq+1}if($.ended&&V>$.lastSeq||$.evicted)return;await this.wait($,G)}}wait($,Q){if($.version!==Q)return Promise.resolve();return new Promise((Z)=>$.wake.add(Z))}notify($){$.version++;let Q=Array.from($.wake);$.wake.clear();for(let Z of Q)Z()}scheduleEviction($){if($.evictAt)return;let Q=setTimeout(()=>{let Z=$.run.runId;if(!$.ended)$.evicted=!0,$.frames=[];if(this.runs.get(Z)===$)this.runs.delete(Z);if($.threadId&&this.byThread.get($.threadId)===Z)this.byThread.delete($.threadId);if($.clientRunId&&this.byClientRun.get($.clientRunId)===Z)this.byClientRun.delete($.clientRunId);this.notify($)},this.ttlMs);Q.unref?.(),$.evictAt=Q}scheduleExpiry($,Q){if(this.maxAgeMs===null||Q===null)return;let Z=Q===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,Q+this.ttlMs);if(!Number.isFinite(Z)||Z>2147483647)return;let V=setTimeout(()=>{if($.expireAt=null,$.ended)return;try{$.run.stop({reason:`The run was still going ${Math.round(Z/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction($)},Z);V.unref?.(),$.expireAt=V}}var ZQ=new r9;function QQ($,Q){try{$.onInternalError?.(Q)}catch{}}class e9{maxEntries;records=new Map;constructor($=1e5){this.maxEntries=$}async record($,Q){if(this.records.has($))return;this.records.set($,{...Q});while(this.records.size>this.maxEntries){let Z=this.records.keys().next().value;if(Z===void 0)break;this.records.delete(Z)}}async get($){let Q=this.records.get($);return Q?{...Q}:null}}var VQ=new e9;class WQ{now;receipts=new Map;sweepAt=1024;constructor($=Date.now){this.now=$}async claim($,Q){let Z=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Z);let V=this.receipts.get($);if(V&&V.expiresAt>Z)return V.result?{status:"replay",result:structuredClone(V.result)}:{status:"blocked"};return this.receipts.set($,{expiresAt:Q}),{status:"claimed"}}async complete($,Q,Z){this.receipts.set($,{result:structuredClone(Q),expiresAt:Z})}async release($){let Q=this.receipts.get($);if(Q&&!Q.result)this.receipts.delete($)}get size(){return this.receipts.size}sweep($){for(let[Q,Z]of this.receipts)if(Z.expiresAt<=$)this.receipts.delete(Q);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var lZ="pending",GQ="done:",G0=`
74
+ "settled_at" BIGINT${Z}
75
+ )`,`CREATE INDEX IF NOT EXISTS "${Q}_thread_id_created_at_idx" ON "${Q}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Q}_state_deadline_at_idx" ON "${Q}"("state", "deadline_at")`]}var l$=/^[A-Za-z0-9_-]{1,64}$/;function d$(J,Q){let $=i$(Q)?Q:{filter:Q},Z=$.deferred===!0,W=J.descriptors($.filter);if(!$.namespaces)return W.map((H)=>RJ(J,H,Z));let G=Object.entries($.namespaces),V=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,B]of G){if(!l$.test(H))throw Error(`toAgentTools: "${H}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof B?.description!=="string"||B.description.trim()==="")throw Error(`toAgentTools: the namespace "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!V.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let K=new Map(G.map(([H])=>[H,[]])),Y=[];for(let H of W){let B=G.find(([D])=>H.tags.includes(D))?.[0];if(B===void 0)Y.push(RJ(J,H,Z));else K.get(B).push(RJ(J,H,!1))}let X=[];for(let[H,B]of G){let D=K.get(H);if(D.length===0)continue;X.push(jJ.create({name:H,description:B.description,tools:D,deferred:B.deferred??Z}))}return[...X,...Y]}function i$(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function RJ(J,Q,$){if(Q.kind==="tool")return n$(J,Q,$);return QJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,execute:(Z,W)=>{let G=n.getStore()?.req;if(!G)throw new TJ(`"${Q.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return J.execute({kind:"local",req:G},Q.name,Z,W)}})}function n$(J,Q,$){let Z=J.nativeTool(Q.name);return QJ.create({name:Q.name,description:Q.description,inputSchema:Q.inputSchema,...Q.outputSchema?{outputSchema:Q.outputSchema}:{},requiresApproval:Q.requiresApproval,deferred:$,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,G)=>{let V=n.getStore()?.req;return J.startNative(V?{kind:"local",req:V}:void 0,Q.name,W,G)}})}function o$(J){if(J==="auto")return;let Q=/^(\d+)x(\d+)$/.exec(J);if(!Q)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let $=Number(Q[1]),Z=Number(Q[2]);if($%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max($/Z,Z/$)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function kQ(J,Q){if(J.size!==void 0)try{o$(J.size)}catch($){throw Error(`${Q}: ${$.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${Q}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let $=J.compression;if(!Number.isInteger($)||$<0||$>100)throw Error(`${Q}: compression is an integer from 0 to 100; got ${$}.`)}}function EQ(J,Q){if(J instanceof File)return J;let $=J.type||"image/png",Z=$==="image/jpeg"?"jpg":$.split("/")[1]??"png";return new File([J],`${Q}.${Z}`,{type:$})}class kJ{name;provider;settings;constructor(J){let{name:Q,provider:$,...Z}=J;kQ(Z,`ImageModel "${Q}"`),this.name=Q,this.provider=$,this.settings=Z}static create(J){return new kJ(J)}async generate(J){let Q=this.merge(J);return qQ(await this.provider.generate({prompt:J.prompt,...Q,signal:J.signal}))}async edit(J){let Q=this.merge(J);return qQ(await this.provider.edit({prompt:J.prompt,...Q,images:J.images.map(($,Z)=>EQ($,`image-${Z}`)),...J.mask?{mask:EQ(J.mask,"mask")}:{},signal:J.signal}))}merge(J){let Q={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return kQ(Q,`ImageModel "${this.name}"`),Q}}function qQ(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function I(J){return typeof process>"u"?void 0:process.env?.[J]}var s$="preview";function xQ(J){let Q=J.trim().replace(/\/+$/,"");if(!Q)return"";return`${Q.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function a$(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function $J(J,Q={}){return{base:(J.baseURL??I("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??I("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}function t$(J){let Q=J.baseURL??J.endpoint??I("AZURE_OPENAI_ENDPOINT");if(Q)return xQ(Q);let $=J.resourceName??I("AZURE_OPENAI_RESOURCE_NAME")??I("AZURE_RESOURCE_NAME");return $?xQ(`https://${$.trim()}.cognitiveservices.azure.com`):""}function ZJ(J,Q={}){let $=J.apiVersion??I("AZURE_OPENAI_API_VERSION")??s$;return{base:`${t$(J)}${a$($)}`,query:`?api-version=${encodeURIComponent($)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??I("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??Q.timeoutMs??120000,maxRetries:J.maxRetries??2}}var r$=500,bQ=20000;function e$(J,Q){if(!J)return;let $=J.trim();if(/^\d+(\.\d+)?$/.test($))return Math.max(0,Number($)*1000);let Z=Date.parse($);if(Number.isNaN(Z))return;return Math.max(0,Z-Q)}function wQ(J,Q){let $=Math.min(bQ,r$*2**J);return Math.round($*(0.5+Q()*0.5))}function J3(J){return J===429||J===408||J===409||J>=500}function Q3(J,Q){return J3(J)&&R(Q).retryable}function vQ(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function $3(J,Q){return new Promise(($,Z)=>{let W=setTimeout($,J);Q?.addEventListener("abort",()=>{clearTimeout(W),Z(vQ(Q))},{once:!0})})}async function o(J,Q,$){let Z=$.fetchImpl??((H,B)=>fetch(H,B)),W=$.sleep??$3,G=$.random??Math.random,V=$.now??Date.now,K=Math.max(0,$.maxRetries),Y=async(H)=>{let B=$.signal;if(!B)return await W(H);B.throwIfAborted();let D;try{await Promise.race([W(H,B),new Promise((z,F)=>{D=()=>F(vQ(B)),B.addEventListener("abort",D,{once:!0})})])}finally{if(D)B.removeEventListener("abort",D)}},X;for(let H=0;H<=K;H++){$.signal?.throwIfAborted();let B=new AbortController,D=()=>B.abort($.signal?.reason);$.signal?.addEventListener("abort",D,{once:!0});let z=!1,F=$.timeoutMs>0?setTimeout(()=>{z=!0,B.abort()},$.timeoutMs):void 0,U;try{U=await Z(J,{...Q,signal:B.signal})}catch(O){if(F!==void 0)clearTimeout(F);if($.signal?.removeEventListener("abort",D),$.signal?.aborted)throw O;if(X=z?new IQ($.timeoutMs):O,z&&$.retryTimeouts===!1)throw X;if(H===K)throw X;await Y(wQ(H,G));continue}if(F!==void 0)clearTimeout(F);if(U.ok)return U;$.signal?.removeEventListener("abort",D);let N=await Z3(U),P=new h(U.status,N,U.headers.get("x-request-id")??void 0);if(H===K||!Q3(U.status,P))throw P;let _=e$(U.headers.get("retry-after"),V());await Y(_===void 0?wQ(H,G):Math.min(_,bQ)),X=P}throw X??Error("Provider request failed with no response.")}async function Z3(J){let Q;try{Q=await J.text()}catch{return null}try{return JSON.parse(Q)}catch{return Q}}var EJ=300000;function qJ(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 WJ extends Error{code;retryable;constructor(J,Q={}){super(J.message,Q);this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable}}var W3={png:"image/png",jpeg:"image/jpeg"};function G3(J){let Q=Number(J?.input_tokens??0),$=Number(J?.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J?.total_tokens??Q+$)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let G=J?.output_tokens_details?.image_tokens;if(typeof G==="number")Z.imageOutputTokens=G;return Z}function V3(J){let Q=atob(J),$=new Uint8Array(Q.length);for(let Z=0;Z<Q.length;Z++)$[Z]=Q.charCodeAt(Z);return $}function K3(J){let $=J?.data?.[0]?.b64_json;if(typeof $!=="string"||$.length===0)throw new WJ({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:V3($),mimeType:W3[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:G3(J.usage)}}async function fQ(J,Q,$,Z){let W;try{W=await o(J,Q,{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(G){if(Z.signal?.aborted)throw G;throw new WJ(R(G),{cause:G})}return K3(await W.json())}async function hQ(J,Q,$={}){return await fQ(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Q)},J,$)}async function yQ(J,Q,$={}){return await fQ(J.editsUrl,{method:"POST",headers:await J.headers(),body:Q},J,$)}class GJ{static models(){return[]}modelName(){return this.model}async generate(J){return await hQ(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let Q=new FormData;for(let[$,Z]of Object.entries(this.body(J)))if(Z!==void 0)Q.set($,String(Z));for(let $ of J.images)Q.append("image[]",$,$.name);if(J.mask)Q.set("mask",J.mask,J.mask.name);return await yQ(this.endpoint(),Q,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return R(J)}}var gQ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class xJ extends GJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new xJ(J,Q)}static models(){return gQ}endpoint(){return qJ($J(this.config,{timeoutMs:EJ}))}}class wJ extends GJ{model;config;constructor(J,Q={}){super();this.model=J,this.config=Q}static model(J,Q){return new wJ(J,Q)}static models(){return gQ}modelName(){return this.config.deployment??this.model}endpoint(){return qJ(ZJ(this.config,{timeoutMs:EJ}))}}var mQ=3;function IJ(J){let Q=new Map;for(let $ of J)for(let Z of $.content??[]){if(Z.type!=="file"||!Z.fileId||Q.has(Z.fileId))continue;Q.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return Q}function pQ(J,Q,$=new Map){if(!(Q instanceof h))return[];if(Q.status!==400&&Q.status!==404)return[];let Z=Y3(Q.body);if(!Z)return[];let W=X3(J.input);if(W.length===0)return[];let G=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(G){let X=J.input[Number(G[1])],H=vJ(X)[Number(G[2])],B=H&&typeof H.file_id==="string"?H.file_id:void 0;if(B)return[B]}let V=Z.message??"",K=cQ(W.map((X)=>X.fileId).filter((X)=>H3(V,X)));if(K.length>0)return K;let Y=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(V);if(Y){let X=Y[1].toLowerCase()==="image type"?"input_image":"input_file",H=Y[2].toLowerCase(),B=cQ(W.filter((z)=>z.type===X).map((z)=>z.fileId)),D=B.filter((z)=>($.get(z)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(D.length===1)return D;if(D.length===0&&B.length===1)return B}return[]}function lQ(J,Q,$=new Map){return{...J,input:J.input.map((Z)=>{let W=vJ(Z);if(!W.some((G)=>uQ(G,Q)))return Z;return{...Z,content:W.map((G)=>uQ(G,Q)?{type:"input_text",text:bJ($.get(String(G.file_id))?.name)}:G)}})}}function bJ(J){return`[${J?`attachment ${JSON.stringify(J)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function uQ(J,Q){return typeof J.file_id==="string"&&Q.has(J.file_id)}function vJ(J){let Q=J?.content;return Array.isArray(Q)?Q:[]}function X3(J){let Q=[];for(let $ of J)for(let Z of vJ($))if(typeof Z.file_id==="string"&&Z.file_id)Q.push({type:String(Z.type),fileId:Z.file_id});return Q}function Y3(J){if(!J||typeof J!=="object")return null;let Q=J,$=Q.error&&typeof Q.error==="object"?Q.error:J;return{message:typeof $.message==="string"?$.message:void 0,param:typeof $.param==="string"?$.param:void 0}}function H3(J,Q){let $=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${$}($|[^A-Za-z0-9_-])`).test(J)}function cQ(J){return[...new Set(J)]}async function*D3(J){let Q="",$="",Z=[],W,G=()=>{if(Z.length===0&&!$)return null;let Y={event:$,data:Z.join(`
76
+ `),id:W};return $="",Z=[],W=void 0,Y.data?Y:null},V=(Y)=>{let X=Y.endsWith("\r")?Y.slice(0,-1):Y;if(X==="")return G();if(X.startsWith(":"))return null;let H=X.indexOf(":"),B=H===-1?X:X.slice(0,H),D=H===-1?"":X.slice(H+1);if(D.startsWith(" "))D=D.slice(1);if(B==="event")$=D;else if(B==="data")Z.push(D);else if(B==="id")W=D;return null};for await(let Y of J){Q+=Y;let X=Q.indexOf(`
77
+ `);while(X!==-1){let H=Q.slice(0,X);Q=Q.slice(X+1);let B=V(H);if(B)yield B;X=Q.indexOf(`
78
+ `)}}if(Q.length>0){let Y=V(Q);if(Y)yield Y}let K=G();if(K)yield K}async function*dQ(J,Q={}){let $=new Map,Z=new Set,W,G=!1,V,K=(Y,X)=>({type:"finish",reason:Y,usage:X,...V?{model:V}:{}});for await(let Y of D3(J)){if(Y.data==="[DONE]")break;let X;try{X=JSON.parse(Y.data)}catch{continue}let H=typeof X.type==="string"?X.type:Y.event,B=X.response?.model;if(typeof B==="string"&&B)V=B;switch(H){case"response.output_text.delta":{let D=String(X.delta??"");if(!D)break;yield Q.structuredOutput?{type:"output-delta",delta:D}:{type:"text-delta",delta:D};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let D=String(X.delta??"");if(!D)break;yield{type:"reasoning-delta",delta:D,id:X.item_id};break}case"response.output_item.added":{let D=X.item;if(!D)break;if(D.type==="function_call"){let z=String(D.id??X.item_id??D.call_id??"");$.set(z,{callId:String(D.call_id??z),name:String(D.name??""),namespace:typeof D.namespace==="string"&&D.namespace?D.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let D=$.get(String(X.item_id??""));if(!D)break;let z=String(X.delta??"");if(!z)break;yield{type:"tool-call-delta",toolCallId:D.callId,name:D.name,argsDelta:z,...D.namespace?{namespace:D.namespace}:{}};break}case"response.function_call_arguments.done":{let D=String(X.item_id??""),z=$.get(D);if(!z)break;z.done=!0,yield{type:"tool-call",toolCallId:z.callId,name:z.name,args:String(X.arguments??""),...z.namespace?{namespace:z.namespace}:{}};break}case"response.output_item.done":{let D=X.item;if(!D)break;if(D.type==="function_call"){let z=String(D.id??X.item_id??D.call_id??""),F=$.get(z);if(F?.done)break;let U=(typeof D.namespace==="string"?D.namespace:"")||F?.namespace;if(yield{type:"tool-call",toolCallId:String(D.call_id??z),name:String(D.name??F?.name??""),args:String(D.arguments??""),...U?{namespace:U}:{}},F)F.done=!0;break}if(D.type==="tool_search_call"||D.type==="tool_search_output"){if(D.type==="tool_search_call"&&D.arguments!==void 0)W=D.arguments;let z=z3(D);if(z.loaded.length===0&&z.namespaces.length===0)break;let F=String(D.tool_search_call_id??D.id??"");if(Z.has(F))break;Z.add(F);let U=W;W=void 0,yield{type:"tool-search",...z,...U!==void 0&&U!==null?{arguments:U}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(X.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{G=!0,yield K("stop",fJ(X.response?.usage));break}case"response.incomplete":{G=!0;let D=fJ(X.response?.usage),z=X.response?.incomplete_details?.reason;if(z==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:B3(X.response?.content_filters),retryable:!1}},yield K("error",D);break}yield K(z==="max_output_tokens"?"length":"stop",D);break}case"response.failed":case"error":{G=!0;let D=X.response?.error??X.error??X;yield{type:"error",error:U3(D)},yield K("error",fJ(X.response?.usage));break}}if(G)return}if(!G)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error",y())}function z3(J){let Q=[],$=[];return iQ(J.results??J.tools??J.loaded??J.output,Q,$,0),{loaded:hJ(Q),namespaces:hJ($)}}function iQ(J,Q,$,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){Q.push(W);continue}if(!W||typeof W!=="object")continue;let G=W,V=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",K=G.tools??G.functions;if(Array.isArray(K)){if(V)$.push(V);iQ(K,Q,$,Z+1);continue}if(V)Q.push(V)}}function hJ(J){return J.filter((Q,$)=>J.indexOf(Q)===$)}function B3(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let $=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,G=W.content_filter_results;if(!G||typeof G!=="object")continue;for(let[V,K]of Object.entries(G))if(K&&typeof K==="object"&&K.filtered===!0)$.push(`${V} (${String(W.source_type??"unknown")})`)}return $.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${hJ($).join(", ")}.`}function U3(J){let Q=typeof J?.message==="string"?J.message:"The provider stream failed.",$=String(J?.code??"").toLowerCase();if($==="rate_limit_exceeded")return{code:"rate_limited",message:Q,retryable:!0};if($==="context_length_exceeded")return{code:"context_length_exceeded",message:Q,retryable:!1};if($.includes("content_filter"))return{code:"content_filtered",message:Q,retryable:!1};return{code:"provider_error",message:Q,retryable:!0}}function y(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function fJ(J){if(!J)return y();let Q=Number(J.input_tokens??0),$=Number(J.output_tokens??0),Z={inputTokens:Q,outputTokens:$,totalTokens:Number(J.total_tokens??Q+$)},W=J.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let G=J.input_tokens_details?.cached_tokens;if(typeof G==="number")Z.cachedInputTokens=G;return Z}async function*nQ(J){if(!J)return;let Q=J.getReader(),$=new TextDecoder;try{while(!0){let{done:W,value:G}=await Q.read();if(W)break;if(G)yield $.decode(G,{stream:!0})}let Z=$.decode();if(Z)yield Z}finally{Q.releaseLock()}}function yJ(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}async function*gJ(J,Q,$){let Z,W=Q,G=new Set;for(let V=0;Z===void 0;V++)try{Z=await o(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(W)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:$.signal,fetchImpl:J.fetchImpl})}catch(K){let Y=V<mQ?pQ(W,K,$.files).filter((H)=>!G.has(H)):[];if(Y.length>0){let H=R(K).message;for(let B of Y)G.add(B),yield{type:"file-rejected",fileId:B,message:H,...g(K)};W=lQ(W,new Set(Y),$.files);continue}let X=R(K);if(X.code!=="aborted")yield{type:"error",error:X,...g(K)};yield{type:"finish",reason:X.code==="aborted"?"aborted":"error",usage:y()};return}try{yield*dQ(nQ(Z.body),{structuredOutput:$.structuredOutput})}catch(V){let K=R(V);if(K.code==="aborted"){yield{type:"finish",reason:"aborted",usage:y()};return}yield{type:"error",error:K},yield{type:"finish",reason:"error",usage:y()}}}async function uJ(J,Q,$="user_data"){let Z=new FormData;Z.set("purpose",$),Z.set("file",Q);let G=await(await o(J.filesUrl,{method:"POST",headers:await J.headers(),body:Z},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,fetchImpl:J.fetchImpl})).json();if(!G?.id)throw Error("The provider accepted the upload but returned no file id.");return G.id}function cJ(J){let Q=P3(J);if(Q.startsWith("gpt-3.5")||Q.startsWith("text-")||Q.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let $=F3(Q);if($?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:$.major>1,toolSearch:oQ($)};if($?.kind==="gpt")return{reasoning:$.major>=5,structuredOutput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),fileInput:$.major>4||Q.startsWith("gpt-4o")||Q.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:oQ($)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function oQ(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function P3(J){return J.trim().toLowerCase()}function F3(J){let Q=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if(Q?.[1])return{kind:"gpt",major:Number(Q[1]),minor:Number(Q[2]??0)};let $=/^o(\d+)(?:[-.]|$)/.exec(J);if($?.[1])return{kind:"o",major:Number($[1]),minor:0};return null}function pJ(J,Q){let{capabilities:$}=Q,Z={model:Q.model,input:N3(J.messages,$,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=j3(J.tools,$);if(W.length>0){if(Z.tools=W,!$.parallelToolCalls)Z.parallel_tool_calls=!1}if(J.output)Z.text={format:{type:"json_schema",name:J.output.name,schema:J.output.schema,strict:J.output.strict}};if(J.reasoning&&$.reasoning)Z.reasoning=J.reasoning==="none"?{effort:"none"}:{effort:J.reasoning,summary:"auto"};if(typeof J.temperature==="number")Z.temperature=J.temperature;if(typeof J.maxOutputTokens==="number")Z.max_output_tokens=J.maxOutputTokens;return Z}function N3(J,Q,$){let Z=[],W=new Map;if(Q.toolSearch){for(let G of $??[])if(VJ(G))W.set(G.name,G)}for(let G of J){let V=G.role,K=[],Y=()=>{if(K.length===0)return;Z.push({type:"message",role:V,content:K}),K=[]};for(let X of G.content??[])switch(X.type){case"text":{if(!X.text)break;K.push(u(V,X.text));break}case"output":{if(X.partial)break;K.push(u(V,JSON.stringify(X.value)));break}case"file":{if(V==="assistant")break;let H=O3(X);if(!Q.fileInput){if(H)K.push(u(V,mJ(X,!1)));break}if(X.fileId?.startsWith(b))throw Error(`FilePart.fileId holds a gemi attachment id (${X.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!X.fileId&&!H)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(X.providerRejected){if(H)K.push(u(V,mJ(X,!1)));K.push(u(V,bJ(X.name)));break}if(H)K.push(u(V,mJ(X,!!X.fileId)));if(X.fileId)K.push(_3(X));break}case"reasoning":{Y();let H=A3(X);if(H)Z.push(H);break}case"tool-call":{if(X.partial)break;if(Y(),Q.toolSearch&&Array.isArray(X.toolSearches))for(let B of X.toolSearches)Z.push(...T3(B,$??[]));let H={type:"function_call",call_id:X.toolCallId,name:String(X.name),arguments:JSON.stringify(X.input??{})};if(X.namespace&&W.has(X.namespace))H.namespace=X.namespace;Z.push(H);break}case"tool-result":{Y(),Z.push({type:"function_call_output",call_id:X.toolCallId,output:R3(X)});break}}Y()}return C3(Z)}var L3="No result was recorded for this tool call. Assume it did not complete.";function C3(J){let Q=new Set,$=new Set,Z=[];for(let G of J){if(G.type==="function_call"){let V=String(G.call_id);if(Q.has(V))continue;Q.add(V)}else if(G.type==="function_call_output"){let V=String(G.call_id);if(!Q.has(V)||$.has(V))continue;$.add(V)}Z.push(G)}if($.size===Q.size)return Z;let W=[];for(let G of Z){if(W.push(G),G.type!=="function_call")continue;let V=String(G.call_id);if($.has(V))continue;$.add(V),W.push({type:"function_call_output",call_id:V,output:L3})}return W}function u(J,Q){return{type:J==="assistant"?"output_text":"input_text",text:Q}}function O3(J){let Q=J.attachmentId;return typeof Q==="string"&&Q.startsWith(b)?Q:void 0}function mJ(J,Q){let $=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)$.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)$.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${$.join(" ")}`;return Q?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function _3(J){let Q=J.mimeType?.trim().toLowerCase()??"";return{type:(Q?Q.startsWith("image/")&&Q!=="image/svg+xml":S3(J.name))?"input_image":"input_file",file_id:J.fileId}}function S3(J){let Q=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return Q?.[1]!==void 0&&M3.has(Q[1])}var M3=new Set(["jpeg","jpg","png","gif","webp"]);function A3(J){if(!J.id)return null;let Q={type:"reasoning",id:J.id};return Q.summary=J.text?[{type:"summary_text",text:J.text}]:[],Q}function R3(J){if(J.status==="ok")return typeof J.output==="string"?J.output:JSON.stringify(J.output??null);if(J.status==="running"){let Q=J.job?.summary===void 0?"":` Started with: ${JSON.stringify(J.job.summary)}.`;return`Started background job ${J.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${Q}`}if(J.status==="denied"){let Q=J.reason?` Reason given: ${J.reason}`:"";if(J.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${Q}`;if(J.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${Q}`;return`The user declined this tool call, so it did not run.${Q}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function T3(J,Q){let $=new Set(sQ(J?.loaded)),Z=sQ(J?.namespaces),W=new Set(Z),G=[];for(let K of Q)if(VJ(K)){if(!W.has(K.name))continue;let Y=K.tools.filter((X)=>$.size===0||$.has(X.name));if(Y.length===0)continue;G.push({type:"namespace",name:K.name,description:K.description,tools:Y.map((X)=>c(X,!0))})}else if(K.deferred&&$.has(K.name))G.push(c(K,!0));if(G.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:J.arguments&&typeof J.arguments==="object"?J.arguments:{paths:Z.length>0?Z:[...$]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:G}]}function sQ(J){return Array.isArray(J)?J.filter((Q)=>typeof Q==="string"):[]}function VJ(J){return Array.isArray(J.tools)}function j3(J,Q){if(!J||J.length===0)return[];if(!Q.toolSearch){let W=[];for(let G of J)if(VJ(G))for(let V of G.tools)W.push(c(V,!1));else W.push(c(G,!1));return W}let $=[],Z=!1;for(let W of J)if(VJ(W)){let G=W.tools.map((V)=>{if(V.deferred)Z=!0;return c(V,!0)});$.push({type:"namespace",name:W.name,description:W.description,tools:G})}else{if(W.deferred)Z=!0;$.push(c(W,!0))}if(Z)$.push({type:"tool_search"});return $}function c(J,Q){let $={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if(Q&&J.deferred)$.defer_loading=!0;return $}class m{static models(){return[]}normalizeError(J){return R(J)}}var aQ=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class lJ extends m{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=cJ(J),this.config=Q}static model(J,Q){return new lJ(J,Q)}static models(){return aQ}stream(J){let Q=pJ(J,{model:this.model,capabilities:this.capabilities});return gJ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:IJ(J.messages)})}upload(J){return uJ(this.endpoint(),J)}endpoint(){return yJ($J(this.config))}}class dJ extends m{model;capabilities;config;constructor(J,Q={}){super();this.model=J,this.capabilities=cJ(J),this.config=Q}static model(J,Q){return new dJ(J,Q)}static models(){return aQ}stream(J){let Q=pJ(J,{model:this.deployment(),capabilities:this.capabilities});return gJ(this.endpoint(),Q,{signal:J.signal,structuredOutput:Boolean(J.output),files:IJ(J.messages)})}upload(J){return uJ(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return yJ(ZJ(this.config))}}class KJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,Q){let $=this.entries.get(J);if($?.openUntil===void 0)return!0;let Z=this.now();if(Z<$.openUntil)return!1;if($.probeUntil!==void 0&&Z<$.probeUntil)return!1;return $.probeUntil=Z+Q.cooldownMs,!0}record(J,Q,$){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if(Q==="success")return this.entries.delete(J),W?"closed":void 0;if(Q==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=$.failures)return Z.openUntil=this.now()+$.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return"closed";return this.now()<Q.openUntil?"open":"half-open"}}function k3(J){switch(J.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}var tQ=Symbol("timed-out");class s extends m{model;capabilities;entries;options;circuit;constructor(J,Q={}){super();if(J.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of J)if(Z.timeoutMs!==void 0&&!(Z.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${Z.provider.model} must be a positive number, got ${Z.timeoutMs}.`);this.entries=[...J];let $=Q.circuit;if($){let Z=$.failures??3,W=$.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let G=new Set;for(let K of J){let Y=iJ(K);if(G.has(Y))throw Error(`FallbackProvider: two legs share the circuit key "${Y}". Give one of them a \`circuitKey\`.`);G.add(Y)}let V=$.store??new KJ;this.options={...Q,circuit:{...$,store:V}},this.circuit={policy:{failures:Z,cooldownMs:W},store:V,...$.onStateChange?{onStateChange:$.onStateChange}:{}}}else this.options=Q,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=E3(J.map((Z)=>Z.provider.capabilities))}static chain(J,Q){return new s(J,Q)}from(J){if(!Number.isInteger(J)||J<0||J>=this.entries.length)throw RangeError(`FallbackProvider.from(${J}): the chain has ${this.entries.length} entries.`);return new s(this.entries.slice(J),this.options)}leg(J){let Q=this.from(J).entries[0];return new s([Q],this.options)}upload(J){return this.entries[0].provider.upload(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let Q,$=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let G=this.entries[W],V=W===this.entries.length-1,K=G.provider.model;if(this.circuit&&!V&&!await this.allow(G))continue;Z+=1;let Y=!1,X=async(C)=>{if(Y)return;Y=!0,await this.record(W,G,C)},H=new AbortController,B=()=>H.abort($?.reason);if($?.aborted)H.abort($.reason);else $?.addEventListener("abort",B,{once:!0});let D=[],z=!1,F=!1,U,N,P,_=!1,O,M=!1,T=(C)=>{let A=Q?p(p(q(),Q),C.usage):C.usage;return Q=void 0,{...C,usage:A}};try{O=G.provider.stream({...J,...G.reasoning!==void 0?{reasoning:G.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let C=!0;for(;;){let A=C&&G.timeoutMs!==void 0?await q3(O.next(),G.timeoutMs):await O.next();if(A===tQ){_=!0,P={error:{code:"provider_error",message:`${K} sent nothing within ${G.timeoutMs}ms.`,retryable:!0}};break}if(C=!1,A.done){M=!0;break}let L=A.value;if(L.type==="finish"&&L.model)N=L.model;if(z){if(L.type==="finish")U=p(U??q(),L.usage),F=!0,yield T(L);else{if(L.type==="error")P={error:L.error};yield L}continue}if(k3(L)){z=!0,await X("success"),yield*D.splice(0),yield L;continue}if(L.type==="error")P={error:L.error,...L.status!==void 0?{status:L.status}:{},...L.requestId!==void 0?{requestId:L.requestId}:{}};else if(L.type==="finish"){if(U=p(U??q(),L.usage),L.reason==="error"&&!P)P={error:{code:"provider_error",message:`${K} ended the call with an error and did not say which.`,retryable:!1}}}D.push(L)}}catch(C){let A=G.provider.normalizeError(C);if(z){if(A.code!=="aborted")yield{type:"error",error:A,...g(C)};this.report({index:W,model:K,responseModel:N,attempt:Z,usage:U,outcome:nJ(A),error:A}),yield T({type:"finish",reason:A.code==="aborted"?"aborted":"error",usage:q(),...N?{model:N}:{}});return}P={error:A,...g(C)}}finally{if($?.removeEventListener("abort",B),!M)H.abort(),O?.return?.()?.catch(()=>{})}if(z){if(!F&&Q)yield{type:"finish",reason:P?"error":"stop",usage:Q},Q=void 0;this.report({index:W,model:K,responseModel:N,attempt:Z,usage:U,outcome:P?nJ(P.error):"ok",...P?{error:P.error}:{}});return}if($?.aborted){await X("none"),this.report({index:W,model:K,responseModel:N,attempt:Z,usage:U,outcome:"aborted"}),yield T({type:"finish",reason:"aborted",usage:U??q(),...N?{model:N}:{}});return}if(!P){await X("success"),this.report({index:W,model:K,responseModel:N,attempt:Z,usage:U,outcome:"ok"});for(let C of D)yield C.type==="finish"?T(C):C;return}let k=!V&&P.error.code!=="aborted"&&this.shouldFallBack(P.error,{index:W,model:K,timedOut:_,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}});if(await X(k?"failure":"none"),this.report({index:W,model:K,responseModel:N,attempt:Z,usage:U,outcome:k?"fallback":nJ(P.error),error:P.error}),k){if(U)Q=p(Q??q(),U);continue}let x=!1,E;for(let C of D){if(C.type==="finish"){E=C;continue}if(C.type==="error")x=!0;yield C}if(!x&&P.error.code!=="aborted")yield{type:"error",error:P.error,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}};yield T({type:"finish",reason:P.error.code==="aborted"?"aborted":E?.reason??"error",usage:U??q(),...N?{model:N}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(iJ(J),this.circuit.policy)}catch{return!0}}async record(J,Q,$){if(!this.circuit)return;let Z=iJ(Q),W;try{W=await this.circuit.store.record(Z,$,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:Q.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,Q){let $=this.options.fallbackOn??((Z)=>Z.retryable);try{return $(J,Q)}catch{return!1}}report(J){if(J.usage===void 0)delete J.usage;if(J.responseModel===void 0)delete J.responseModel;try{this.options.onUsage?.(J)}catch{}}}function iJ(J){return J.circuitKey??J.provider.model}function nJ(J){return J.code==="aborted"?"aborted":"failed"}function E3(J){return{reasoning:J.every((Q)=>Q.reasoning),structuredOutput:J.every((Q)=>Q.structuredOutput),fileInput:J.every((Q)=>Q.fileInput),parallelToolCalls:J.every((Q)=>Q.parallelToolCalls),toolSearch:J.every((Q)=>Q.toolSearch)}}function q3(J,Q){let $,Z=new Promise((W)=>{$=setTimeout(()=>W(tQ),Q)});return Promise.race([J,Z]).finally(()=>clearTimeout($))}async function x3(J,Q,$={}){let Z=$.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let G=0;G<J.entries.length;G++){let V=J.leg(G),K={index:G,model:V.model,results:[],errors:[]};for(let Y=0;Y<Z;Y++)try{K.results.push(await Q(V,{index:G,sample:Y}))}catch(X){K.errors.push({sample:Y,error:X})}W.push(K)}return W}class l extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,Q,$){super(`Frame ${Q} of run ${J} has been evicted; the oldest frame still buffered is ${$}. Reload the thread instead of resuming.`);this.runId=J;this.requested=Q;this.oldest=$}}class a extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class XJ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(J={}){this.ttlMs=J.ttlMs??60000,this.maxFrames=J.maxFrames??4096,this.maxAgeMs=J.maxAgeMs===void 0?3600000:J.maxAgeMs}register(J,Q={}){let $={run:J,threadId:Q.threadId,owner:Q.owner??null,clientRunId:Q.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(J.runId,$),Q.threadId)this.byThread.set(Q.threadId,J.runId);if(Q.clientRunId)this.byClientRun.set(Q.clientRunId,J.runId);return this.scheduleExpiry($,Q.maxRunDurationMs),this.pump($,Q)}findByClientRunId(J){let Q=this.byClientRun.get(J);return Q&&this.runs.has(Q)?Q:null}async find(J){let Q=this.byThread.get(J.threadId);if(!Q)return null;let $=this.runs.get(Q);if(!$)return null;return{runId:Q,seq:$.lastSeq}}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,Q){let $=this.ownerOf(J);return $===null||$===Q}isRunning(J){let Q=this.runs.get(J);return!!Q&&!Q.ended&&!Q.evicted}replay(J,Q){let $=this.runs.get(J);if(!$)throw new a(J);if(Q!==void 0&&Q<$.lostBefore)throw new l(J,Q,$.lostBefore);let Z=$.frames[0]?.seq;return this.drain($,J,Q??Z??$.lastSeq+1)}clear(){for(let J of this.runs.values()){if(J.evictAt)clearTimeout(J.evictAt);if(J.expireAt)clearTimeout(J.expireAt);J.ended=!0,this.notify(J)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(J,Q){let $=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let G=Q.onEvent;if(G)$=$.then(()=>G(Z.event)).catch((V)=>oJ(Q,V));continue}if(J.frames.push(Z),J.lastSeq=Z.seq,J.frames.length>this.maxFrames){let G=J.frames.shift();if(G)J.lostBefore=G.seq+1}this.notify(J);let W=Q.onEvent;if(W)$=$.then(()=>W(Z.event)).catch((G)=>oJ(Q,G))}}catch(Z){oJ(Q,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await $}}async*drain(J,Q,$){let Z=$;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new l(Q,Z,J.lostBefore);let G=J.frames,V=G[0]?.seq;if(V===void 0)break;let K=Math.max(0,Z-V);if(K>=G.length)break;let Y=G[K];yield Y,Z=Y.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,Q){if(J.version!==Q)return Promise.resolve();return new Promise(($)=>J.wake.add($))}notify(J){J.version++;let Q=Array.from(J.wake);J.wake.clear();for(let $ of Q)$()}scheduleEviction(J){if(J.evictAt)return;let Q=setTimeout(()=>{let $=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get($)===J)this.runs.delete($);if(J.threadId&&this.byThread.get(J.threadId)===$)this.byThread.delete(J.threadId);if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===$)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);Q.unref?.(),J.evictAt=Q}scheduleExpiry(J,Q){if(this.maxAgeMs===null||Q===null)return;let $=Q===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,Q+this.ttlMs);if(!Number.isFinite($)||$>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round($/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},$);Z.unref?.(),J.expireAt=Z}}var sJ=new XJ;function oJ(J,Q){try{J.onInternalError?.(Q)}catch{}}class YJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,Q){if(this.records.has(J))return;this.records.set(J,{...Q});while(this.records.size>this.maxEntries){let $=this.records.keys().next().value;if($===void 0)break;this.records.delete($)}}async get(J){let Q=this.records.get(J);return Q?{...Q}:null}}var aJ=new YJ;class eJ{now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,Q){let $=this.now();if(this.receipts.size>=this.sweepAt)this.sweep($);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>$)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:Q}),{status:"claimed"}}async complete(J,Q,$){this.receipts.set(J,{result:structuredClone(Q),expiresAt:$})}async release(J){let Q=this.receipts.get(J);if(Q&&!Q.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[Q,$]of this.receipts)if($.expiresAt<=J)this.receipts.delete(Q);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var rQ="pending",tJ="done:",w3=`
96
79
  if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
97
80
  local held = redis.call('GET', KEYS[1])
98
81
  if not held then return ARGV[1] end
99
- return held`,J0=`
82
+ return held`,I3=`
100
83
  if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
101
- return 0`;class YQ{injectedClient;prefix;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:ai:receipt"}async claim($,Q){let Z=await this.client.send("EVAL",[G0,"1",this.key($),lZ,dZ(Q)]);if(Z==="claimed")return{status:"claimed"};let V=String(Z??"");if(V.startsWith(GQ))return{status:"replay",result:JSON.parse(V.slice(GQ.length))};return{status:"blocked"}}async complete($,Q,Z){await this.client.send("SET",[this.key($),GQ+JSON.stringify(Q),"PX",dZ(Z)])}async release($){await this.client.send("EVAL",[J0,"1",this.key($),lZ])}key($){return`${this.prefix}:${$}`}get client(){if(this.injectedClient)return this.injectedClient;let $=I9(),Q=$.bound(JQ)?$.make(JQ).client:void 0;if(!Q)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return Q}}function dZ($){return String(Math.max(1,Math.ceil($-Date.now())))}var W0=86400000,Y0=60000;class $${ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor($={}){this.ttlMs=$.ttlMs??W0,this.clientOwnedIds=$.clientOwnedIds??!1}async createThread($){let Q=crypto.randomUUID();return this.threads.set(Q,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:Q}}async loadThread($){this.sweep();let Q=this.threads.get($);if(!Q)return this.clientOwnedIds?[]:null;return Q.touchedAt=Date.now(),Q.messages.slice()}async appendMessages($,Q){this.sweep();let Z=this.threads.get($);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${$} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set($,Z)}for(let V of Q){let G=Z.messages.findIndex((J)=>J.id===V.id);if(G===-1)Z.messages.push(V);else Z.messages[G]=V}Z.touchedAt=Date.now()}async removeMessages($,Q){this.sweep();let Z=this.threads.get($);if(!Z)return;let V=new Set(Q);Z.messages=Z.messages.filter((G)=>!V.has(G.id)),Z.touchedAt=Date.now()}async loadSummaries($){return this.threads.get($)?.summaries?.slice()??[]}async saveSummary($,Q){let Z=this.threads.get($);if(!Z)return;Z.summaries=h9(Z.summaries??[],Q)}delete($){this.threads.delete($)}get size(){return this.threads.size}sweep($=Date.now()){if($-this.lastSweep<Y0)return;this.lastSweep=$;for(let[Q,Z]of this.threads)if($-Z.touchedAt>this.ttlMs)this.threads.delete(Q)}}var XQ=new $$;function sZ($={}){return{messages:$.messages?[...$.messages]:[],pending:$.pending?[...$.pending]:[],error:null,threadId:$.threadId,seq:$.seq??-1,cursorRunId:$.cursorRunId,runMessageIds:[],loadedTools:[]}}function tZ($,Q,Z=new Date().toISOString()){if(!(Q.event.type==="run-start"&&Q.event.runId!==$.cursorRunId)&&Q.seq<=$.seq)return $;return{...aZ($,Q.event,Z),seq:Q.seq}}function aZ($,Q,Z){switch(Q.type){case"run-start":return{...$,messages:X0($.messages,Q.runId),runId:Q.runId,cursorRunId:Q.runId,threadId:Q.threadId??$.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return o($,Q.messageId,Z,(V)=>({...V,role:Q.role}));case"text-delta":if(nZ($,Q.messageId))return $;return o($,Q.messageId,Z,(V)=>({...V,content:D0(V.content,Q.delta)}));case"reasoning-delta":if(nZ($,Q.messageId))return $;return o($,Q.messageId,Z,(V)=>({...V,content:F0(V.content,Q.delta,Q.id)}));case"output-delta":return o($,Q.messageId,Z,(V)=>({...V,content:oZ(V.content,{type:"output",value:Q.snapshot,partial:!0},(G)=>G.type==="output")}));case"tool-call":return o($,Q.messageId,Z,(V)=>{let G=V.content.findIndex((B)=>B.type==="tool-call"&&B.toolCallId===Q.part.toolCallId),J=G===-1?void 0:V.content[G],W=Q.part.progress??J?.progress,X=Q.part.nested??J?.nested,K=Q.part.attachments??J?.attachments,Y={...Q.part,...W?{progress:W}:{},...X?{nested:X}:{},...K?{attachments:K}:{}},H=V.content.slice();if(G===-1)H.push(Y);else H[G]=Y;return{...V,content:H}});case"tool-search":{let V=Q.loaded.filter((G)=>!$.loadedTools.includes(G));if(V.length===0)return $;return{...$,loadedTools:[...$.loadedTools,...V]}}case"tool-progress":return iZ($,Q.toolCallId,(V)=>({...V,progress:[...V.progress??[],Q.data]}));case"nested-event":{let V=Q;return iZ($,Q.toolCallId,(G)=>{let J=G.nested??[],W=J.findIndex((H)=>H.runId===V.runId),X=J[W]??{runId:V.runId,agent:V.agent,messages:[]},K=z0(X,V,Z),Y=W===-1?[...J,K]:J.map((H,B)=>B===W?K:H);return{...G,nested:Y}})}case"tool-result":{let V=o($,Q.messageId,Z,(G)=>({...G,content:oZ(G.content,Q.part,(J)=>J.type==="tool-result"&&J.toolCallId===Q.part.toolCallId)}));return{...V,pending:V.pending.filter((G)=>G.toolCallId!==Q.part.toolCallId)}}case"message":{let V=$.messages.findIndex((W)=>W.id===Q.message.id),G=$.messages.slice();if(V===-1)G.push(Q.message);else G[V]=Q.message;let J=$.runMessageIds.includes(Q.message.id)?$.runMessageIds:[...$.runMessageIds,Q.message.id];return{...$,messages:G,runMessageIds:J}}case"message-id":{let V=$.messages.findIndex((J)=>J.id===Q.localId);if(V===-1){if(!Q.message||$.messages.some((J)=>J.id===Q.messageId))return $;return{...$,messages:[...$.messages,Q.message]}}let G=$.messages.some((J)=>J.id===Q.messageId)?$.messages.filter((J,W)=>W!==V):$.messages.map((J,W)=>W===V?{...J,id:Q.messageId}:J);return{...$,messages:G}}case"awaiting-input":return{...$,runId:Q.runId,pending:[...Q.pending]};case"message-end":return o($,Q.messageId,Z,(V)=>({...V,finishReason:Q.finishReason,...Q.outputTruncated?{outputTruncated:!0}:{},...Q.usage?{usage:Q.usage}:{},content:Q.outputTruncated||Q.finishReason==="length"?V.content.filter((G)=>!(G.type==="output"&&G.partial)):V.content.map((G)=>G.type==="output"&&G.partial?{...G,partial:!1}:G)}));case"usage":return{...$,usage:Q.usage};case"error":return{...$,error:Q.error,pending:[]};case"run-end":return{...$,runId:void 0,finishReason:Q.finishReason,messages:rZ($,Q.finishReason)};default:return $}}function X0($,Q){if(!$.some((Z)=>Z.runId===Q&&Z.finishReason===void 0))return $;return $.map((Z)=>{if(Z.runId!==Q||Z.finishReason!==void 0)return Z;let{runId:V,...G}=Z;return{...G,content:[]}})}function rZ($,Q){return $.messages.map((Z)=>Z.role==="assistant"&&$.runMessageIds.includes(Z.id)?K0(Z,Q):Z)}function K0($,Q){let Z=$.content.map((G)=>G.type==="tool-call"&&G.nested?.some((J)=>J.finishReason===void 0)?{...G,nested:G.nested.map((J)=>J.finishReason===void 0?H0(J,Q):J)}:G);if($.finishReason===void 0)return{...$,finishReason:Q,content:Z};return Z.some((G,J)=>G!==$.content[J])?{...$,content:Z}:$}function H0($,Q){let Z={messages:$.messages,pending:[],error:null,seq:-1,runMessageIds:$.messages.map((V)=>V.id),loadedTools:[]};return{...$,finishReason:Q,messages:rZ(Z,Q)}}function iZ($,Q,Z){for(let V=$.messages.length-1;V>=0;V--){let G=$.messages[V],J=G.content.findIndex((Y)=>Y.type==="tool-call"&&Y.toolCallId===Q);if(J===-1)continue;if(G.finishReason!==void 0&&!B0($,G,Q))return $;let W=G.content.slice();W[J]=Z(W[J]);let X=$.messages.slice();X[V]={...G,content:W};let K=$.runMessageIds.includes(G.id)?$.runMessageIds:[...$.runMessageIds,G.id];return{...$,runMessageIds:K,messages:X}}return $}function z0($,Q,Z){let V={messages:$.messages,pending:[],error:null,seq:-1,runMessageIds:$.messages.map((J)=>J.id),loadedTools:[],finishReason:$.finishReason},G=aZ(V,Q.event,Z);return{...$,...Q.label!==void 0?{label:Q.label}:{},messages:G.messages,...G.finishReason!==void 0?{finishReason:G.finishReason}:{},...G.usage!==void 0?{usage:G.usage}:{}}}function B0($,Q,Z){if(Q.finishReason!=="awaiting-input")return!1;return!$.messages.some((V)=>V.content.some((G)=>G.type==="tool-result"&&G.toolCallId===Z))}function nZ($,Q){let Z=$.messages.find((V)=>V.id===Q);return Z!==void 0&&Z.finishReason!==void 0}function o($,Q,Z,V){let G=$.messages.findIndex((X)=>X.id===Q),J=$.runMessageIds.includes(Q)?$.runMessageIds:[...$.runMessageIds,Q];if(G===-1){let X={id:Q,role:"assistant",content:[],createdAt:Z};return{...$,runMessageIds:J,messages:[...$.messages,V(X)]}}let W=$.messages.slice();return W[G]=V(W[G]),{...$,runMessageIds:J,messages:W}}function D0($,Q){let Z=$[$.length-1];if(Z&&Z.type==="text")return[...$.slice(0,-1),{type:"text",text:Z.text+Q}];return[...$,{type:"text",text:Q}]}function F0($,Q,Z){let V=$[$.length-1];if(V&&V.type==="reasoning"&&V.id===Z)return[...$.slice(0,-1),{...V,text:(V.text??"")+Q}];return[...$,Z?{type:"reasoning",id:Z,text:Q}:{type:"reasoning",text:Q}]}function oZ($,Q,Z){let V=$.findIndex(Z);if(V===-1)return[...$,Q];let G=$.slice();return G[V]=Q,G}class HQ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor($,Q,Z,V){this.store=$;this.threadId=Q;this.report=V;this.state=sZ({messages:Z})}finish($){if(this.closed)return;this.done.add($.id),this.write(()=>[KQ($)])}frame($){if(this.closed)return;let Q=$.event;if(Q.type==="run-start")this.runId=Q.runId;switch(this.state=tZ(this.state,$),Q.type){case"message":this.write(()=>[KQ(Q.message)]);return;case"tool-call":if(Q.part.partial)return;this.checkpoint(Q.messageId);return;case"message-start":case"tool-result":this.checkpoint(Q.messageId);return;default:return}}close($=[]){this.closed=!0;for(let Q of $)this.done.add(Q.id)}settled(){return this.chain}checkpoint($){if(this.done.has($))return;let Q=this.state.messages.find((V)=>V.id===$);if(!Q)return;let Z=this.runId;this.write(()=>{let V=KQ(Q);if(V.finishReason===void 0&&Z)V.runId=Z;return[V]})}write($){let Q;try{Q=$()}catch(Z){this.report(Z);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,Q)).catch((Z)=>this.report(Z))}}function KQ($){return structuredClone($)}async function eZ($,Q){let Z=[],V=null,G=$.slice();for(let J=0;J<G.length;J++){let W=G[J];if(W.role!=="assistant"||W.finishReason!==void 0)continue;if(W.runId&&await Q(W.runId))continue;V??=new Set($.flatMap((Y)=>Y.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let X=W.content.map((Y)=>Y.type==="tool-call"?$6(Y):Y);for(let Y of W.content){if(Y.type!=="tool-call"||V.has(Y.toolCallId))continue;let H={type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"denied",cause:"interrupted"};X.push(H)}let K={...W,content:X,finishReason:"interrupted"};G[J]=K,Z.push(K)}return{messages:G,settled:Z}}function $6($){let{partial:Q,...Z}=$;if(!Z.nested?.some((V)=>V.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(L0)}}function L0($){if($.finishReason!==void 0)return $;return{...$,finishReason:"interrupted",messages:$.messages.map((Q)=>Q.role==="assistant"&&Q.finishReason===void 0?{...Q,finishReason:"interrupted",content:Q.content.map((Z)=>Z.type==="tool-call"?$6(Z):Z)}:Q)}}var U0=50,P0=["running","ok","error"];async function Q6($,Q){let{store:Z,threadId:V}=Q,G=Math.max(U0,Q.scan??0),J=await Z.listForThread(V,{limit:G}),W,X=async(D)=>{if(D.state!=="running")return D;if(W??=await z$(Z),D.deadlineAt>W)return D;return await B$(Z,D),await Z.get(D.id)??D};for(let D=0;D<J.length;D++)J[D]=await X(J[D]);let K=new Map(J.map((D)=>[D.id,D])),Y=$.slice(),H=[],B=new Set;for(let D=0;D<Y.length;D++){let L=Y[D],F=null;for(let U=0;U<L.content.length;U++){let P=L.content[U];if(P.type==="tool-call")B.add(P.toolCallId);if(P.type!=="tool-result"||P.status!=="running")continue;let q=P.job?.id,_=q?K.get(q):void 0;if(q&&_===void 0){let O=await Z.get(q);if(_=O?await X(O):void 0,_)K.set(q,_)}if(_?.state==="running")continue;F??=L.content.slice(),F[U]=N0(P,_,Q.outputSchemaFor)}if(F){let U={...L,content:F};Y[D]=U,H.push(U)}}let z=[];for(let D of J){if(D.orphaned||B.has(D.toolCallId))continue;if(await Q.isRunLive(D.runId))continue;z.push(D)}return{messages:Y,settled:H,orphans:z,jobs:J}}async function Z6($,Q,Z){for(let V of Q)try{await $.transition(V.id,P0,{orphaned:!0})}catch(G){Z(G)}}function N0($,Q,Z){let V={type:"tool-result",toolCallId:$.toolCallId,name:$.name};if(!Q)return{...V,status:"error",job:$.job,error:{code:"tool_error",message:`The background job for "${String($.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:$.toolCallId,retryable:!0}};let G={id:Q.id,...Q.summary!==void 0?{summary:Q.summary}:{},...Q.usage?{usage:Q.usage}:{}};if(Q.state==="error")return{...V,status:"error",job:G,error:Q.error??{code:"tool_error",message:`The background job for "${String($.name)}" failed.`,toolCallId:$.toolCallId,retryable:!0}};let J=Z?.(String($.name));if(J){let W=J.safeParse(Q.output);if(W.ok===!1)return{...V,status:"error",job:G,error:{code:"invalid_tool_result",message:`The background job for "${String($.name)}" finished with an output that does not match the tool's output schema: ${W.errors.join(", ")}`,toolCallId:$.toolCallId,retryable:!0}};return{...V,status:"ok",job:G,output:W.value}}return{...V,status:"ok",job:G,output:Q.output}}var C0=D6,Q$=new Map,V6=new WeakMap,Z$=new Map,O0=4194304,_0=1000,q0=5,G6=65536,C6=()=>{};class O6{byKey=new Map;take($,Q,Z){let V=this.byKey.get($);if(!V?.has(Q)&&(V?.size??0)>=Z)return null;if(!V)V=new Map,this.byKey.set($,V);V.set(Q,(V.get(Q)??0)+1);let G=!1;return()=>{if(G)return;G=!0;let J=this.byKey.get($),W=(J?.get(Q)??1)-1;if(!J)return;if(W>0)J.set(Q,W);else if(J.delete(Q),J.size===0)this.byKey.delete($)}}}var J6=new WeakMap;function M0($){let Q=J6.get($);if(!Q)Q=new O6,J6.set($,Q);return Q}class UQ extends C0{static kind="agent-controller";store=XQ;liveRuns=ZQ;attachments=t;attachmentStorage=w9;fileOwners=VQ;nonces=C9;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions($,Q){}context($,Q){return{}}requireThread=!1;maxBodyBytes=O0;maxHistoryMessages=_0;contextWindow=void 0;prepareStep($,Q){}maxConcurrentRuns=q0;runLimitKey($,Q){return Q.owner}authorizeRequest($,Q){return this.resource?.authorize($,Q)}resource;runOwner($){let Q=$.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}async stream($=new M9){let Q=await zQ($,this.maxBodyBytes);if(Q.error)return V$(Q);let Z=Q.body,V=typeof Z.threadId==="string"?Z.threadId:void 0,G=x0(Z);if(G.error)return V$({body:{},error:G.error});let J=G.turn,W=V!==void 0&&Z.regenerate===!0,X=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,K=_6(Z);if(this.requireThread&&!V)return f(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(W&&!this.store.removeMessages)return f(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(!V&&Array.isArray(Z.messages)&&Z.messages.length>this.maxHistoryMessages)return FQ(413,"history_too_long",`The conversation has ${Z.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner($),H=X?{cancelled:!1,owner:Y}:null;if(H)Z$.set(X,H);let B=null,z=[],D=async()=>{try{return await L()}finally{if(V&&z.length>0&&B===null)await this.store.appendMessages(V,z).catch((F)=>this.reportHookFailure(F))}},L=async()=>{let F,U=null;if(V){let E=await this.store.loadThread(V);if(!E)return f(404,{code:"thread_not_found",message:`Thread ${V} does not exist here, or has expired.`});let s=await this.settleThread(V,E,{write:!0});if(F=s.messages,U=this.jobsBlock(s.jobs),W){let J9=f0(F);if(!J9)return f(409,{code:"nothing_to_regenerate",message:`Thread ${V} has no user turn to answer again.`});z=F.slice(J9.index),await this.store.removeMessages(V,z.map((S6)=>S6.id)),F=F.slice(0,J9.index),J=J?.localId?{...J9.turn,localId:J.localId}:J9.turn}}else F=Array.isArray(Z.messages)?Z.messages:[],p0(this.nonces);let P=[await this.instructions($,{body:K})||void 0,U??void 0].filter(Boolean).join(`
84
+ return 0`;class JQ{injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,Q){let $=await this.client.send("EVAL",[w3,"1",this.key(J),rQ,eQ(Q)]);if($==="claimed")return{status:"claimed"};let Z=String($??"");if(Z.startsWith(tJ))return{status:"replay",result:JSON.parse(Z.slice(tJ.length))};return{status:"blocked"}}async complete(J,Q,$){await this.client.send("SET",[this.key(J),tJ+JSON.stringify(Q),"PX",eQ($)])}async release(J){await this.client.send("EVAL",[I3,"1",this.key(J),rQ])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=J$(),Q=J.bound(rJ)?J.make(rJ).client:void 0;if(!Q)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return Q}}function eQ(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var b3=86400000,v3=60000;class HJ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??b3,this.clientOwnedIds=J.clientOwnedIds??!1}async createThread(J){let Q=crypto.randomUUID();return this.threads.set(Q,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:Q}}async loadThread(J){this.sweep();let Q=this.threads.get(J);if(!Q)return this.clientOwnedIds?[]:null;return Q.touchedAt=Date.now(),Q.messages.slice()}async appendMessages(J,Q){this.sweep();let $=this.threads.get(J);if(!$){if(!this.clientOwnedIds)throw Error(`Thread ${J} does not exist here, or has expired.`);$={messages:[],touchedAt:Date.now()},this.threads.set(J,$)}for(let Z of Q){let W=$.messages.findIndex((G)=>G.id===Z.id);if(W===-1)$.messages.push(Z);else $.messages[W]=Z}$.touchedAt=Date.now()}async removeMessages(J,Q){this.sweep();let $=this.threads.get(J);if(!$)return;let Z=new Set(Q);$.messages=$.messages.filter((W)=>!Z.has(W.id)),$.touchedAt=Date.now()}async loadSummaries(J){return this.threads.get(J)?.summaries?.slice()??[]}async saveSummary(J,Q){let $=this.threads.get(J);if(!$)return;$.summaries=QQ($.summaries??[],Q)}delete(J){this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<v3)return;this.lastSweep=J;for(let[Q,$]of this.threads)if(J-$.touchedAt>this.ttlMs)this.threads.delete(Q)}}var $Q=new HJ;function W$(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 G$(J,Q,$=new Date().toISOString()){if(!(Q.event.type==="run-start"&&Q.event.runId!==J.cursorRunId)&&Q.seq<=J.seq)return J;return{...V$(J,Q.event,$),seq:Q.seq}}function V$(J,Q,$){switch(Q.type){case"run-start":return{...J,messages:f3(J.messages,Q.runId),runId:Q.runId,cursorRunId:Q.runId,threadId:Q.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return v(J,Q.messageId,$,(Z)=>({...Z,role:Q.role}));case"text-delta":if($$(J,Q.messageId))return J;return v(J,Q.messageId,$,(Z)=>({...Z,content:c3(Z.content,Q.delta)}));case"reasoning-delta":if($$(J,Q.messageId))return J;return v(J,Q.messageId,$,(Z)=>({...Z,content:m3(Z.content,Q.delta,Q.id)}));case"output-delta":return v(J,Q.messageId,$,(Z)=>({...Z,content:Z$(Z.content,{type:"output",value:Q.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return v(J,Q.messageId,$,(Z)=>{let W=Z.content.findIndex((B)=>B.type==="tool-call"&&B.toolCallId===Q.part.toolCallId),G=W===-1?void 0:Z.content[W],V=Q.part.progress??G?.progress,K=Q.part.nested??G?.nested,Y=Q.part.attachments??G?.attachments,X={...Q.part,...V?{progress:V}:{},...K?{nested:K}:{},...Y?{attachments:Y}:{}},H=Z.content.slice();if(W===-1)H.push(X);else H[W]=X;return{...Z,content:H}});case"tool-search":{let Z=Q.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return Q$(J,Q.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],Q.data]}));case"nested-event":{let Z=Q;return Q$(J,Q.toolCallId,(W)=>{let G=W.nested??[],V=G.findIndex((H)=>H.runId===Z.runId),K=G[V]??{runId:Z.runId,agent:Z.agent,messages:[]},Y=g3(K,Z,$),X=V===-1?[...G,Y]:G.map((H,B)=>B===V?Y:H);return{...W,nested:X}})}case"tool-result":{let Z=v(J,Q.messageId,$,(W)=>({...W,content:Z$(W.content,Q.part,(G)=>G.type==="tool-result"&&G.toolCallId===Q.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==Q.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((V)=>V.id===Q.message.id),W=J.messages.slice();if(Z===-1)W.push(Q.message);else W[Z]=Q.message;let G=J.runMessageIds.includes(Q.message.id)?J.runMessageIds:[...J.runMessageIds,Q.message.id];return{...J,messages:W,runMessageIds:G}}case"message-id":{let Z=J.messages.findIndex((K)=>K.id===Q.localId);if(Z===-1){if(!Q.message||J.messages.some((K)=>K.id===Q.messageId))return J;return{...J,messages:[...J.messages,Q.message]}}let W=J.messages[Z],G={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},V=J.messages.some((K)=>K.id===Q.messageId)?J.messages.filter((K,Y)=>Y!==Z).map((K)=>K.id===Q.messageId?{...K,...G}:K):J.messages.map((K,Y)=>Y===Z?{...K,...G,id:Q.messageId}:K);return{...J,messages:V}}case"awaiting-input":return{...J,runId:Q.runId,pending:[...Q.pending]};case"message-end":return v(J,Q.messageId,$,(Z)=>({...Z,finishReason:Q.finishReason,...Q.outputTruncated?{outputTruncated:!0}:{},...Q.usage?{usage:Q.usage}:{},content:Q.outputTruncated||Q.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...J,usage:Q.usage};case"error":return{...J,error:Q.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:Q.finishReason,messages:K$(J,Q.finishReason)};default:return J}}function f3(J,Q){if(!J.some(($)=>$.runId===Q&&$.finishReason===void 0))return J;return J.map(($)=>{if($.runId!==Q||$.finishReason!==void 0)return $;let{runId:Z,...W}=$;return{...W,content:[]}})}function K$(J,Q){return J.messages.map(($)=>$.role==="assistant"&&J.runMessageIds.includes($.id)?h3($,Q):$)}function h3(J,Q){let $=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((G)=>G.finishReason===void 0)?{...W,nested:W.nested.map((G)=>G.finishReason===void 0?y3(G,Q):G)}:W);if(J.finishReason===void 0)return{...J,finishReason:Q,content:$};return $.some((W,G)=>W!==J.content[G])?{...J,content:$}:J}function y3(J,Q){let $={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:Q,messages:K$($,Q)}}function Q$(J,Q,$){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],G=W.content.findIndex((X)=>X.type==="tool-call"&&X.toolCallId===Q);if(G===-1)continue;if(W.finishReason!==void 0&&!u3(J,W,Q))return J;let V=W.content.slice();V[G]=$(V[G]);let K=J.messages.slice();K[Z]={...W,content:V};let Y=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:Y,messages:K}}return J}function g3(J,Q,$){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((G)=>G.id),loadedTools:[],finishReason:J.finishReason},W=V$(Z,Q.event,$);return{...J,...Q.label!==void 0?{label:Q.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function u3(J,Q,$){if(Q.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===$))}function $$(J,Q){let $=J.messages.find((Z)=>Z.id===Q);return $!==void 0&&$.finishReason!==void 0}function v(J,Q,$,Z){let W=J.messages.findIndex((K)=>K.id===Q),G=J.runMessageIds.includes(Q)?J.runMessageIds:[...J.runMessageIds,Q];if(W===-1){let K={id:Q,role:"assistant",content:[],createdAt:$};return{...J,runMessageIds:G,messages:[...J.messages,Z(K)]}}let V=J.messages.slice();return V[W]=Z(V[W]),{...J,runMessageIds:G,messages:V}}function c3(J,Q){let $=J[J.length-1];if($&&$.type==="text")return[...J.slice(0,-1),{type:"text",text:$.text+Q}];return[...J,{type:"text",text:Q}]}function m3(J,Q,$){let Z=J[J.length-1];if(Z&&Z.type==="reasoning"&&Z.id===$)return[...J.slice(0,-1),{...Z,text:(Z.text??"")+Q}];return[...J,$?{type:"reasoning",id:$,text:Q}:{type:"reasoning",text:Q}]}function Z$(J,Q,$){let Z=J.findIndex($);if(Z===-1)return[...J,Q];let W=J.slice();return W[Z]=Q,W}class WQ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,Q,$,Z){this.store=J;this.threadId=Q;this.report=Z;this.state=W$({messages:$})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[ZQ(J)])}frame(J){if(this.closed)return;let Q=J.event;if(Q.type==="run-start")this.runId=Q.runId;switch(this.state=G$(this.state,J),Q.type){case"message":this.write(()=>[ZQ(Q.message)]);return;case"tool-call":if(Q.part.partial)return;this.checkpoint(Q.messageId);return;case"message-start":case"tool-result":this.checkpoint(Q.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let Q of J)this.done.add(Q.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let Q=this.state.messages.find((Z)=>Z.id===J);if(!Q)return;let $=this.runId;this.write(()=>{let Z=ZQ(Q);if(Z.finishReason===void 0&&$)Z.runId=$;return[Z]})}write(J){let Q;try{Q=J()}catch($){this.report($);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,Q)).catch(($)=>this.report($))}}function ZQ(J){return structuredClone(J)}async function X$(J,Q){let $=[],Z=null,W=J.slice();for(let G=0;G<W.length;G++){let V=W[G];if(V.role!=="assistant"||V.finishReason!==void 0)continue;if(V.runId&&await Q(V.runId))continue;Z??=new Set(J.flatMap((X)=>X.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let K=V.content.map((X)=>X.type==="tool-call"?Y$(X):X);for(let X of V.content){if(X.type!=="tool-call"||Z.has(X.toolCallId))continue;let H={type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"denied",cause:"interrupted"};K.push(H)}let Y={...V,content:K,finishReason:"interrupted"};W[G]=Y,$.push(Y)}return{messages:W,settled:$}}function Y$(J){let{partial:Q,...$}=J;if(!$.nested?.some((Z)=>Z.finishReason===void 0))return $;return{...$,nested:$.nested.map(p3)}}function p3(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map((Q)=>Q.role==="assistant"&&Q.finishReason===void 0?{...Q,finishReason:"interrupted",content:Q.content.map(($)=>$.type==="tool-call"?Y$($):$)}:Q)}}var l3=50,d3=["running","ok","error"];async function z$(J,Q){let{store:$,threadId:Z}=Q,W=Math.max(l3,Q.scan??0),G=await $.listForThread(Z,{limit:W}),V,K=async(z)=>{if(z.state!=="running")return z;if(V??=await H$($),z.deadlineAt>V)return z;return await D$($,z),await $.get(z.id)??z};for(let z=0;z<G.length;z++)G[z]=await K(G[z]);let Y=new Map(G.map((z)=>[z.id,z])),X=J.slice(),H=[],B=new Set;for(let z=0;z<X.length;z++){let F=X[z],U=null;for(let N=0;N<F.content.length;N++){let P=F.content[N];if(P.type==="tool-call")B.add(P.toolCallId);if(P.type!=="tool-result"||P.status!=="running")continue;let _=P.job?.id,O=_?Y.get(_):void 0;if(_&&O===void 0){let M=await $.get(_);if(O=M?await K(M):void 0,O)Y.set(_,O)}if(O?.state==="running")continue;U??=F.content.slice(),U[N]=i3(P,O,Q.outputSchemaFor)}if(U){let N={...F,content:U};X[z]=N,H.push(N)}}let D=[];for(let z of G){if(z.orphaned||B.has(z.toolCallId))continue;if(await Q.isRunLive(z.runId))continue;D.push(z)}return{messages:X,settled:H,orphans:D,jobs:G}}async function B$(J,Q,$){for(let Z of Q)try{await J.transition(Z.id,d3,{orphaned:!0})}catch(W){$(W)}}function i3(J,Q,$){let Z={type:"tool-result",toolCallId:J.toolCallId,name:J.name};if(!Q)return{...Z,status:"error",job:J.job,error:{code:"tool_error",message:`The background job for "${String(J.name)}" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,toolCallId:J.toolCallId,retryable:!0}};let W={id:Q.id,...Q.summary!==void 0?{summary:Q.summary}:{},...Q.usage?{usage:Q.usage}:{}};if(Q.state==="error")return{...Z,status:"error",job:W,error:Q.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let G=$?.(String(J.name));if(G){let V=G.safeParse(Q.output);if(V.ok===!1)return{...Z,status:"error",job:W,error:{code:"invalid_tool_result",message:`The background job for "${String(J.name)}" finished with an output that does not match the tool's output schema: ${V.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return{...Z,status:"ok",job:W,output:V.value}}return{...Z,status:"ok",job:W,output:Q.output}}class OJ extends Error{status;code;kind;constructor(J,Q){super(J);this.name="AgentTurnError",this.status=Q.status,this.code=Q.code,this.kind=Q.kind}static async from(J){let Q={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")Q=Z.error}catch{}let $=(Z)=>typeof Q[Z]==="string"?Q[Z]:void 0;return new OJ($("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:$("code"),kind:$("kind")})}}function n3(J){for(let Q=J.length-1;Q>=0;Q--){let $=J[Q];if($.role!=="assistant")continue;return $.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var o3=R$,DJ=new Map,U$=new WeakMap,t=new WeakMap,P$="http://gemi.internal/__gemi/agent-turn",zJ=new Map,s3=4194304,a3=1000,t3=5,F$=65536,PJ=()=>{};class y${byKey=new Map;take(J,Q,$){let Z=this.byKey.get(J);if(!Z?.has(Q)&&(Z?.size??0)>=$)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set(Q,(Z.get(Q)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let G=this.byKey.get(J),V=(G?.get(Q)??1)-1;if(!G)return;if(V>0)G.set(Q,V);else if(G.delete(Q),G.size===0)this.byKey.delete(J)}}}var N$=new WeakMap;function r3(J){let Q=N$.get(J);if(!Q)Q=new y$,N$.set(J,Q);return Q}class UQ extends o3{static kind="agent-controller";store=$Q;liveRuns=sJ;attachments=CJ;attachmentStorage=k$;fileOwners=aJ;nonces=DQ;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,Q){}context(J,Q){return{}}requireThread=!1;maxBodyBytes=s3;maxHistoryMessages=a3;contextWindow=void 0;prepareStep(J,Q){}maxConcurrentRuns=t3;runLimitKey(J,Q){return Q.owner}authorizeRequest(J,Q){return this.resource?.authorize(J,Q)}resource;runOwner(J){let Q=J.ctx?.()?.user,$=Q?.id??Q?.publicId;if($!==void 0&&$!==null&&String($)!=="")return`user:${String($)}`;return null}static async startTurn(J){let{threadId:Q}=J;if(typeof Q!=="string"||Q==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let $={...J.turn,...J.text!==void 0?{text:J.text}:{}},Z={...J.body,threadId:Q,turn:$},W=new d(new Request(P$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)}),{},"api",new URL(P$).pathname),G=new this;t.set(W,null);let V=await n.run(W,()=>G.stream(W),{user:J.user??null}),K=t.get(W);if(!K)throw await OJ.from(V);t.delete(W),V.body?.cancel().catch(PJ);let{run:Y,hooks:X}=K,H=[],B=(async()=>{for await(let z of Y)if(z.type==="awaiting-input")H=z.pending})().catch(PJ),D;return{runId:Y.runId,threadId:Q,run:Y,stop:(z)=>Y.stop(z),result:()=>D??=(async()=>{let z=await Y.result();await Promise.all([X,B]);let F=z.messages;return{...z,threadId:Q,text:n3(F),pending:z.finishReason==="awaiting-input"?H:[]}})()}}async stream(J=new d){let Q=await GQ(J,this.maxBodyBytes);if(Q.error)return BJ(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:void 0,W=V9($);if(W.error)return BJ({body:{},error:W.error});let G=W.turn,V=Z!==void 0&&$.regenerate===!0,K=typeof $.clientRunId==="string"?$.clientRunId:void 0,Y=g$($);if(this.requireThread&&!Z)return j(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(V&&!this.store.removeMessages)return j(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!Z&&Array.isArray($.messages)&&$.messages.length>this.maxHistoryMessages)return YQ(413,"history_too_long",`The conversation has ${$.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let X=await this.runOwner(J),H=K?{cancelled:!1,owner:X}:null;if(H)zJ.set(K,H);let B=null,D=[],z=async()=>{try{return await F()}finally{if(Z&&D.length>0&&B===null)await this.store.appendMessages(Z,D).catch((U)=>this.reportHookFailure(U))}},F=async()=>{let U,N=null;if(Z){let S=await this.store.loadThread(Z);if(!S)return j(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let f=await this.settleThread(Z,S,{write:!0});if(U=f.messages,N=this.jobsBlock(f.jobs),V){let i=H9(U);if(!i)return j(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});D=U.slice(i.index),await this.store.removeMessages(Z,D.map((m$)=>m$.id)),U=U.slice(0,i.index),G=G?.localId?{...i.turn,localId:G.localId}:i.turn}}else U=Array.isArray($.messages)?$.messages:[],N9(this.nonces);let P=[await this.instructions(J,{body:Y})||void 0,N??void 0].filter(Boolean).join(`
102
85
 
103
- `)||void 0,q=await this.context($,{body:K}),_=await this.attachmentsFor($,V,{body:K});if(H?.cancelled)return H6();let O=V?new HQ(this.store,V,F,(E)=>this.reportHookFailure(E)):null,A=`run_${crypto.randomUUID()}`,k={req:$,runId:A,threadId:V},x={id:null,notified:Promise.resolve()},C=this.agent.stream({runId:A,messages:F,turn:J,threadId:V,...O?{onMessage:(E)=>O.finish(E)}:{},onTurn:(E)=>{if(x.id!==null)return;x.id=E.id;let s=O?O.settled():Promise.resolve();x.notified=s.then(()=>this.safely(()=>this.onMessage(E,k)))},instructions:P,context:q,attachments:_,body:K,redactError:(E,s)=>this.redactError(E,s,k),nonces:this.nonces,receipts:this.receipts,subject:Y,...V?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...V&&gQ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==UQ.prototype.prepareStep?{prepareStep:(E)=>this.prepareStep(E,k)}:{}}),N=this.liveRuns.register(C,{threadId:V,owner:Y,clientRunId:X,onEvent:(E)=>this.dispatchEvent(E,k),onInternalError:(E)=>this.reportHookFailure(E),maxRunDurationMs:this.agent.maxRunDurationMs});if(B=C,O)this.follow(C,O);let{stored:T,hooks:S}=this.persistRun(C,k,N,O,x);return V6.set(C,T),$.ctx?.()?.waitUntil(S),C.toResponse()};try{await this.authorizeRequest($,{route:"stream",threadId:V,body:K});let F=await this.foreignFile([...J?.files??[],...V?[]:y0(Z.messages)],Y);if(F)return F;if(H?.cancelled)return H6();let U=await this.runLimitKey($,{owner:Y,threadId:V}),P=U===null?C6:M0(this.liveRuns).take(U,V?`thread:${V}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return FQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return V?await this.withThread(V,Y,D):await D()}finally{let q=B;if(q)q.result().then(P,P);else P()}}finally{if(H&&Z$.get(X)===H)Z$.delete(X)}}async withThread($,Q,Z){let V=Q$.get($)??Promise.resolve(),G,J=new Promise((X)=>{G=X}),W=V.then(()=>J);Q$.set($,W),await V;try{let X=await this.liveRuns.find({threadId:$});if(X&&this.liveRuns.isRunning(X.runId)&&!this.liveRuns.mayAccess(X.runId,Q))return G$();let K=X?this.liveRuns.get(X.runId):null;if(K)K.stop({reason:"superseded by a later turn on this thread"}),await V6.get(K);return await Z()}finally{if(G(),Q$.get($)===W)Q$.delete($)}}async attach($=new M9){let Q=await zQ($,G6);if(Q.error)return V$(Q);let Z=Q.body,V=typeof Z.threadId==="string"?Z.threadId:b0($,"threadId");if(!V)return f(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest($,{route:"attach",threadId:V});let G=await this.liveRuns.find({threadId:V});if(G&&!this.liveRuns.mayAccess(G.runId,await this.runOwner($)))return G$();if(!G)return f(404,{code:"no_live_run",message:`No run in progress for thread ${V} in this process.`});let J=typeof Z.runId==="string"?Z.runId:void 0,W=J&&J!==G.runId?void 0:w0($,Z);try{return U6(this.liveRuns.replay(G.runId,W))}catch(X){if(X instanceof G9)return f(410,{code:X.code,message:X.message,oldestSeq:X.oldest});if(X instanceof q9)return f(404,{code:X.code,message:X.message});throw X}}async stop($=new M9){let Q=await zQ($,G6);if(Q.error)return V$(Q);let Z=Q.body;await this.authorizeRequest($,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let V=await this.runOwner($),G=typeof Z.runId==="string"?Z.runId:void 0;if(!G&&typeof Z.clientRunId==="string"){if(G=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!G){let W=Z$.get(Z.clientRunId);if(W){if(W.owner!==null&&W.owner!==V)return G$();return W.cancelled=!0,{stopped:!0}}}}if(!G&&typeof Z.threadId==="string")G=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let J=G?this.liveRuns.get(G):null;if(!J)return{stopped:!1};if(!this.liveRuns.mayAccess(J.runId,V))return G$();return J.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope($,Q,Z){let V=$.ctx()?.user,G=V?.id??V?.publicId;if(G!==void 0&&G!==null&&String(G)!=="")return{key:`user:${String(G)}`};if(Q)return{key:`thread:${Q}`};return null}attachmentLimits($){return null}attachmentDestination($,Q){return"both"}async attachmentsFor($,Q,Z={body:{}}){let V=await this.attachmentScope($,Q,Z);if(!V)return null;return new p(this.attachments,this.attachmentStorage,V)}async upload($=new M9){let Q=await $.rawRequest.formData(),Z=Q.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let V=Z instanceof File&&Z.name?Z.name:"upload",G=Z.type||"application/octet-stream",J=S0(Q.get("body")),W=Q.get("threadId");await this.authorizeRequest($,{route:"upload",threadId:typeof W==="string"&&W.length>0?W:void 0,body:J});let X=A0(await this.attachmentLimits($),Z,V,G);if(X)throw new q6(X.code,X.message);let K=typeof W==="string"&&W.length>0&&await this.store.loadThread(W)!==null?W:void 0,Y=await this.runOwner($),H=(_)=>this.fileOwners.record(_,{owner:Y,name:V,mimeType:G,size:Z.size,createdAt:new Date().toISOString()}),B=await this.attachmentDestination(Z,$),z=h0(B,Q.get("destination")),D=await this.attachmentScope($,K,{body:J}),L=z!=="provider"&&!D;if(L){if(z==="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()`.');g0()}if(z==="provider"||!D){let _=await W6(this.agent.provider,Z);await H(_);let O={fileId:_,name:V,mimeType:G,size:Z.size,destination:"provider"};if(L)O.downgraded="no_scope";return O}let F=K$(),U=await this.attachmentStorage.put({name:H$(F,V),body:Z,contentType:G}),P=z==="both"?await W6(this.agent.provider,Z):void 0;if(P)await H(P);let q={id:F,scopeKey:D.key,fileId:P,objectName:U,name:V,mimeType:G,size:Z.size,createdAt:new Date().toISOString(),destination:z};return await this.attachments.put(D,q),{fileId:P,attachmentId:F,name:V,mimeType:G,size:Z.size,destination:z}}async foreignFile($,Q){let Z=new Set($.map((V)=>V.fileId).filter((V)=>typeof V==="string"));for(let V of Z){let G=await this.fileOwners.get(V);if(G?G.owner!==null&&G.owner!==Q:this.requireKnownFiles)return v0()}return null}onMessage($,Q){}onToolCall($,Q){}onAwaitingInput($,Q){}redactError($,Q,Z){return F9($,Q)}onError($,Q){}onStreamComplete($,Q){}reportHookFailure($){console.error("[gemi/ai] agent controller hook failed",$)}async dispatchEvent($,Q){switch($.type){case"tool-call":if(!$.part.partial&&!$.resent)await this.onToolCall({toolCallId:$.part.toolCallId,name:String($.part.name),input:$.part.input},Q);return;case"awaiting-input":await this.onAwaitingInput($.pending,Q);return;case"error":await this.onError(N6($.error),Q);return;default:return}}async readThread($){let Q=await this.store.loadThread($);return Q?(await this.settleThread($,Q,{write:!1})).messages:null}isRunLive($,Q){return this.liveRuns.get($)!==null}async settleThread($,Q,{write:Z}){let V=(K)=>this.isRunLive(K,$),G=await eZ(Q,V),J=G.messages,W=[],X=new Map(G.settled.map((K)=>[K.id,K]));if(m0(J)||Z)try{let K=await Q6(J,{threadId:$,store:y.store,isRunLive:V,outputSchemaFor:(Y)=>this.toolOutputSchema(Y),scan:this.jobsBlockMax()});J=K.messages,W=K.jobs;for(let Y of K.settled)X.set(Y.id,Y);if(Z&&K.orphans.length>0){await Z6(y.store,K.orphans,(H)=>this.reportHookFailure(H));let Y=new Set(K.orphans.map((H)=>H.id));W=W.map((H)=>Y.has(H.id)?{...H,orphaned:!0}:H)}}catch(K){this.reportHookFailure(K)}if(Z&&X.size>0)try{await this.store.appendMessages($,[...X.values()])}catch(K){this.reportHookFailure(K)}return{messages:J,jobs:W}}jobsBlockMax(){let $=this.agent.jobs?.contextBlock;if($===!1)return 0;return $?.max??m9}jobsBlock($){return LZ($,this.jobsBlockMax())}toolOutputSchema($){let Q=(Z)=>{for(let V of Z){let G=V;if(Array.isArray(G.tools)){let J=Q(G.tools);if(J)return J}else if(G.name===$)return G.outputSchema}return};return Q(this.agent.tools??[])}follow($,Q){(async()=>{try{for await(let Z of $.frames())Q.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun($,Q,Z,V=null,G={id:null,notified:Promise.resolve()}){let J=Promise.resolve(),W=(async()=>{let K;try{K=await $.result()}catch(H){V?.close(),await V?.settled(),J=G.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},Q)));return}let Y=K.messages;if(V?.close(Y),await V?.settled(),Q.threadId&&Y.length>0)try{await this.store.appendMessages(Q.threadId,Y)}catch(H){this.reportHookFailure(H)}J=this.notifyRun(K,Y,Q,G)})(),X=W.then(()=>c0(Promise.all([J,Z]).then(()=>{}),this.hookHoldMs));return{stored:W,hooks:X}}async notifyRun($,Q,Z,V){await V.notified;for(let G of Q){if(G.id===V.id)continue;await this.safely(()=>this.onMessage(G,Z))}await this.safely(()=>this.onStreamComplete($,Z))}async safely($){try{await $()}catch(Q){this.reportHookFailure(Q)}}}var BQ=["turn","clientRunId","threadId","messages","regenerate"],R0=["text","files","toolResults"];function _6($,Q=R6($)?BQ:[...BQ,...R0]){let Z={};for(let[V,G]of Object.entries($)){if(Q.includes(V))continue;Object.defineProperty(Z,V,{value:G,writable:!0,enumerable:!0,configurable:!0})}return Z}function S0($){if($===null)return{};let Q;if(typeof $==="string")try{Q=JSON.parse($)}catch{throw new DQ("The upload's `body` field is not valid JSON.")}if(Q===null||typeof Q!=="object"||Array.isArray(Q))throw new DQ("The upload's `body` field must be a JSON object.");return _6(Q,BQ)}class DQ extends J${constructor($){super($);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:$}}},view:{}}}}async function W6($,Q){try{return await $.upload(Q)}catch(Z){if(Z instanceof h&&j0.has(Z.status))throw new M6(I(Z).message);throw Z}}var j0=new Set([400,413,415,422]);class q6 extends J${constructor($,Q){super(Q);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}function A0($,Q,Z,V){if(!$)return null;let{maxBytes:G,accept:J}=$;if(typeof G==="number"&&Q.size>G)return{code:"file_too_large",message:`${JSON.stringify(Z)} is ${Y6(Q.size)}; the limit is ${Y6(G)}.`};if(J&&J.length>0&&!J.some((W)=>T0(W,Z,V)))return{code:"unsupported_file_type",message:`${JSON.stringify(Z)} is not a type this chat accepts. Accepted: ${J.join(", ")}.`};return null}function T0($,Q,Z){let V=$.trim().toLowerCase();if(!V)return!1;if(V.startsWith("."))return Q.toLowerCase().endsWith(V);let G=Z.toLowerCase().split(";")[0].trim();if(V.endsWith("/*"))return G.startsWith(V.slice(0,-1));return G===V}function Y6($){if($<1024)return`${$} B`;let Q=["KB","MB","GB"],Z=$/1024,V=0;while(Z>=1024&&V<Q.length-1)Z/=1024,V++;return`${Math.round(Z*10)/10} ${Q[V]}`}class M6 extends J${constructor($){super($);this.name="RejectedUploadError";let Q=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test($)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}async function zQ($,Q){let Z=$?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!E0(Z.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let V=Number(Z.headers.get("Content-Length"));if(Number.isFinite(V)&&V>Q)return X6(Q);let G;try{let W=await k0(Z,Q);if(W===null)return X6(Q);G=W}catch{return{body:{},error:"The request body could not be read."}}if(!G.trim())return{body:{}};let J;try{J=JSON.parse(G)}catch{return{body:{},error:"The request body is not valid JSON."}}if(J===null||typeof J!=="object"||Array.isArray(J))return{body:{},error:"The request body must be a JSON object."};return{body:J}}function E0($){return L6($)==="application/json"}async function k0($,Q){if(!Number.isFinite(Q)||!$.body)return await $.text();let Z=$.body.getReader(),V=[],G=0;for(;;){let{done:X,value:K}=await Z.read();if(X)break;if(G+=K.byteLength,G>Q)return await Z.cancel().catch(C6),null;V.push(K)}let J=new Uint8Array(G),W=0;for(let X of V)J.set(X,W),W+=X.byteLength;return new TextDecoder().decode(J)}function X6($){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${$} bytes).`}}function FQ($,Q,Z){return f($,{...W$(F6($),Z,$),code:Q})}function V$($){if($.status===413)return FQ(413,$.code??"body_too_large",$.error??"");return f($.status??400,{code:$.code??"invalid_request",message:$.error})}function R6($){return Boolean($.turn)&&typeof $.turn==="object"}function x0($){let Q=R6($)?$.turn:$,Z={};if(typeof Q.text==="string")Z.text=Q.text;if(Array.isArray(Q.files)){let V=I0(Q.files);if(typeof V==="string")return{error:V};Z.files=V}if(Array.isArray(Q.toolResults))Z.toolResults=Q.toolResults;if(Object.keys(Z).length===0)return{};if(Q===$.turn&&Q.localId!==void 0&&Q.localId!==null&&Q.localId!==""){let{localId:V}=Q;if(typeof V!=="string")return{error:"turn.localId must be a string."};if(V.length>K6)return{error:`turn.localId is longer than ${K6} characters.`};Z.localId=V}return{turn:Z}}var K6=200;function I0($){let Q=[];for(let[Z,V]of $.entries()){let G=`turn.files[${Z}]`;if(!V||typeof V!=="object"||Array.isArray(V))return`${G} must be an object.`;let J={};for(let H of["fileId","attachmentId","name","mimeType"]){let B=V[H];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${G}.${H} must be a string.`;J[H]=B}let{fileId:W,attachmentId:X,name:K,mimeType:Y}=J;if(W?.startsWith(v))return`${G}.fileId holds a gemi attachment id (${W}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(X!==void 0&&!X.startsWith(v))return`${G}.attachmentId is not a gemi attachment id: it must start with "${v}".`;if(!W&&!X)return`${G} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;Q.push({...W?{fileId:W}:{},...X?{attachmentId:X}:{},...K!==void 0?{name:K}:{},...Y!==void 0?{mimeType:Y}:{}})}return Q}function w0($,Q){if(typeof Q.from==="number"&&Number.isFinite(Q.from))return Math.max(0,Math.floor(Q.from));if(typeof Q.cursor==="number"&&Number.isFinite(Q.cursor)){let V=Math.floor(Q.cursor);if(V>=0)return V+1;return}let Z=$?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let V=Number.parseInt(Z,10);if(Number.isFinite(V))return Math.max(0,V+1)}return}function b0($,Q){let Z=$?.search?.get(Q);return typeof Z==="string"?Z:void 0}function f0($){let Q=m($);for(let Z=$.length-1;Z>=0;Z--){let V=$[Z];if(V.role!=="user"||Q.has(V.id))continue;let G="",J=[];for(let W of V.content){if(W.type==="text")G+=W.text;if(W.type==="file")J.push({...W.fileId?{fileId:W.fileId}:{},...W.attachmentId?{attachmentId:W.attachmentId}:{},...W.name?{name:W.name}:{},...W.mimeType?{mimeType:W.mimeType}:{}})}if(!G&&J.length===0)continue;return{index:Z,turn:{...G?{text:G}:{},...J.length>0?{files:J}:{}}}}return null}function H6(){return f(409,{code:"stopped",message:"The turn was stopped before it started."})}function G$(){return f(403,W$("permission","This run belongs to someone else.",403))}function v0(){return f(403,W$("permission","A file in this turn was uploaded by someone else.",403))}function y0($){if(!Array.isArray($))return[];let Q=[];for(let Z of $){let V=Z?.content;if(!Array.isArray(V))continue;for(let G of V)if(G&&typeof G==="object"&&typeof G.fileId==="string")Q.push({fileId:G.fileId})}return Q}function f($,Q){return new Response(JSON.stringify({error:Q}),{status:$,headers:{"Content-Type":"application/json"}})}function h0($,Q){if(typeof Q!=="string"||Q.length===0)return $;if(Q!=="both"&&Q!=="provider"&&Q!=="storage")throw Error(`Unknown attachment destination "${Q}". Expected "both", "provider" or "storage".`);if(Q===$||$==="both"&&Q==="storage")return Q;if($==="both"&&Q==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${Q}" destination, but the server's policy for it is "${$}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var z6=!1;function g0(){if(z6)return;z6=!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 u0=2147483647;function c0($,Q){let Z=$.then(()=>{},()=>{});if(!(Q<=u0))return Z;let V,G=new Promise((J)=>{V=setTimeout(J,Q)});return Promise.race([Z,G]).finally(()=>clearTimeout(V))}var B6=!1;function p0($){if(B6||Bun.env.NODE_ENV!=="production")return;if(!($ instanceof LQ))return;B6=!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 m0($){return $.some((Q)=>Q.content.some((Z)=>Z.type==="tool-result"&&Z.status==="running"))}export{r as windowMessages,L9 as turnStarts,N8 as toAgentTools,W9 as supportsStrict,y6 as splitTurns,n6 as settleSummaries,v9 as s,F9 as redactError,EQ as messageSize,ZQ as liveRuns,h9 as keepSummary,m as injectedMessageIds,Y$ as generate,V0 as evalChain,C$ as defaultSummaryStore,C9 as defaultNonceStore,VQ as defaultFileOwners,t as defaultAttachmentStore,XQ as defaultAgentStore,e as ToolNamespace,j as ToolError,S$ as Skill,p as ScopedAttachments,N9 as SKILLS_NAMESPACE,YQ as RedisReceiptStore,P6 as RedisNonceStore,d as PendingEscalation,a$ as OpenAIProvider,h$ as OpenAIImageProvider,N$ as MemorySummaryStore,WQ as MemoryReceiptStore,LQ as MemoryNonceStore,r9 as MemoryLiveRuns,e9 as MemoryFileOwners,a9 as MemoryCircuitStore,k9 as MemoryAttachmentStore,$$ as MemoryAgentStore,B9 as MemoryAgentJobStore,q9 as LiveRunNotFoundError,D9 as JobsRequireThreadError,b9 as JobHandle,l0 as JSONSchemaError,g as InvalidAttachmentScopeError,o9 as ImageRequestError,s9 as ImageProvider,f$ as ImageModel,G9 as FrameCursorEvictedError,_9 as FallbackProvider,w$ as DatabaseAgentJobStore,fQ as DEFAULT_MAX_SUMMARY_TOKENS,T$ as DEFAULT_MAX_RUN_DURATION_MS,D$ as DEFAULT_JOB_DEADLINE_MS,m9 as DEFAULT_JOBS_CONTEXT_MAX,kQ as DEFAULT_CONTEXT_WINDOW_STEP,xQ as DEFAULT_CONTEXT_WINDOW_NOTE,vQ as DEFAULT_COMPACT_TRIGGER_TOKENS,yQ as DEFAULT_COMPACT_INSTRUCTIONS,hQ as COMPACT_SUMMARY_HEADER,r$ as AzureOpenAIProvider,g$ as AzureOpenAIImageProvider,z9 as AttachmentNotFoundError,i as AgentTool,H9 as AgentRunError,V9 as AgentProvider,y as AgentJobs,k$ as AgentJobDeadlineSweep,F$ as AgentJob,UQ as AgentController,E$ as Agent};
86
+ `)||void 0,_=await this.context(J,{body:Y}),O=await this.attachmentsFor(J,Z,{body:Y});if(H?.cancelled)return S$();let M=Z?new WQ(this.store,Z,U,(S)=>this.reportHookFailure(S)):null,T=`run_${crypto.randomUUID()}`,k={req:J,runId:T,threadId:Z},x={id:null,notified:Promise.resolve()},E=this.agent.stream({runId:T,messages:U,turn:G,threadId:Z,...M?{onMessage:(S)=>M.finish(S)}:{},onTurn:(S)=>{if(x.id!==null)return;x.id=S.id;let f=M?M.settled():Promise.resolve();x.notified=f.then(()=>this.safely(()=>this.onMessage(S,k)))},instructions:P,context:_,attachments:O,body:Y,redactError:(S,f)=>this.redactError(S,f,k),nonces:this.nonces,receipts:this.receipts,subject:X,...Z?{jobs:{owner:X}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&h$(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==UQ.prototype.prepareStep?{prepareStep:(S)=>this.prepareStep(S,k)}:{}}),C=this.liveRuns.register(E,{threadId:Z,owner:X,clientRunId:K,onEvent:(S)=>this.dispatchEvent(S,k),onInternalError:(S)=>this.reportHookFailure(S),maxRunDurationMs:this.agent.maxRunDurationMs});if(B=E,M)this.follow(E,M);let{stored:A,hooks:L}=this.persistRun(E,k,C,M,x);if(U$.set(E,A),t.has(J))t.set(J,{run:E,hooks:L});return J.ctx?.()?.waitUntil(L),E.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:Y});let U=await this.foreignFile([...G?.files??[],...Z?[]:z9($.messages)],X);if(U)return U;if(H?.cancelled)return S$();let N=await this.runLimitKey(J,{owner:X,threadId:Z}),P=N===null?PJ:r3(this.liveRuns).take(N,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return YQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return Z?await this.withThread(Z,X,z):await z()}finally{let _=B;if(_)_.result().then(P,P);else P()}}finally{if(H&&zJ.get(K)===H)zJ.delete(K)}}async withThread(J,Q,$){let Z=DJ.get(J)??Promise.resolve(),W,G=new Promise((K)=>{W=K}),V=Z.then(()=>G);DJ.set(J,V),await Z;try{let K=await this.liveRuns.find({threadId:J});if(K&&this.liveRuns.isRunning(K.runId)&&!this.liveRuns.mayAccess(K.runId,Q))return UJ();let Y=K?this.liveRuns.get(K.runId):null;if(Y)Y.stop({reason:"superseded by a later turn on this thread"}),await U$.get(Y);return await $()}finally{if(W(),DJ.get(J)===V)DJ.delete(J)}}async attach(J=new d){let Q=await GQ(J,F$);if(Q.error)return BJ(Q);let $=Q.body,Z=typeof $.threadId==="string"?$.threadId:Y9(J,"threadId");if(!Z)return j(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(J,{route:"attach",threadId:Z});let W=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(J)))return UJ();if(!W)return j(404,{code:"no_live_run",message:`No run in progress for thread ${Z} in this process.`});let G=typeof $.runId==="string"?$.runId:void 0,V=G&&G!==W.runId?void 0:X9(J,$);try{return E$(this.liveRuns.replay(W.runId,V))}catch(K){if(K instanceof l)return j(410,{code:K.code,message:K.message,oldestSeq:K.oldest});if(K instanceof a)return j(404,{code:K.code,message:K.message});throw K}}async stop(J=new d){let Q=await GQ(J,F$);if(Q.error)return BJ(Q);let $=Q.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof $.threadId==="string"?$.threadId:void 0});let Z=await this.runOwner(J),W=typeof $.runId==="string"?$.runId:void 0;if(!W&&typeof $.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId($.clientRunId)??void 0,!W){let V=zJ.get($.clientRunId);if(V){if(V.owner!==null&&V.owner!==Z)return UJ();return V.cancelled=!0,{stopped:!0}}}}if(!W&&typeof $.threadId==="string")W=(await this.liveRuns.find({threadId:$.threadId}))?.runId;let G=W?this.liveRuns.get(W):null;if(!G)return{stopped:!1};if(!this.liveRuns.mayAccess(G.runId,Z))return UJ();return G.stop({reason:typeof $.reason==="string"?$.reason:void 0}),{stopped:!0}}attachmentScope(J,Q,$){let Z=J.ctx()?.user,W=Z?.id??Z?.publicId;if(W!==void 0&&W!==null&&String(W)!=="")return{key:`user:${String(W)}`};if(Q)return{key:`thread:${Q}`};return null}attachmentLimits(J){return null}checkUpload(J,Q,$){}attachmentDestination(J,Q,$){return"both"}async attachmentsFor(J,Q,$={body:{}}){let Z=await this.attachmentScope(J,Q,$);if(!Z)return null;return new LJ(this.attachments,this.attachmentStorage,Z)}async upload(J=new d){let Q=await J.rawRequest.formData(),$=Q.get("file");if(!($ instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=$ instanceof File&&$.name?$.name:"upload",W=$.type||"application/octet-stream",G=J9(Q.get("body")),V=Q.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof V==="string"&&V.length>0?V:void 0,body:G});let K=$9(await this.attachmentLimits(J),$,Z,W);if(K)throw new XQ(K.code,K.message);let Y=typeof V==="string"&&V.length>0&&await this.store.loadThread(V)!==null?V:void 0,X=await this.runOwner(J),H=(T)=>this.fileOwners.record(T,{owner:X,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString()}),B={body:G,threadId:Y},D=await this.checkUpload({name:Z,size:$.size,mimeType:W},J,B);if(D)throw new XQ(D.code||"upload_refused",D.message);let z=await this.attachmentDestination($,J,B),F=B9(z,Q.get("destination")),U=await this.attachmentScope(J,Y,{body:G}),N=F!=="provider"&&!U;if(N){if(F==="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()`.');U9()}if(F==="provider"||!U){let T=await L$(this.agent.provider,$);await H(T);let k={fileId:T,name:Z,mimeType:W,size:$.size,destination:"provider"};if(N)k.downgraded="no_scope";return k}let P=b$(),_=await this.attachmentStorage.put({name:v$(P,Z),body:$,contentType:W}),O=F==="both"?await L$(this.agent.provider,$):void 0;if(O)await H(O);let M={id:P,scopeKey:U.key,fileId:O,objectName:_,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString(),destination:F};return await this.attachments.put(U,M),{fileId:O,attachmentId:P,name:Z,mimeType:W,size:$.size,destination:F}}async foreignFile(J,Q){let $=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of $){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==Q:this.requireKnownFiles)return D9()}return null}onMessage(J,Q){}onToolCall(J,Q){}onAwaitingInput(J,Q){}redactError(J,Q,$){return zQ(J,Q)}onError(J,Q){}onStreamComplete(J,Q){}reportHookFailure(J){console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,Q){switch(J.type){case"tool-call":if(!J.part.partial&&!J.resent)await this.onToolCall({toolCallId:J.part.toolCallId,name:String(J.part.name),input:J.part.input},Q);return;case"awaiting-input":await this.onAwaitingInput(J.pending,Q);return;case"error":await this.onError(x$(J.error),Q);return;default:return}}async readThread(J){let Q=await this.store.loadThread(J);return Q?(await this.settleThread(J,Q,{write:!1})).messages:null}isRunLive(J,Q){return this.liveRuns.get(J)!==null}async settleThread(J,Q,{write:$}){let Z=(Y)=>this.isRunLive(Y,J),W=await X$(Q,Z),G=W.messages,V=[],K=new Map(W.settled.map((Y)=>[Y.id,Y]));if(L9(G)||$)try{let Y=await z$(G,{threadId:J,store:w.store,isRunLive:Z,outputSchemaFor:(X)=>this.toolOutputSchema(X),scan:this.jobsBlockMax()});G=Y.messages,V=Y.jobs;for(let X of Y.settled)K.set(X.id,X);if($&&Y.orphans.length>0){await B$(w.store,Y.orphans,(H)=>this.reportHookFailure(H));let X=new Set(Y.orphans.map((H)=>H.id));V=V.map((H)=>X.has(H.id)?{...H,orphaned:!0}:H)}}catch(Y){this.reportHookFailure(Y)}if($&&K.size>0)try{await this.store.appendMessages(J,[...K.values()])}catch(Y){this.reportHookFailure(Y)}return{messages:G,jobs:V}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??r}jobsBlock(J){return NQ(J,this.jobsBlockMax())}toolOutputSchema(J){let Q=($)=>{for(let Z of $){let W=Z;if(Array.isArray(W.tools)){let G=Q(W.tools);if(G)return G}else if(W.name===J)return W.outputSchema}return};return Q(this.agent.tools??[])}follow(J,Q){(async()=>{try{for await(let $ of J.frames())Q.frame($)}catch($){this.reportHookFailure($)}})()}persistRun(J,Q,$,Z=null,W={id:null,notified:Promise.resolve()}){let G=Promise.resolve(),V=(async()=>{let Y;try{Y=await J.result()}catch(H){Z?.close(),await Z?.settled(),G=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},Q)));return}let X=Y.messages;if(Z?.close(X),await Z?.settled(),Q.threadId&&X.length>0)try{await this.store.appendMessages(Q.threadId,X)}catch(H){this.reportHookFailure(H)}G=this.notifyRun(Y,X,Q,W)})(),K=V.then(()=>F9(Promise.all([G,$]).then(()=>{}),this.hookHoldMs));return{stored:V,hooks:K}}async notifyRun(J,Q,$,Z){await Z.notified;for(let W of Q){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,$))}await this.safely(()=>this.onStreamComplete(J,$))}async safely(J){try{await J()}catch(Q){this.reportHookFailure(Q)}}}var VQ=["turn","clientRunId","threadId","messages","regenerate"],e3=["text","files","toolResults"];function g$(J,Q=c$(J)?VQ:[...VQ,...e3]){let $={};for(let[Z,W]of Object.entries(J)){if(Q.includes(Z))continue;Object.defineProperty($,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return $}function J9(J){if(J===null)return{};let Q;if(typeof J==="string")try{Q=JSON.parse(J)}catch{throw new KQ("The upload's `body` field is not valid JSON.")}if(Q===null||typeof Q!=="object"||Array.isArray(Q))throw new KQ("The upload's `body` field must be a JSON object.");return g$(Q,VQ)}class KQ extends FJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function L$(J,Q){try{return await J.upload(Q)}catch($){if($ instanceof h&&Q9.has($.status))throw new u$(R($).message);throw $}}var Q9=new Set([400,413,415,422]);class XQ extends FJ{constructor(J,Q){super(Q);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:Q}}},view:{}}}}function $9(J,Q,$,Z){if(!J)return null;let{maxBytes:W,accept:G}=J;if(typeof W==="number"&&Q.size>W)return{code:"file_too_large",message:`${JSON.stringify($)} is ${C$(Q.size)}; the limit is ${C$(W)}.`};if(G&&G.length>0&&!G.some((V)=>Z9(V,$,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify($)} is not a type this chat accepts. Accepted: ${G.join(", ")}.`};return null}function Z9(J,Q,$){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return Q.toLowerCase().endsWith(Z);let W=$.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function C$(J){if(J<1024)return`${J} B`;let Q=["KB","MB","GB"],$=J/1024,Z=0;while($>=1024&&Z<Q.length-1)$/=1024,Z++;return`${Math.round($*10)/10} ${Q[Z]}`}class u$ extends FJ{constructor(J){super(J);this.name="RejectedUploadError";let Q=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(J)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:Q,message:J}}},view:{}}}}async function GQ(J,Q){let $=J?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!W9($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number($.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>Q)return O$(Q);let W;try{let V=await G9($,Q);if(V===null)return O$(Q);W=V}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let G;try{G=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(G===null||typeof G!=="object"||Array.isArray(G))return{body:{},error:"The request body must be a JSON object."};return{body:G}}function W9(J){return j$(J)==="application/json"}async function G9(J,Q){if(!Number.isFinite(Q)||!J.body)return await J.text();let $=J.body.getReader(),Z=[],W=0;for(;;){let{done:K,value:Y}=await $.read();if(K)break;if(W+=Y.byteLength,W>Q)return await $.cancel().catch(PJ),null;Z.push(Y)}let G=new Uint8Array(W),V=0;for(let K of Z)G.set(K,V),V+=K.byteLength;return new TextDecoder().decode(G)}function O$(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function YQ(J,Q,$){return j(J,{...NJ(T$(J),$,J),code:Q})}function BJ(J){if(J.status===413)return YQ(413,J.code??"body_too_large",J.error??"");return j(J.status??400,{code:J.code??"invalid_request",message:J.error})}function c$(J){return Boolean(J.turn)&&typeof J.turn==="object"}function V9(J){let Q=c$(J)?J.turn:J,$={};if(typeof Q.text==="string")$.text=Q.text;if(Array.isArray(Q.files)){let Z=K9(Q.files);if(typeof Z==="string")return{error:Z};$.files=Z}if(Array.isArray(Q.toolResults))$.toolResults=Q.toolResults;if(Object.keys($).length===0)return{};if(Q===J.turn&&Q.localId!==void 0&&Q.localId!==null&&Q.localId!==""){let{localId:Z}=Q;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>_$)return{error:`turn.localId is longer than ${_$} characters.`};$.localId=Z}return{turn:$}}var _$=200;function K9(J){let Q=[];for(let[$,Z]of J.entries()){let W=`turn.files[${$}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let G={};for(let H of["fileId","attachmentId","name","mimeType"]){let B=Z[H];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${W}.${H} must be a string.`;G[H]=B}let{fileId:V,attachmentId:K,name:Y,mimeType:X}=G;if(V?.startsWith(b))return`${W}.fileId holds a gemi attachment id (${V}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(K!==void 0&&!K.startsWith(b))return`${W}.attachmentId is not a gemi attachment id: it must start with "${b}".`;if(!V&&!K)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;Q.push({...V?{fileId:V}:{},...K?{attachmentId:K}:{},...Y!==void 0?{name:Y}:{},...X!==void 0?{mimeType:X}:{}})}return Q}function X9(J,Q){if(typeof Q.from==="number"&&Number.isFinite(Q.from))return Math.max(0,Math.floor(Q.from));if(typeof Q.cursor==="number"&&Number.isFinite(Q.cursor)){let Z=Math.floor(Q.cursor);if(Z>=0)return Z+1;return}let $=J?.rawRequest?.headers?.get("Last-Event-ID");if($){let Z=Number.parseInt($,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function Y9(J,Q){let $=J?.search?.get(Q);return typeof $==="string"?$:void 0}function H9(J){let Q=BQ(J);for(let $=J.length-1;$>=0;$--){let Z=J[$];if(Z.role!=="user"||Q.has(Z.id))continue;let W="",G=[];for(let V of Z.content){if(V.type==="text")W+=V.text;if(V.type==="file")G.push({...V.fileId?{fileId:V.fileId}:{},...V.attachmentId?{attachmentId:V.attachmentId}:{},...V.name?{name:V.name}:{},...V.mimeType?{mimeType:V.mimeType}:{}})}if(!W&&G.length===0)continue;return{index:$,turn:{...W?{text:W}:{},...G.length>0?{files:G}:{}}}}return null}function S$(){return j(409,{code:"stopped",message:"The turn was stopped before it started."})}function UJ(){return j(403,NJ("permission","This run belongs to someone else.",403))}function D9(){return j(403,NJ("permission","A file in this turn was uploaded by someone else.",403))}function z9(J){if(!Array.isArray(J))return[];let Q=[];for(let $ of J){let Z=$?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")Q.push({fileId:W.fileId})}return Q}function j(J,Q){return new Response(JSON.stringify({error:Q}),{status:J,headers:{"Content-Type":"application/json"}})}function B9(J,Q){if(typeof Q!=="string"||Q.length===0)return J;if(Q!=="both"&&Q!=="provider"&&Q!=="storage")throw Error(`Unknown attachment destination "${Q}". Expected "both", "provider" or "storage".`);if(Q===J||J==="both"&&Q==="storage")return Q;if(J==="both"&&Q==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${Q}" destination, but the server's policy for it is "${J}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var M$=!1;function U9(){if(M$)return;M$=!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 P9=2147483647;function F9(J,Q){let $=J.then(()=>{},()=>{});if(!(Q<=P9))return $;let Z,W=new Promise((G)=>{Z=setTimeout(G,Q)});return Promise.race([$,W]).finally(()=>clearTimeout(Z))}var A$=!1;function N9(J){if(A$||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof HQ))return;A$=!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 L9(J){return J.some((Q)=>Q.content.some(($)=>$.type==="tool-result"&&$.status==="running"))}export{j9 as windowMessages,S9 as turnStarts,d$ as toAgentTools,_9 as supportsStrict,M9 as splitTurns,b9 as settleSummaries,O9 as s,zQ as redactError,A9 as messageSize,sJ as liveRuns,QQ as keepSummary,BQ as injectedMessageIds,c9 as generate,x3 as evalChain,I9 as defaultSummaryStore,DQ as defaultNonceStore,aJ as defaultFileOwners,CJ as defaultAttachmentStore,$Q as defaultAgentStore,jJ as ToolNamespace,TJ as ToolError,f9 as Skill,LJ as ScopedAttachments,h9 as SKILLS_NAMESPACE,JQ as RedisReceiptStore,q$ as RedisNonceStore,v9 as PendingEscalation,lJ as OpenAIProvider,xJ as OpenAIImageProvider,w9 as MemorySummaryStore,eJ as MemoryReceiptStore,HQ as MemoryNonceStore,XJ as MemoryLiveRuns,YJ as MemoryFileOwners,KJ as MemoryCircuitStore,f$ as MemoryAttachmentStore,HJ as MemoryAgentStore,MQ as MemoryAgentJobStore,a as LiveRunNotFoundError,RQ as JobsRequireThreadError,AQ as JobHandle,C9 as JSONSchemaError,I$ as InvalidAttachmentScopeError,WJ as ImageRequestError,GJ as ImageProvider,kJ as ImageModel,l as FrameCursorEvictedError,s as FallbackProvider,AJ as DatabaseAgentJobStore,k9 as DEFAULT_MAX_SUMMARY_TOKENS,y9 as DEFAULT_MAX_RUN_DURATION_MS,TQ as DEFAULT_JOB_DEADLINE_MS,r as DEFAULT_JOBS_CONTEXT_MAX,R9 as DEFAULT_CONTEXT_WINDOW_STEP,T9 as DEFAULT_CONTEXT_WINDOW_NOTE,E9 as DEFAULT_COMPACT_TRIGGER_TOKENS,q9 as DEFAULT_COMPACT_INSTRUCTIONS,x9 as COMPACT_SUMMARY_HEADER,dJ as AzureOpenAIProvider,wJ as AzureOpenAIImageProvider,w$ as AttachmentNotFoundError,OJ as AgentTurnError,QJ as AgentTool,g9 as AgentRunError,m as AgentProvider,w as AgentJobs,_J as AgentJobDeadlineSweep,jQ as AgentJob,UQ as AgentController,u9 as Agent};
104
87
 
105
- //# debugId=3518169BAF28C24564756E2164756E21
88
+ //# debugId=8C6BA69BA7D7181C64756E2164756E21