gemi 0.84.1 → 0.86.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 (280) hide show
  1. package/dist/ai/Agent.d.ts +41 -3
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +238 -0
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/AgentProvider.d.ts +15 -0
  6. package/dist/ai/AgentProvider.d.ts.map +1 -1
  7. package/dist/ai/client/index.d.ts +2 -2
  8. package/dist/ai/client/index.d.ts.map +1 -1
  9. package/dist/ai/client/index.js +138 -35
  10. package/dist/ai/client/index.js.map +1 -1
  11. package/dist/ai/client/reducer.d.ts +7 -1
  12. package/dist/ai/client/reducer.d.ts.map +1 -1
  13. package/dist/ai/generate.d.ts.map +1 -1
  14. package/dist/ai/index.d.ts +4 -2
  15. package/dist/ai/index.d.ts.map +1 -1
  16. package/dist/ai/index.js +12 -12
  17. package/dist/ai/index.js.map +19 -16
  18. package/dist/ai/providers/call.d.ts +4 -0
  19. package/dist/ai/providers/call.d.ts.map +1 -1
  20. package/dist/ai/providers/fileRejection.d.ts +84 -0
  21. package/dist/ai/providers/fileRejection.d.ts.map +1 -0
  22. package/dist/ai/providers/request.d.ts.map +1 -1
  23. package/dist/ai/redact.d.ts +70 -0
  24. package/dist/ai/redact.d.ts.map +1 -0
  25. package/dist/ai/signing.d.ts +33 -4
  26. package/dist/ai/signing.d.ts.map +1 -1
  27. package/dist/ai/store/Attachments.d.ts +5 -3
  28. package/dist/ai/store/Attachments.d.ts.map +1 -1
  29. package/dist/ai/store/FileOwners.d.ts +59 -0
  30. package/dist/ai/store/FileOwners.d.ts.map +1 -0
  31. package/dist/ai/store/LiveRuns.d.ts +25 -0
  32. package/dist/ai/store/LiveRuns.d.ts.map +1 -1
  33. package/dist/ai/store/MemoryAgentStore.d.ts +1 -0
  34. package/dist/ai/store/MemoryAgentStore.d.ts.map +1 -1
  35. package/dist/ai/store/Nonces.d.ts +109 -0
  36. package/dist/ai/store/Nonces.d.ts.map +1 -0
  37. package/dist/ai/store/index.d.ts +2 -0
  38. package/dist/ai/store/index.d.ts.map +1 -1
  39. package/dist/ai/types.d.ts +30 -1
  40. package/dist/ai/types.d.ts.map +1 -1
  41. package/dist/ai/useChat.d.ts +62 -3
  42. package/dist/ai/useChat.d.ts.map +1 -1
  43. package/dist/app/index.js +1 -1
  44. package/dist/bun/plugin.js +1 -1
  45. package/dist/bun/preload.js +1 -1
  46. package/dist/{chunk-82nn71zs.js → chunk-09sr33ff.js} +2 -2
  47. package/dist/{chunk-82nn71zs.js.map → chunk-09sr33ff.js.map} +1 -1
  48. package/dist/chunk-174jkg6d.js +7 -0
  49. package/dist/{chunk-302mkqeq.js.map → chunk-174jkg6d.js.map} +9 -8
  50. package/dist/{chunk-87x692j7.js → chunk-1b5s4w5f.js} +2 -2
  51. package/dist/{chunk-87x692j7.js.map → chunk-1b5s4w5f.js.map} +1 -1
  52. package/dist/{chunk-rmv1jp9p.js → chunk-1jcp8m8h.js} +2 -2
  53. package/dist/{chunk-rmv1jp9p.js.map → chunk-1jcp8m8h.js.map} +1 -1
  54. package/dist/{chunk-g6qe6wyb.js → chunk-1w5a11cd.js} +2 -2
  55. package/dist/{chunk-g6qe6wyb.js.map → chunk-1w5a11cd.js.map} +1 -1
  56. package/dist/chunk-1wby1sr2.js +5 -0
  57. package/dist/{chunk-e43drft2.js.map → chunk-1wby1sr2.js.map} +3 -3
  58. package/dist/{chunk-vmpzg4z5.js → chunk-1yq1e6sb.js} +3 -3
  59. package/dist/{chunk-vmpzg4z5.js.map → chunk-1yq1e6sb.js.map} +1 -1
  60. package/dist/chunk-1yzdxv2a.js +5 -0
  61. package/dist/{chunk-tmwsvf02.js.map → chunk-1yzdxv2a.js.map} +1 -1
  62. package/dist/chunk-2dzqrf0z.js +55 -0
  63. package/dist/{chunk-rp5j1mgk.js.map → chunk-2dzqrf0z.js.map} +3 -3
  64. package/dist/{chunk-ah9ajys0.js → chunk-2gdhcswa.js} +1 -1
  65. package/dist/{chunk-1evk2pma.js → chunk-2yw23zhn.js} +4 -4
  66. package/dist/{chunk-1evk2pma.js.map → chunk-2yw23zhn.js.map} +1 -1
  67. package/dist/{chunk-3z6wkvwj.js → chunk-4ysar3ev.js} +2 -2
  68. package/dist/{chunk-3z6wkvwj.js.map → chunk-4ysar3ev.js.map} +1 -1
  69. package/dist/{chunk-z409rk5j.js → chunk-4zj05vry.js} +2 -2
  70. package/dist/{chunk-z409rk5j.js.map → chunk-4zj05vry.js.map} +1 -1
  71. package/dist/{chunk-1cebv3h8.js → chunk-55x9kkdt.js} +2 -2
  72. package/dist/{chunk-1cebv3h8.js.map → chunk-55x9kkdt.js.map} +1 -1
  73. package/dist/{chunk-3zb2ycxj.js → chunk-7c33ngqs.js} +2 -2
  74. package/dist/{chunk-3zb2ycxj.js.map → chunk-7c33ngqs.js.map} +1 -1
  75. package/dist/{chunk-en3mtnsg.js → chunk-7n5775qx.js} +2 -2
  76. package/dist/{chunk-en3mtnsg.js.map → chunk-7n5775qx.js.map} +1 -1
  77. package/dist/{chunk-bn9pzgww.js → chunk-7nj2t2gm.js} +2 -2
  78. package/dist/{chunk-bn9pzgww.js.map → chunk-7nj2t2gm.js.map} +1 -1
  79. package/dist/{chunk-kfavcgv2.js → chunk-81k26w39.js} +2 -2
  80. package/dist/{chunk-kfavcgv2.js.map → chunk-81k26w39.js.map} +1 -1
  81. package/dist/{chunk-cg4k40zy.js → chunk-81v4c4b1.js} +2 -2
  82. package/dist/{chunk-cg4k40zy.js.map → chunk-81v4c4b1.js.map} +1 -1
  83. package/dist/{chunk-wh728wd6.js → chunk-8gexb1gt.js} +2 -2
  84. package/dist/{chunk-wh728wd6.js.map → chunk-8gexb1gt.js.map} +1 -1
  85. package/dist/{chunk-zfch4da5.js → chunk-9tsw1bmt.js} +2 -2
  86. package/dist/{chunk-8mmfpqgs.js.map → chunk-9tsw1bmt.js.map} +1 -1
  87. package/dist/{chunk-m0zba09s.js → chunk-9tv5j3b2.js} +3 -3
  88. package/dist/{chunk-m0zba09s.js.map → chunk-9tv5j3b2.js.map} +1 -1
  89. package/dist/{chunk-jg9eqd3r.js → chunk-c3gzpjba.js} +1 -1
  90. package/dist/{chunk-r5e4vpa1.js → chunk-cbycz5z3.js} +2 -2
  91. package/dist/{chunk-r5e4vpa1.js.map → chunk-cbycz5z3.js.map} +1 -1
  92. package/dist/{chunk-cfvq30n4.js → chunk-cfykfnqx.js} +2 -2
  93. package/dist/{chunk-cfvq30n4.js.map → chunk-cfykfnqx.js.map} +1 -1
  94. package/dist/{chunk-eysexnqb.js → chunk-ct7wxm98.js} +2 -2
  95. package/dist/{chunk-eysexnqb.js.map → chunk-ct7wxm98.js.map} +1 -1
  96. package/dist/{chunk-v27a4se1.js → chunk-d3jkypc7.js} +3 -3
  97. package/dist/{chunk-v27a4se1.js.map → chunk-d3jkypc7.js.map} +1 -1
  98. package/dist/{chunk-vfrrzr10.js → chunk-dadygfkf.js} +2 -2
  99. package/dist/{chunk-vfrrzr10.js.map → chunk-dadygfkf.js.map} +1 -1
  100. package/dist/{chunk-m4xw99vm.js → chunk-dwqh79e5.js} +2 -2
  101. package/dist/{chunk-m4xw99vm.js.map → chunk-dwqh79e5.js.map} +1 -1
  102. package/dist/chunk-eptv0nvv.js +24 -0
  103. package/dist/chunk-eptv0nvv.js.map +17 -0
  104. package/dist/{chunk-ng8pp9k2.js → chunk-fbwe0agk.js} +2 -2
  105. package/dist/{chunk-ng8pp9k2.js.map → chunk-fbwe0agk.js.map} +1 -1
  106. package/dist/{chunk-495qwteq.js → chunk-fc2je244.js} +3 -3
  107. package/dist/{chunk-495qwteq.js.map → chunk-fc2je244.js.map} +1 -1
  108. package/dist/{chunk-gr61ymse.js → chunk-gx0x772p.js} +2 -2
  109. package/dist/{chunk-gr61ymse.js.map → chunk-gx0x772p.js.map} +1 -1
  110. package/dist/{chunk-tdnfhe7x.js → chunk-ha705bcz.js} +3 -3
  111. package/dist/{chunk-tdnfhe7x.js.map → chunk-ha705bcz.js.map} +1 -1
  112. package/dist/chunk-jhe0t7yj.js +5 -0
  113. package/dist/chunk-jhe0t7yj.js.map +11 -0
  114. package/dist/{chunk-d0qwdeza.js → chunk-k5j65f2c.js} +2 -2
  115. package/dist/{chunk-d0qwdeza.js.map → chunk-k5j65f2c.js.map} +1 -1
  116. package/dist/{chunk-pt59xjfc.js → chunk-kmsrzbx1.js} +2 -2
  117. package/dist/{chunk-pt59xjfc.js.map → chunk-kmsrzbx1.js.map} +1 -1
  118. package/dist/{chunk-v1nm4tcq.js → chunk-m7y8d3k7.js} +2 -2
  119. package/dist/{chunk-v1nm4tcq.js.map → chunk-m7y8d3k7.js.map} +1 -1
  120. package/dist/{chunk-k2qh3hvd.js → chunk-mk8m3ffx.js} +2 -2
  121. package/dist/{chunk-k2qh3hvd.js.map → chunk-mk8m3ffx.js.map} +1 -1
  122. package/dist/{chunk-z7442w3q.js → chunk-mszy6cfw.js} +2 -2
  123. package/dist/{chunk-z7442w3q.js.map → chunk-mszy6cfw.js.map} +1 -1
  124. package/dist/{chunk-kb3xk9r8.js → chunk-ndat0nf0.js} +2 -2
  125. package/dist/{chunk-kb3xk9r8.js.map → chunk-ndat0nf0.js.map} +1 -1
  126. package/dist/{chunk-j9wqzemf.js → chunk-p0m3qgs5.js} +2 -2
  127. package/dist/{chunk-j9wqzemf.js.map → chunk-p0m3qgs5.js.map} +1 -1
  128. package/dist/{chunk-8mmfpqgs.js → chunk-p7r3ecpk.js} +2 -2
  129. package/dist/{chunk-zfch4da5.js.map → chunk-p7r3ecpk.js.map} +1 -1
  130. package/dist/{chunk-zp971jp2.js → chunk-pmmrhak1.js} +3 -3
  131. package/dist/{chunk-zp971jp2.js.map → chunk-pmmrhak1.js.map} +1 -1
  132. package/dist/{chunk-0agfx93f.js → chunk-ptkt4h2j.js} +2 -2
  133. package/dist/{chunk-0agfx93f.js.map → chunk-ptkt4h2j.js.map} +1 -1
  134. package/dist/{chunk-nvj1z2rs.js → chunk-pzwyg474.js} +2 -2
  135. package/dist/{chunk-nvj1z2rs.js.map → chunk-pzwyg474.js.map} +1 -1
  136. package/dist/{chunk-73dk6k4p.js → chunk-qje4kdff.js} +3 -3
  137. package/dist/{chunk-73dk6k4p.js.map → chunk-qje4kdff.js.map} +1 -1
  138. package/dist/{chunk-yk8s5egf.js → chunk-rdnm6rem.js} +2 -2
  139. package/dist/{chunk-yk8s5egf.js.map → chunk-rdnm6rem.js.map} +1 -1
  140. package/dist/{chunk-enf9mdac.js → chunk-s046a984.js} +2 -2
  141. package/dist/{chunk-enf9mdac.js.map → chunk-s046a984.js.map} +1 -1
  142. package/dist/{chunk-1s914cdj.js → chunk-saqfc6vp.js} +3 -3
  143. package/dist/{chunk-1s914cdj.js.map → chunk-saqfc6vp.js.map} +1 -1
  144. package/dist/{chunk-pgpqsgzx.js → chunk-sejnmn1q.js} +1 -1
  145. package/dist/{chunk-xhha1gb3.js → chunk-sjckrbr2.js} +2 -2
  146. package/dist/{chunk-xhha1gb3.js.map → chunk-sjckrbr2.js.map} +1 -1
  147. package/dist/{chunk-r8nhndzb.js → chunk-swhyp0yw.js} +2 -2
  148. package/dist/{chunk-r8nhndzb.js.map → chunk-swhyp0yw.js.map} +1 -1
  149. package/dist/{chunk-wkdzz0rx.js → chunk-trdwxm5x.js} +3 -3
  150. package/dist/{chunk-wkdzz0rx.js.map → chunk-trdwxm5x.js.map} +1 -1
  151. package/dist/{chunk-aztkrzvf.js → chunk-v2hvnxsf.js} +2 -2
  152. package/dist/{chunk-aztkrzvf.js.map → chunk-v2hvnxsf.js.map} +1 -1
  153. package/dist/{chunk-57ryyhh3.js → chunk-v4ngf77f.js} +2 -2
  154. package/dist/{chunk-57ryyhh3.js.map → chunk-v4ngf77f.js.map} +1 -1
  155. package/dist/{chunk-159hyeng.js → chunk-v8nf45gt.js} +2 -2
  156. package/dist/{chunk-159hyeng.js.map → chunk-v8nf45gt.js.map} +1 -1
  157. package/dist/{chunk-ys4fejmx.js → chunk-vwp1g8wh.js} +2 -2
  158. package/dist/{chunk-ys4fejmx.js.map → chunk-vwp1g8wh.js.map} +1 -1
  159. package/dist/chunk-w312e9nx.js +5 -0
  160. package/dist/{chunk-ash9e6fn.js.map → chunk-w312e9nx.js.map} +4 -3
  161. package/dist/{chunk-wwdaswxh.js → chunk-wwzg4dmy.js} +3 -3
  162. package/dist/{chunk-wwdaswxh.js.map → chunk-wwzg4dmy.js.map} +1 -1
  163. package/dist/{chunk-wsx3j5ws.js → chunk-xckeyg3v.js} +2 -2
  164. package/dist/{chunk-wsx3j5ws.js.map → chunk-xckeyg3v.js.map} +1 -1
  165. package/dist/chunk-xx2zg6sk.js +17 -0
  166. package/dist/{chunk-49akdtfe.js.map → chunk-xx2zg6sk.js.map} +11 -12
  167. package/dist/{chunk-rqh2wdhb.js → chunk-y7qnx8vm.js} +2 -2
  168. package/dist/{chunk-rqh2wdhb.js.map → chunk-y7qnx8vm.js.map} +1 -1
  169. package/dist/{chunk-rv7da58g.js → chunk-z4k18gnp.js} +2 -2
  170. package/dist/{chunk-rv7da58g.js.map → chunk-z4k18gnp.js.map} +1 -1
  171. package/dist/{chunk-w099t7zj.js → chunk-zf4r4kat.js} +2 -2
  172. package/dist/{chunk-w099t7zj.js.map → chunk-zf4r4kat.js.map} +1 -1
  173. package/dist/{chunk-dvpxkzms.js → chunk-zs90w6ke.js} +2 -2
  174. package/dist/{chunk-dvpxkzms.js.map → chunk-zs90w6ke.js.map} +1 -1
  175. package/dist/chunks/{ThemeProvider-Dn3UREDn.js → ThemeProvider-D1kDfCwY.js} +59 -2
  176. package/dist/chunks/ThemeProvider-D1kDfCwY.js.map +1 -0
  177. package/dist/client/Link.d.ts.map +1 -1
  178. package/dist/client/MutationError.d.ts +60 -50
  179. package/dist/client/MutationError.d.ts.map +1 -1
  180. package/dist/client/ProgressManager.d.ts +1 -1
  181. package/dist/client/QueryResource.d.ts +20 -0
  182. package/dist/client/QueryResource.d.ts.map +1 -1
  183. package/dist/client/auth/useForgotPassword.d.ts +2 -1
  184. package/dist/client/auth/useForgotPassword.d.ts.map +1 -1
  185. package/dist/client/auth/useResetPassword.d.ts +2 -1
  186. package/dist/client/auth/useResetPassword.d.ts.map +1 -1
  187. package/dist/client/auth/useSignIn.d.ts +11 -1
  188. package/dist/client/auth/useSignIn.d.ts.map +1 -1
  189. package/dist/client/auth/useSignOut.d.ts +2 -1
  190. package/dist/client/auth/useSignOut.d.ts.map +1 -1
  191. package/dist/client/auth/useSignUp.d.ts +2 -1
  192. package/dist/client/auth/useSignUp.d.ts.map +1 -1
  193. package/dist/client/index.d.ts +3 -1
  194. package/dist/client/index.d.ts.map +1 -1
  195. package/dist/client/index.js +169 -65
  196. package/dist/client/index.js.map +1 -1
  197. package/dist/client/useMutation.d.ts +33 -6
  198. package/dist/client/useMutation.d.ts.map +1 -1
  199. package/dist/client/useQuery.d.ts.map +1 -1
  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/Email.d.ts.map +1 -1
  208. package/dist/email/debugEmail.d.ts +40 -0
  209. package/dist/email/debugEmail.d.ts.map +1 -0
  210. package/dist/email/index.js +4 -3
  211. package/dist/email/index.js.map +6 -5
  212. package/dist/facades/index.js +2 -2
  213. package/dist/facades/index.js.map +1 -1
  214. package/dist/foundation/index.js +2 -2
  215. package/dist/foundation/index.js.map +1 -1
  216. package/dist/http/ApiRouter.d.ts +12 -0
  217. package/dist/http/ApiRouter.d.ts.map +1 -1
  218. package/dist/http/CSRFMiddleware.d.ts +1 -1
  219. package/dist/http/CSRFMiddleware.d.ts.map +1 -1
  220. package/dist/http/Error.d.ts +50 -0
  221. package/dist/http/Error.d.ts.map +1 -1
  222. package/dist/http/HttpRequest.d.ts +26 -0
  223. package/dist/http/HttpRequest.d.ts.map +1 -1
  224. package/dist/http/RateLimitMiddleware.d.ts +6 -3
  225. package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
  226. package/dist/http/Router.d.ts.map +1 -1
  227. package/dist/http/errors.d.ts.map +1 -1
  228. package/dist/http/index.d.ts +2 -1
  229. package/dist/http/index.d.ts.map +1 -1
  230. package/dist/http/index.js +2 -2
  231. package/dist/http/index.js.map +1 -1
  232. package/dist/http/mediaType.d.ts +16 -0
  233. package/dist/http/mediaType.d.ts.map +1 -0
  234. package/dist/http/refusal.d.ts +52 -0
  235. package/dist/http/refusal.d.ts.map +1 -0
  236. package/dist/i18n/dictionaryRuntime.js +2 -2
  237. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  238. package/dist/i18n/index.js +2 -2
  239. package/dist/i18n/index.js.map +2 -2
  240. package/dist/kernel/index.js +2 -2
  241. package/dist/kernel/index.js.map +2 -2
  242. package/dist/orm/index.js +2 -2
  243. package/dist/orm/index.js.map +1 -1
  244. package/dist/server/devFetch.d.ts.map +1 -1
  245. package/dist/server/forwardedFor.d.ts +42 -0
  246. package/dist/server/forwardedFor.d.ts.map +1 -0
  247. package/dist/server/httpProd.d.ts.map +1 -1
  248. package/dist/server/index.js +2 -2
  249. package/dist/server/index.js.map +1 -1
  250. package/dist/server/staticFile.d.ts +33 -0
  251. package/dist/server/staticFile.d.ts.map +1 -0
  252. package/dist/server/unhandledError.d.ts.map +1 -1
  253. package/dist/services/index.js +2 -2
  254. package/dist/services/index.js.map +2 -2
  255. package/dist/services/mcp/McpRegistry.d.ts +2 -1
  256. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  257. package/dist/services/mcp/toAgentTools.d.ts +1 -1
  258. package/dist/services/mcp/toAgentTools.d.ts.map +1 -1
  259. package/dist/services/queue/work.js +2 -2
  260. package/dist/services/queue/work.js.map +1 -1
  261. package/dist/services/router/notFound.d.ts.map +1 -1
  262. package/dist/services/router/policyDenied.d.ts.map +1 -1
  263. package/dist/services/router/serverQueryFetcher.d.ts.map +1 -1
  264. package/dist/support/index.js +2 -2
  265. package/dist/support/index.js.map +1 -1
  266. package/dist/testing/index.js +1 -1
  267. package/package.json +1 -1
  268. package/skills/gemi-react-best-practices/rules/controller-throw-framework-errors.md +5 -0
  269. package/dist/chunk-302mkqeq.js +0 -7
  270. package/dist/chunk-49akdtfe.js +0 -17
  271. package/dist/chunk-ash9e6fn.js +0 -5
  272. package/dist/chunk-e43drft2.js +0 -5
  273. package/dist/chunk-j5xcfeqx.js +0 -24
  274. package/dist/chunk-j5xcfeqx.js.map +0 -16
  275. package/dist/chunk-rp5j1mgk.js +0 -55
  276. package/dist/chunk-tmwsvf02.js +0 -5
  277. package/dist/chunks/ThemeProvider-Dn3UREDn.js.map +0 -1
  278. /package/dist/{chunk-ah9ajys0.js.map → chunk-2gdhcswa.js.map} +0 -0
  279. /package/dist/{chunk-jg9eqd3r.js.map → chunk-c3gzpjba.js.map} +0 -0
  280. /package/dist/{chunk-pgpqsgzx.js.map → chunk-sejnmn1q.js.map} +0 -0
package/dist/ai/index.js CHANGED
@@ -1,20 +1,20 @@
1
1
  // @bun
2
- import{Db as e3,Eb as p}from"../chunk-ash9e6fn.js";import{Fe as P$,Ve as K9,Ye as r,kf as _$,mf as JQ}from"../chunk-302mkqeq.js";import{pf as zQ}from"../chunk-rmv1jp9p.js";import"../chunk-v27a4se1.js";import"../chunk-wh728wd6.js";import"../chunk-r8nhndzb.js";import"../chunk-r5e4vpa1.js";import"../chunk-zfch4da5.js";class h extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${R$($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class a extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function R$(Q){let $=B9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function B9(Q){if(!Q||typeof Q!=="object")return null;let $=Q,G=$.error&&typeof $.error==="object"?$.error:Q;if(typeof G.message!=="string"&&typeof G.code!=="string"&&typeof G.type!=="string")return null;let J=G.innererror?.code??G.code;return{message:G.message,type:G.type,code:J,param:G.param}}function M(Q){if(!Q||typeof Q!=="object")return{};let{status:$,requestId:Z}=Q;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function P(Q){if(Q instanceof a)return{code:"provider_error",message:Q.message,retryable:!0};if(E$(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof h)return k$(Q.status,B9(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function k$(Q,$,Z){let G=$?.message??Z,J=($?.code??"").toLowerCase(),Y=($?.type??"").toLowerCase(),W=`${J} ${Y} ${G}`.toLowerCase();if(Q===429){let K=J==="insufficient_quota"||W.includes("quota");return{code:"rate_limited",message:G,retryable:!K}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:G,retryable:!0};if(T$(W))return{code:"context_length_exceeded",message:G,retryable:!1};if(A$(W))return{code:"content_filtered",message:G,retryable:!1};if($?.param?.startsWith("tools")||W.includes("invalid schema for function"))return{code:"invalid_tool_input",message:G,retryable:!1};return{code:"provider_error",message:G,retryable:!1}}function T$(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function A$(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function E$(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class _ extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function T(Q,$){if($.aborted)return Promise.reject(new _);return new Promise((Z,G)=>{let J=()=>G(new _);$.addEventListener("abort",J,{once:!0}),Q.then(Z,G).finally(()=>$.removeEventListener("abort",J))})}function A(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function q(Q,$){if(!$)return Q;let Z={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)Z.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)Z.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);if($.imageInputTokens!==void 0||Q.imageInputTokens!==void 0)Z.imageInputTokens=(Q.imageInputTokens??0)+($.imageInputTokens??0);if($.imageOutputTokens!==void 0||Q.imageOutputTokens!==void 0)Z.imageOutputTokens=(Q.imageOutputTokens??0)+($.imageOutputTokens??0);return Z}function e(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,G=!1;for(let W of Q){if(Z){if(G)G=!1;else if(W==="\\")G=!0;else if(W==='"')Z=!1;continue}if(W==='"')Z=!0;else if(W==="{")$.push("}");else if(W==="[")$.push("]");else if(W==="}"||W==="]")$.pop()}let J=Q;if(Z)J+='"';J=J.replace(/[,:]\s*$/,"");let Y=$.reverse().join("");try{return JSON.parse(J+Y)}catch{try{return JSON.parse(J.replace(/,?\s*"[^"]*"\s*$/,"")+Y)}catch{return{}}}}function QQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:p(Q)}}function $Q(Q,$){let Z=Q.safeParse(e($));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 ZQ(Q){if(Q.length>0)Q[0];return Q}function l(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type===$){G.text=(G.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function GQ(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type==="reasoning"&&G.id===$){G.text=(G.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function x$(Q){return RQ(Q)}async function RQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,G=await I$(Q);if($.settled?.(G),!G.ok){if(Q.logErrors!==!1&&G.error.code!=="aborted")b$(Z,G.error,$.origin);if(Q.throwOnError)throw new d({runId:Z,messages:G.messages,finishReason:G.finishReason,usage:G.usage,error:G.error})}return G}function b$(Q,$,Z){let G=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,J={...Z,generateId:Q,error:$},Y=!1;try{JQ.error(G,J),Y=!0}catch{}if(!Y||Bun.env.NODE_ENV==="development")console.error(G,J)}async function I$(Q){let $=Q.messages??[];if($.length===0&&!Q.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...$];if(Q.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q.prompt}],createdAt:new Date().toISOString()});let G={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},J=Q.signal??new AbortController().signal,Y=A(),W="stop",K,V={},X="";try{let U=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:QQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let F=await T(Promise.resolve(U.next()),J);if(F.done)break;let D=F.value;switch(D.type){case"output-delta":X+=D.delta;break;case"text-delta":l(G,"text",D.delta);break;case"reasoning-delta":GQ(G,D.id,D.delta);break;case"finish":if(Y=q(Y,D.usage),!K)W=D.reason;break;case"error":W="error",K=D.error,V=M(D);break}}}finally{if(J.aborted)Promise.resolve(U.return?.()).catch(()=>{})}}catch(z){if(z instanceof _||J.aborted)W="aborted",K=w$(J);else W="error",K=Q.provider.normalizeError(z),V=M(z)}let H=!1,B;if(!K)if(W==="length")K={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(!X.trim())K={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let z=$Q(Q.output,X);if(z.ok===!0)H=!0,B=z.value;else K=z.error}if(H)G.content.push({type:"output",value:B});else if(X)l(G,"text",X);for(let z of G.content)if((z.type==="text"||z.type==="reasoning")&&typeof z.text==="string")z.text=ZQ(z.text);if(G.finishReason=W,Z.push(G),H)return{ok:!0,output:B,messages:Z,usage:Y,finishReason:W};return{ok:!1,error:{...K,...V},messages:Z,usage:Y,finishReason:W}}function w$(Q){return Q.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}import{createHmac as f$,randomBytes as z9,timingSafeEqual as D9}from"crypto";var kQ="agt1",U9=86400000;function YQ(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function E(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(E).join(",")}]`;let $=Q;return`{${Object.keys($).filter((G)=>$[G]!==void 0).sort().map((G)=>`${JSON.stringify(G)}:${E($[G])}`).join(",")}}`}function v$(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function WQ(Q,$){return f$("sha256",Q).update(v$($)).digest()}function F9(Q,$,Z){let G=[kQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),E(Q.input)];if(Q.path&&Q.path.length>0)G.push(E(Q.path));return G}var O9=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),y$=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function L9(Q,$={}){let Z=YQ($.secret),J=($.now??Date.now())+($.ttlMs??U9),Y=z9(12).toString("base64url"),W=WQ(Z,F9(Q,Y,J)).toString("base64url");return[kQ,O9(Q.runId),Y,J.toString(36),W].join(".")}function XQ(Q){return TQ(Q,kQ)}function TQ(Q,$){let Z=Q.split(".");if(Z.length!==5||Z[0]!==$)return null;let G=Number.parseInt(Z[3],36);if(!Number.isFinite(G))return null;try{return{runId:y$(Z[1]),nonce:Z[2],expiresAt:G}}catch{return null}}function N9(Q,$,Z={}){let G=YQ(Z.secret),J=XQ(Q);if(!J)return{ok:!1,reason:"malformed"};let Y=Buffer.from(Q.split(".")[4],"base64url"),W=WQ(G,F9($,J.nonce,J.expiresAt));if(Y.length!==W.length||!D9(Y,W))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var VQ="agn1";function C9(Q,$,Z){return[VQ,Q.runId,E(Q.path),Q.nestedRunId,$,String(Z),E([...Q.open].sort()),E(Q.input)]}function P9(Q,$={}){let Z=YQ($.secret),J=($.now??Date.now())+($.ttlMs??U9),Y=z9(12).toString("base64url"),W=WQ(Z,C9(Q,Y,J)).toString("base64url");return[VQ,O9(Q.runId),Y,J.toString(36),W].join(".")}function _9(Q,$,Z={}){let G=YQ(Z.secret),J=TQ(Q,VQ);if(!J)return{ok:!1,reason:"malformed"};let Y=Buffer.from(Q.split(".")[4],"base64url"),W=WQ(G,C9({...$,runId:J.runId},J.nonce,J.expiresAt));if(Y.length!==W.length||!D9(Y,W))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var u=new Map,j9=1024;function h$(Q){for(let[$,Z]of u)if(Z<=Q)u.delete($);j9=Math.max(1024,u.size*2)}function M9(Q,$={}){return S9(XQ(Q),$)}function q9(Q,$={}){return S9(TQ(Q,VQ),$)}function S9(Q,$){if(!Q)return!1;let Z=$.now??Date.now();if(u.size>=j9)h$(Z);let G=u.get(Q.nonce);if(G!==void 0&&G>Z)return!1;return u.set(Q.nonce,Q.expiresAt),!0}class i extends Error{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class g extends Error{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function AQ(Q){if(!Q||typeof Q.key!=="string"||Q.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 Q}var j="gemi_att_";function EQ(){return`${j}${crypto.randomUUID()}`}class o{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;AQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new i(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new i(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),G=(await this.readRecord(Q,$)).body,J=G instanceof Blob?G:G?await new Response(G).blob():new Blob([]);return new File([J],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=EQ(),G=$.mimeType??Q.type??"",J=$.name??(Q instanceof File?Q.name:Z),Y=await this.storage.put({name:xQ(Z,J),body:Q,contentType:G||void 0}),W={id:Z,scopeKey:this.scope.key,objectName:Y,name:J,mimeType:G||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,W),W}}function xQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class KQ{rows=new Map;async put(Q,$){AQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){AQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var HQ=new KQ;var bQ=new TextEncoder;function R9(Q){return`id: ${Q.seq}
2
+ import{Db as j,Eb as k9,Fb as $$,Gb as Z$,Hb as a$,Ib as lZ,Jb as o}from"../chunk-w312e9nx.js";import{Ie as o$,Le as s$,_e as GQ,mf as t$,of as s,pf as hQ}from"../chunk-174jkg6d.js";import{qf as n$,sf as IQ,tf as vQ}from"../chunk-jhe0t7yj.js";import{xf as PQ}from"../chunk-1jcp8m8h.js";import{tg as A9}from"../chunk-d3jkypc7.js";import"../chunk-8gexb1gt.js";import"../chunk-swhyp0yw.js";import"../chunk-cbycz5z3.js";import"../chunk-9tsw1bmt.js";class w extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${V3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class WQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function V3(Q){let $=T9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function T9(Q){if(!Q||typeof Q!=="object")return null;let $=Q,G=$.error&&typeof $.error==="object"?$.error:Q;if(typeof G.message!=="string"&&typeof G.code!=="string"&&typeof G.type!=="string")return null;let J=G.innererror?.code??G.code;return{message:G.message,type:G.type,code:J,param:G.param}}function T(Q){if(!Q||typeof Q!=="object")return{};let{status:$,requestId:Z}=Q;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function _(Q){if(Q instanceof WQ)return{code:"provider_error",message:Q.message,retryable:!0};if(H3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof w)return X3(Q.status,T9(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function X3(Q,$,Z){let G=$?.message??Z,J=($?.code??"").toLowerCase(),W=($?.type??"").toLowerCase(),V=`${J} ${W} ${G}`.toLowerCase();if(Q===429){let X=J==="insufficient_quota"||V.includes("quota");return{code:"rate_limited",message:G,retryable:!X}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:G,retryable:!0};if(Y3(V))return{code:"context_length_exceeded",message:G,retryable:!1};if(K3(V))return{code:"content_filtered",message:G,retryable:!1};if($?.param?.startsWith("tools")||V.includes("invalid schema for function"))return{code:"invalid_tool_input",message:G,retryable:!1};return{code:"provider_error",message:G,retryable:!1}}function Y3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function K3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function H3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class S extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function v(Q,$){if($.aborted)return Promise.reject(new S);return new Promise((Z,G)=>{let J=()=>G(new S);$.addEventListener("abort",J,{once:!0}),Q.then(Z,G).finally(()=>$.removeEventListener("abort",J))})}function I(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function E(Q,$){if(!$)return Q;let Z={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)Z.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)Z.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);if($.imageInputTokens!==void 0||Q.imageInputTokens!==void 0)Z.imageInputTokens=(Q.imageInputTokens??0)+($.imageInputTokens??0);if($.imageOutputTokens!==void 0||Q.imageOutputTokens!==void 0)Z.imageOutputTokens=(Q.imageOutputTokens??0)+($.imageOutputTokens??0);return Z}function VQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,G=!1;for(let V of Q){if(Z){if(G)G=!1;else if(V==="\\")G=!0;else if(V==='"')Z=!1;continue}if(V==='"')Z=!0;else if(V==="{")$.push("}");else if(V==="[")$.push("]");else if(V==="}"||V==="]")$.pop()}let J=Q;if(Z)J+='"';J=J.replace(/[,:]\s*$/,"");let W=$.reverse().join("");try{return JSON.parse(J+W)}catch{try{return JSON.parse(J.replace(/,?\s*"[^"]*"\s*$/,"")+W)}catch{return{}}}}function XQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:o(Q)}}function YQ(Q,$){let Z=Q.safeParse(VQ($));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 KQ(Q){if(Q.length>0)Q[0];return Q}function n(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type===$){G.text=(G.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function HQ(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type==="reasoning"&&G.id===$){G.text=(G.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function z3(Q){return fQ(Q)}async function fQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,G=await D3(Q);if($.settled?.(G),!G.ok){if(Q.logErrors!==!1&&G.error.code!=="aborted")B3(Z,G.error,$.origin);if(Q.throwOnError)throw new t({runId:Z,messages:G.messages,finishReason:G.finishReason,usage:G.usage,error:G.error})}return G}function B3(Q,$,Z){let G=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,J={...Z,generateId:Q,error:$},W=!1;try{s.error(G,J),W=!0}catch{}if(!W||Bun.env.NODE_ENV==="development")console.error(G,J)}async function D3(Q){let $=Q.messages??[];if($.length===0&&!Q.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...$];if(Q.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q.prompt}],createdAt:new Date().toISOString()});let G={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},J=Q.signal??new AbortController().signal,W=I(),V="stop",X,K={},Y="";try{let U=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:XQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let F=await v(Promise.resolve(U.next()),J);if(F.done)break;let D=F.value;switch(D.type){case"output-delta":Y+=D.delta;break;case"text-delta":n(G,"text",D.delta);break;case"reasoning-delta":HQ(G,D.id,D.delta);break;case"finish":if(W=E(W,D.usage),!X)V=D.reason;break;case"error":V="error",X=D.error,K=T(D);break}}}finally{if(J.aborted)Promise.resolve(U.return?.()).catch(()=>{})}}catch(B){if(B instanceof S||J.aborted)V="aborted",X=U3(J);else V="error",X=Q.provider.normalizeError(B),K=T(B)}let H=!1,z;if(!X)if(V==="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 B=YQ(Q.output,Y);if(B.ok===!0)H=!0,z=B.value;else X=B.error}if(H)G.content.push({type:"output",value:z});else if(Y)n(G,"text",Y);for(let B of G.content)if((B.type==="text"||B.type==="reasoning")&&typeof B.text==="string")B.text=KQ(B.text);if(G.finishReason=V,G.usage=W,Z.push(G),H)return{ok:!0,output:z,messages:Z,usage:W,finishReason:V};return{ok:!1,error:{...X,...K},messages:Z,usage:W,finishReason:V}}function U3(Q){return Q.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}import{createHmac as F3,randomBytes as E9,timingSafeEqual as x9}from"crypto";class a{spent=new Map;sweepAt=1024;async consume(Q,$){return this.consumeSync(Q,$)}consumeSync(Q,$,Z=Date.now()){if(this.spent.size>=this.sweepAt)this.sweep(Z);let G=this.spent.get(Q);if(G!==void 0&&G>Z)return!1;return this.spent.set(Q,$),!0}get size(){return this.spent.size}sweep(Q){for(let[$,Z]of this.spent)if(Z<=Q)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class yQ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:nonce"}async consume(Q,$){let Z=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Q}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Q=A9(),$=Q.bound(hQ)?Q.make(hQ).client:void 0;if(!$)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return $}}var p=new a;var gQ="agt1",b9=86400000;function zQ(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function f(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(f).join(",")}]`;let $=Q;return`{${Object.keys($).filter((G)=>$[G]!==void 0).sort().map((G)=>`${JSON.stringify(G)}:${f($[G])}`).join(",")}}`}function L3(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function BQ(Q,$){return F3("sha256",Q).update(L3($)).digest()}function w9(Q,$,Z){let G=[gQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),f(Q.input)];if(Q.path&&Q.path.length>0)G.push(f(Q.path));return G}var I9=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),C3=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function v9(Q,$={}){let Z=zQ($.secret),J=($.now??Date.now())+($.ttlMs??b9),W=E9(12).toString("base64url"),V=BQ(Z,w9(Q,W,J)).toString("base64url");return[gQ,I9(Q.runId),W,J.toString(36),V].join(".")}function DQ(Q){return uQ(Q,gQ)}function uQ(Q,$){let Z=Q.split(".");if(Z.length!==5||Z[0]!==$)return null;let G=Number.parseInt(Z[3],36);if(!Number.isFinite(G))return null;try{return{runId:C3(Z[1]),nonce:Z[2],expiresAt:G}}catch{return null}}function f9(Q,$,Z={}){let G=zQ(Z.secret),J=DQ(Q);if(!J)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),V=BQ(G,w9($,J.nonce,J.expiresAt));if(W.length!==V.length||!x9(W,V))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var UQ="agn1";function h9(Q,$,Z){return[UQ,Q.runId,f(Q.path),Q.nestedRunId,$,String(Z),f([...Q.open].sort()),f(Q.input)]}function y9(Q,$={}){let Z=zQ($.secret),J=($.now??Date.now())+($.ttlMs??b9),W=E9(12).toString("base64url"),V=BQ(Z,h9(Q,W,J)).toString("base64url");return[UQ,I9(Q.runId),W,J.toString(36),V].join(".")}function g9(Q,$,Z={}){let G=zQ(Z.secret),J=uQ(Q,UQ);if(!J)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),V=BQ(G,h9({...$,runId:J.runId},J.nonce,J.expiresAt));if(W.length!==V.length||!x9(W,V))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}function u9(Q,$){return p9($,DQ(Q))}function c9(Q,$){return p9($,uQ(Q,UQ))}async function p9(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class r extends j{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class m extends j{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function cQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new m("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 Q}var A="gemi_att_";function pQ(){return`${A}${crypto.randomUUID()}`}class e{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;cQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new r(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new r(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),G=(await this.readRecord(Q,$)).body,J=G instanceof Blob?G:G?await new Response(G).blob():new Blob([]);return new File([J],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=pQ(),G=$.mimeType??Q.type??"",J=$.name??(Q instanceof File?Q.name:Z),W=await this.storage.put({name:mQ(Z,J),body:Q,contentType:G||void 0}),V={id:Z,scopeKey:this.scope.key,objectName:W,name:J,mimeType:G||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,V),V}}function mQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class FQ{rows=new Map;async put(Q,$){cQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){cQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var LQ=new FQ;var dQ=new TextEncoder;function m9(Q){return`id: ${Q.seq}
3
3
  data: ${JSON.stringify(Q.event)}
4
4
 
5
- `}var u$=5000,g$=`: keepalive
5
+ `}var O3=5000,P3=`: keepalive
6
6
 
7
- `;function IQ(Q,$=u$){let Z=null,G=!1,J=()=>{if(G)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,G)return;try{Q.enqueue(bQ.encode(g$))}catch{Y();return}J()},$)},Y=()=>{if(G=!0,Z!==null)clearTimeout(Z);Z=null};return J(),{touch:J,stop:Y}}function c$(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function k9(Q,$=200){let Z=Q[Symbol.asyncIterator](),G=-1,J,Y=new ReadableStream({start(W){J=IQ(W)},async pull(W){try{let K=await Z.next();if(K.done){J.stop(),W.close();return}G=K.value.seq,W.enqueue(bQ.encode(R9(K.value))),J.touch()}catch(K){let V={type:"error",error:m$(K)};J.stop(),W.enqueue(bQ.encode(R9({seq:G+1,event:V}))),W.close()}},cancel(W){J.stop(),Z.return?.(W)}});return new Response(Y,{status:$,headers:c$()})}function m$(Q){return{code:"unknown",message:Q instanceof Error?Q.message:String(Q),retryable:!1}}class x extends Error{pending;path;nested;constructor(Q){super(`A nested agent run is waiting on the user for ${Q.pending.length} tool call(s).`);this.name="PendingEscalation",this.pending=Q.pending,this.path=Q.path,this.nested=Q.nested}}class b{name;description;inputSchema;outputSchema;requiresApproval;deferred;answeredBy;timeoutMs;execute;constructor(Q){this.name=Q.name,this.description=Q.description,this.inputSchema=Q.inputSchema,this.outputSchema=Q.outputSchema,this.requiresApproval=Q.requiresApproval===!0,this.deferred=Q.deferred===!0,this.answeredBy=Q.answeredBy==="client"?"client":"server",this.execute=Q.execute??void 0,this.timeoutMs=Q.timeoutMs}static create(Q){if(u9(Q.inputSchema,`The tool "${Q.name}"`,"inputSchema"),Q.timeoutMs!==void 0)fQ(Q.timeoutMs,`The tool "${Q.name}"`,"timeoutMs");return new b(Q)}static ask(Q){return b.create({name:Q.name,description:Q.description,inputSchema:yQ,outputSchema:Q.outputSchema,answeredBy:"client"})}}var yQ={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=yQ.safeParse(Q);if($.ok===!1)throw Error($.errors.join(", "));return $.value},safeParse(Q){if(typeof Q!=="object"||Q===null||typeof Q.question!=="string")return{ok:!1,errors:["question: expected a string"]};return{ok:!0,value:{question:Q.question}}}};class DQ{name;description;tools;deferred;constructor(Q){this.name=Q.name,this.description=Q.description,this.tools=Q.tools,this.deferred=Q.deferred===!0}static create(Q){return new DQ(Q)}}class hQ{name;description;instructions;files;constructor(Q){this.name=Q.name,this.description=Q.description,this.instructions=Q.instructions,this.files=Q.files}static create(Q){return new hQ(Q)}}var n="skills",p$="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.";function u9(Q,$,Z){let G=Q?.toJSONSchema?.();if(G?.type==="object")return;let J=!G?"no JSON Schema":G.anyOf?"a union (`anyOf`) \u2014 `s.union(...)`":G.type!==void 0?`a schema of type ${JSON.stringify(G.type)}`:"an unconstrained schema (`s.json()`)";throw Error(`${$} declares an \`${Z}\` whose root is ${J}, 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 fQ(Q,$,Z){if(typeof Q==="number"&&Q>0)return;throw Error(`${$} sets \`${Z}\` to ${String(Q)}, but it has to be a positive number of milliseconds. Use \`null\` for no limit.`)}function T9(Q){if(Q===void 0)return;if(Q===null||!Number.isFinite(Q))return null;return Q}var l$=2147483647;function A9(Q,$){if(Q===null||Q>l$)return()=>{};let Z=setTimeout($,Q);return()=>clearTimeout(Z)}function wQ(Q){if(Q<1000)return`${Q}ms`;if(Q<60000)return`${+(Q/1000).toFixed(1)}s`;return`${+(Q/60000).toFixed(1)}m`}var g9={type:"object",properties:{},required:[],additionalProperties:!1},uQ=600000;class d extends Error{code;retryable;status;requestId;toolCallId;runId;result;constructor(Q){super(Q.error.message);this.name="AgentRunError",this.code=Q.error.code,this.retryable=Q.error.retryable,this.status=Q.error.status,this.requestId=Q.error.requestId,this.toolCallId=Q.error.toolCallId,this.runId=Q.runId,this.result=Q}}function d$(Q){return{code:Q.code,message:Q.message,...Q.toolCallId!==void 0?{toolCallId:Q.toolCallId}:{},retryable:Q.retryable}}var i$=8,o$=3;class gQ{name;tools;skills;provider;output;instructions;maxSteps;maxDepth;reasoning;maxRunDurationMs;config;constructor(Q){this.name=Q.name,this.instructions=Q.instructions,this.provider=Q.provider,this.tools=Q.tools??[],this.skills=Q.skills??[],this.output=Q.output,this.maxSteps=Q.maxSteps??i$,this.maxDepth=Q.maxDepth??o$,this.reasoning=Q.reasoning;let $=T9(Q.maxRunDurationMs);this.maxRunDurationMs=$===void 0?uQ:$;let{registry:Z,providerTools:G}=n$(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:Z,providerTools:G,output:Q.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,logErrors:Q.logErrors??!0,maxRunDurationMs:$}}static create(Q){if(Q.output)u9(Q.output,`The agent "${Q.name}"`,"output");if(Q.maxRunDurationMs!=null)fQ(Q.maxRunDurationMs,`The agent "${Q.name}"`,"maxRunDurationMs");return new gQ(Q)}stream(Q){let $={...this.config,provider:Q.provider??this.config.provider,maxSteps:Q.maxSteps??this.config.maxSteps,reasoning:Q.reasoning??this.config.reasoning,maxOutputTokens:Q.maxOutputTokens??this.config.maxOutputTokens,temperature:Q.temperature??this.config.temperature,maxRunDurationMs:Q.maxRunDurationMs!==void 0?T9(Q.maxRunDurationMs):this.config.maxRunDurationMs};if(Q.maxRunDurationMs!=null)fQ(Q.maxRunDurationMs,`Agent.stream for "${this.name}"`,"maxRunDurationMs");return new m9($,Q)}}function E9(Q){return{name:Q.tool.name,description:Q.tool.description,parameters:Q.tool.inputSchema.toJSONSchema(),strict:p(Q.tool.inputSchema),deferred:Q.deferred}}function n$(Q,$){let Z=new Map,G=[],J=(Y)=>{if(Z.has(Y.tool.name))throw Error(`Two tools are named "${Y.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(Y.tool.name,Y)};for(let Y of Q){if(Y instanceof DQ){if(Y.name===n)throw Error(`"${n}" 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 K=[];for(let V of Y.tools){let X={tool:V,namespace:Y.name,deferred:Y.deferred||V.deferred};J(X),K.push(E9(X))}G.push({name:Y.name,description:Y.description,tools:K});continue}let W={tool:Y,deferred:Y.deferred};J(W),G.push(E9(W))}if($.length>0){let Y=[];for(let W of $){let K=s$(W);J({tool:K,namespace:n,deferred:!1}),Y.push({name:W.name,description:W.description,parameters:g9,strict:!0,deferred:!1})}G.push({name:n,description:p$,tools:Y})}return{registry:Z,providerTools:G}}function s$(Q){return b.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>g9,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Z=[typeof Q.instructions==="function"?await Q.instructions():Q.instructions];for(let G of Q.files??[])Z.push(`--- ${G} ---
8
- ${await t$(G)}`);return Z.join(`
7
+ `;function lQ(Q,$=O3){let Z=null,G=!1,J=()=>{if(G)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,G)return;try{Q.enqueue(dQ.encode(P3))}catch{W();return}J()},$)},W=()=>{if(G=!0,Z!==null)clearTimeout(Z);Z=null};return J(),{touch:J,stop:W}}function j3(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function d9(Q,$=200){let Z=Q[Symbol.asyncIterator](),G=-1,J,W=new ReadableStream({start(V){J=lQ(V)},async pull(V){try{let X=await Z.next();if(X.done){J.stop(),V.close();return}G=X.value.seq,V.enqueue(dQ.encode(m9(X.value))),J.touch()}catch(X){let K={type:"error",error:_3(X)};J.stop(),V.enqueue(dQ.encode(m9({seq:G+1,event:K}))),V.close()}},cancel(V){J.stop(),Z.return?.(V)}});return new Response(W,{status:$,headers:j3()})}var N3=new Set(["frame_cursor_evicted","live_run_not_found"]);function _3(Q){let $=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof $==="string"&&N3.has($))return{code:"unknown",message:Q.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",Q),{code:"unknown",message:"The run's stream failed.",retryable:!1}}class h extends Error{pending;path;nested;constructor(Q){super(`A nested agent run is waiting on the user for ${Q.pending.length} tool call(s).`);this.name="PendingEscalation",this.pending=Q.pending,this.path=Q.path,this.nested=Q.nested}}class y{name;description;inputSchema;outputSchema;requiresApproval;deferred;answeredBy;timeoutMs;execute;constructor(Q){this.name=Q.name,this.description=Q.description,this.inputSchema=Q.inputSchema,this.outputSchema=Q.outputSchema,this.requiresApproval=Q.requiresApproval===!0,this.deferred=Q.deferred===!0,this.answeredBy=Q.answeredBy==="client"?"client":"server",this.execute=Q.execute??void 0,this.timeoutMs=Q.timeoutMs}static create(Q){if(G$(Q.inputSchema,`The tool "${Q.name}"`,"inputSchema"),Q.timeoutMs!==void 0)oQ(Q.timeoutMs,`The tool "${Q.name}"`,"timeoutMs");return new y(Q)}static ask(Q){return y.create({name:Q.name,description:Q.description,inputSchema:sQ,outputSchema:Q.outputSchema,answeredBy:"client"})}}var sQ={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=sQ.safeParse(Q);if($.ok===!1)throw Error($.errors.join(", "));return $.value},safeParse(Q){if(typeof Q!=="object"||Q===null||typeof Q.question!=="string")return{ok:!1,errors:["question: expected a string"]};return{ok:!0,value:{question:Q.question}}}};class jQ{name;description;tools;deferred;constructor(Q){this.name=Q.name,this.description=Q.description,this.tools=Q.tools,this.deferred=Q.deferred===!0}static create(Q){return new jQ(Q)}}class tQ{name;description;instructions;files;constructor(Q){this.name=Q.name,this.description=Q.description,this.instructions=Q.instructions,this.files=Q.files}static create(Q){return new tQ(Q)}}var QQ="skills",M3="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.";function G$(Q,$,Z){let G=Q?.toJSONSchema?.();if(G?.type==="object")return;let J=!G?"no JSON Schema":G.anyOf?"a union (`anyOf`) \u2014 `s.union(...)`":G.type!==void 0?`a schema of type ${JSON.stringify(G.type)}`:"an unconstrained schema (`s.json()`)";throw Error(`${$} declares an \`${Z}\` whose root is ${J}, 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 oQ(Q,$,Z){if(typeof Q==="number"&&Q>0)return;throw Error(`${$} sets \`${Z}\` to ${String(Q)}, but it has to be a positive number of milliseconds. Use \`null\` for no limit.`)}function l9(Q){if(Q===void 0)return;if(Q===null||!Number.isFinite(Q))return null;return Q}var q3=2147483647;function i9(Q,$){if(Q===null||Q>q3)return()=>{};let Z=setTimeout($,Q);return()=>clearTimeout(Z)}function iQ(Q){if(Q<1000)return`${Q}ms`;if(Q<60000)return`${+(Q/1000).toFixed(1)}s`;return`${+(Q/60000).toFixed(1)}m`}var J$={type:"object",properties:{},required:[],additionalProperties:!1},aQ=600000;class t extends Error{code;retryable;status;requestId;toolCallId;runId;result;constructor(Q){super(Q.error.message);this.name="AgentRunError",this.code=Q.error.code,this.retryable=Q.error.retryable,this.status=Q.error.status,this.requestId=Q.error.requestId,this.toolCallId=Q.error.toolCallId,this.runId=Q.runId,this.result=Q}}var S3=8,R3=3;class rQ{name;tools;skills;provider;output;instructions;maxSteps;maxDepth;reasoning;maxRunDurationMs;config;constructor(Q){this.name=Q.name,this.instructions=Q.instructions,this.provider=Q.provider,this.tools=Q.tools??[],this.skills=Q.skills??[],this.output=Q.output,this.maxSteps=Q.maxSteps??S3,this.maxDepth=Q.maxDepth??R3,this.reasoning=Q.reasoning;let $=l9(Q.maxRunDurationMs);this.maxRunDurationMs=$===void 0?aQ:$;let{registry:Z,providerTools:G}=k3(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:Z,providerTools:G,output:Q.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,logErrors:Q.logErrors??!0,maxRunDurationMs:$}}static create(Q){if(Q.output)G$(Q.output,`The agent "${Q.name}"`,"output");if(Q.maxRunDurationMs!=null)oQ(Q.maxRunDurationMs,`The agent "${Q.name}"`,"maxRunDurationMs");return new rQ(Q)}stream(Q){let $={...this.config,provider:Q.provider??this.config.provider,maxSteps:Q.maxSteps??this.config.maxSteps,reasoning:Q.reasoning??this.config.reasoning,maxOutputTokens:Q.maxOutputTokens??this.config.maxOutputTokens,temperature:Q.temperature??this.config.temperature,maxRunDurationMs:Q.maxRunDurationMs!==void 0?l9(Q.maxRunDurationMs):this.config.maxRunDurationMs};if(Q.maxRunDurationMs!=null)oQ(Q.maxRunDurationMs,`Agent.stream for "${this.name}"`,"maxRunDurationMs");return new V$($,Q)}}function o9(Q){return{name:Q.tool.name,description:Q.tool.description,parameters:Q.tool.inputSchema.toJSONSchema(),strict:o(Q.tool.inputSchema),deferred:Q.deferred}}function k3(Q,$){let Z=new Map,G=[],J=(W)=>{if(Z.has(W.tool.name))throw Error(`Two tools are named "${W.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(W.tool.name,W)};for(let W of Q){if(W instanceof jQ){if(W.name===QQ)throw Error(`"${QQ}" 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 W.tools){let Y={tool:K,namespace:W.name,deferred:W.deferred||K.deferred};J(Y),X.push(o9(Y))}G.push({name:W.name,description:W.description,tools:X});continue}let V={tool:W,deferred:W.deferred};J(V),G.push(o9(V))}if($.length>0){let W=[];for(let V of $){let X=T3(V);J({tool:X,namespace:QQ,deferred:!1}),W.push({name:V.name,description:V.description,parameters:J$,strict:!0,deferred:!1})}G.push({name:QQ,description:M3,tools:W})}return{registry:Z,providerTools:G}}function T3(Q){return y.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>J$,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Z=[typeof Q.instructions==="function"?await Q.instructions():Q.instructions];for(let G of Q.files??[])Z.push(`--- ${G} ---
8
+ ${await A3(G)}`);return Z.join(`
9
9
 
10
- `)}})}async function t$(Q){try{return await Bun.file(Q).text()}catch($){return`(could not be read: ${$.message})`}}function r$(Q){return typeof Q==="object"&&Q!==null&&typeof Q.next==="function"&&Symbol.asyncIterator in Q}function x9(Q,$){let Z=[...Q],G=new Map(Z.map((J,Y)=>[J.id,Y]));for(let J of $){let Y=G.get(J.id);if(Y===void 0)G.set(J.id,Z.length),Z.push(J);else Z[Y]=J}return Z}function BQ(Q){let $=new Set;for(let G of Q)for(let J of G.content)if(J.type==="tool-result")$.add(J.toolCallId);let Z=new Set;for(let G of Q)for(let J of G.content)if(J.type==="tool-call"&&!$.has(J.toolCallId))Z.add(J.toolCallId);return Z}function b9(Q){for(let $=Q.length-1;$>=0;$--){let Z=Q[$].content;for(let G=Z.length-1;G>=0;G--){let J=Z[G];if(J.type==="output"&&J.partial!==!0)return J.value}}return}function I9(Q,$){return $===void 0?`"${Q}"`:`"${Q}" labelled "${$}"`}function c9(Q){return Q.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function a$(Q){if(Q.prompt!==void 0)return`user:${Q.prompt}`;let $=Q.messages?.[0];return $?`${$.role}:${c9($)}`:null}function w9(Q){let $=new Set;for(let Z of Q)for(let G of Z.content){if(G.type!=="tool-call")continue;for(let J of G.attachments??[])if("shown"in J&&J.shown)$.add(J.shown.messageId)}return $}var f9=1;function e$(Q,$,Z){let G=Z.mimeType||$.type||"";if(G&&Q.attachment.mimeType!==G)return`was ${JSON.stringify(Q.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(G)} on the replay`;let J=Boolean(Z.showModel);if(J!==Boolean(Q.shown))return J?"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 Q3(Q,$,Z){if(Q.agent!==$.name||Q.label!==Z.label)return`was ${I9(Q.agent,Q.label)} on the turn that escalated and is ${I9($.name,Z.label)} on the replay`;let G=a$(Z),J=Q.messages[0],Y=J?`${J.role}:${c9(J)}`:null;if(G!==null&&Y!==null&&G!==Y)return`was started with ${JSON.stringify(Y)} on the turn that escalated and with ${JSON.stringify(G)} on the replay`;return null}function v9(Q,$){let Z=Q??[];if(Z.length<$.length)return null;for(let G=0;G<$.length;G++)if(Z[G]!==$[G])return null;return Z.slice($.length)}class vQ{read;create;fill;index=0;replayable;constructor(Q,$,Z){this.read=Q;this.create=$;this.fill=Z;this.replayable=Q()?.length??0}next(){let Q=this.index++;return{at:Q,recorded:Q<this.replayable?this.read()?.[Q]:void 0,write:($)=>{let Z=this.read()??this.create();if(this.fill)for(let G=Z.length;G<Q;G++)Z[G]=this.fill();Z[Q]=$}}}}class m9{runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=A();finishReason="stop";failure;output;stopReason;timedOutAfter;cancelDeadline=()=>{};settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor(Q,$){this.config=Q,this.params=$,this.context=$.context??{},this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages];let Z=$.nesting;if(this.depth=Z?.depth??0,this.maxDepth=Z?.maxDepth??Q.maxDepth,this.chain=Z?.chain??[Q.name],this.signingRunId=Z?.signingRunId??this.runId,this.pathPrefix=Z?.signingPath??[],this.onPending=Z?.onPending??"escalate",$.signal)if($.signal.aborted)this.controller.abort();else $.signal.addEventListener("abort",()=>this.stop(),{once:!0});let G=Q.maxRunDurationMs!==void 0?Q.maxRunDurationMs:Z?null:uQ;this.cancelDeadline=A9(G,()=>this.expire(G)),this.settled=this.execute(),zQ.getStore()?.waitUntil(this.settled)}emit(Q){if(this.ended)return;this.buffer.push({seq:++this.seq,event:Q}),this.wake()}wake(){let Q=[...this.waiters];this.waiters.clear();for(let $ of Q)$()}nextFrame(){return new Promise((Q)=>this.waiters.add(Q))}async*frames(Q=0){let $=Q>0?Q-1:0;for(;;){while($<this.buffer.length)yield this.buffer[$++];if(this.ended)return;await this.nextFrame()}}async*[Symbol.asyncIterator](){for await(let Q of this.frames())yield Q.event}toResponse(Q){let $=this.frames(Q?.from),Z=new TextEncoder,G=!1,J,Y=new ReadableStream({start:async(W)=>{J=IQ(W);try{for await(let K of $){if(G)break;W.enqueue(Z.encode(`id: ${K.seq}
11
- data: ${JSON.stringify(K.event)}
10
+ `)}})}async function A3(Q){try{return await Bun.file(Q).text()}catch($){return`(could not be read: ${$.message})`}}function E3(Q){return typeof Q==="object"&&Q!==null&&typeof Q.next==="function"&&Symbol.asyncIterator in Q}function n9(Q,$){let Z=[...Q],G=new Map(Z.map((J,W)=>[J.id,W]));for(let J of $){let W=G.get(J.id);if(W===void 0)G.set(J.id,Z.length),Z.push(J);else Z[W]=J}return Z}function CQ(Q){let $=new Set;for(let G of Q)for(let J of G.content)if(J.type==="tool-result")$.add(J.toolCallId);let Z=new Set;for(let G of Q)for(let J of G.content)if(J.type==="tool-call"&&!$.has(J.toolCallId))Z.add(J.toolCallId);return Z}function s9(Q){for(let $=Q.length-1;$>=0;$--){let Z=Q[$].content;for(let G=Z.length-1;G>=0;G--){let J=Z[G];if(J.type==="output"&&J.partial!==!0)return J.value}}return}function t9(Q,$){return $===void 0?`"${Q}"`:`"${Q}" labelled "${$}"`}function W$(Q){return Q.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function x3(Q){if(Q.prompt!==void 0)return`user:${Q.prompt}`;let $=Q.messages?.[0];return $?`${$.role}:${W$($)}`:null}function OQ(Q){let $=new Set;for(let Z of Q)for(let G of Z.content){if(G.type!=="tool-call")continue;for(let J of G.attachments??[])if("shown"in J&&J.shown)$.add(J.shown.messageId)}return $}var a9=1;function b3(Q,$,Z){let G=Z.mimeType||$.type||"";if(G&&Q.attachment.mimeType!==G)return`was ${JSON.stringify(Q.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(G)} on the replay`;let J=Boolean(Z.showModel);if(J!==Boolean(Q.shown))return J?"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 w3(Q,$,Z){if(Q.agent!==$.name||Q.label!==Z.label)return`was ${t9(Q.agent,Q.label)} on the turn that escalated and is ${t9($.name,Z.label)} on the replay`;let G=x3(Z),J=Q.messages[0],W=J?`${J.role}:${W$(J)}`:null;if(G!==null&&W!==null&&G!==W)return`was started with ${JSON.stringify(W)} on the turn that escalated and with ${JSON.stringify(G)} on the replay`;return null}function r9(Q,$){let Z=Q??[];if(Z.length<$.length)return null;for(let G=0;G<$.length;G++)if(Z[G]!==$[G])return null;return Z.slice($.length)}class nQ{read;create;fill;index=0;replayable;constructor(Q,$,Z){this.read=Q;this.create=$;this.fill=Z;this.replayable=Q()?.length??0}next(){let Q=this.index++;return{at:Q,recorded:Q<this.replayable?this.read()?.[Q]:void 0,write:($)=>{let Z=this.read()??this.create();if(this.fill)for(let G=Z.length;G<Q;G++)Z[G]=this.fill();Z[Q]=$}}}}class V${runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=I();finishReason="stop";failure;output;stopReason;timedOutAfter;cancelDeadline=()=>{};settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor(Q,$){this.config=Q,this.params=$,this.context=$.context??{},this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages];let Z=$.nesting;if(this.depth=Z?.depth??0,this.maxDepth=Z?.maxDepth??Q.maxDepth,this.chain=Z?.chain??[Q.name],this.signingRunId=Z?.signingRunId??this.runId,this.pathPrefix=Z?.signingPath??[],this.onPending=Z?.onPending??"escalate",$.signal)if($.signal.aborted)this.controller.abort();else $.signal.addEventListener("abort",()=>this.stop(),{once:!0});let G=Q.maxRunDurationMs!==void 0?Q.maxRunDurationMs:Z?null:aQ;this.cancelDeadline=i9(G,()=>this.expire(G)),this.settled=this.execute(),PQ.getStore()?.waitUntil(this.settled)}emit(Q){if(this.ended)return;this.buffer.push({seq:++this.seq,event:Q}),this.wake()}wake(){let Q=[...this.waiters];this.waiters.clear();for(let $ of Q)$()}nextFrame(){return new Promise((Q)=>this.waiters.add(Q))}async*frames(Q=0){let $=Q>0?Q-1:0;for(;;){while($<this.buffer.length)yield this.buffer[$++];if(this.ended)return;await this.nextFrame()}}async*[Symbol.asyncIterator](){for await(let Q of this.frames())yield Q.event}toResponse(Q){let $=this.frames(Q?.from),Z=new TextEncoder,G=!1,J,W=new ReadableStream({start:async(V)=>{J=lQ(V);try{for await(let X of $){if(G)break;V.enqueue(Z.encode(`id: ${X.seq}
11
+ data: ${JSON.stringify(X.event)}
12
12
 
13
- `)),J.touch()}}catch{}J.stop();try{W.close()}catch{}},cancel:()=>{G=!0,J.stop()}});return new Response(Y,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(Q){if(!Q?.throwOnError)return this.settled;return this.settled.then(($)=>{if($.error)throw new d({...$,error:$.error});return $})}stop(Q){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Q?.reason,this.controller.abort()}expire(Q){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=Q,this.stopReason=`The run reached its time limit of ${wQ(Q)} 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 $=await this.ingestTurn();if($.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:$});else await this.loop()}catch($){if($ instanceof _||this.controller.signal.aborted)await this.finalizeAborted();else this.fail(this.config.provider.normalizeError($),M($)),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();let Q=this.finishReason==="error"?this.failure:void 0;if(Q&&this.config.logErrors)this.logFailure(Q);return{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,output:this.output,...Q?{error:Q}:{}}}fail(Q,$={}){let Z={...Q,...$};this.failure=Z,this.emit({type:"error",error:d$(Z)})}logFailure(Q){let $=`[gemi/ai] agent "${this.config.name}" run failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`,Z={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},error:Q},G=!1;try{JQ.error($,Z),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.error($,Z)}async loop(){let Q=Math.max(1,this.config.maxSteps);for(let $=1;$<=Q;$++){let Z=this.startMessage(),G=await this.runStep(Z);if(G.error){this.fail(G.error,G.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let J=Z.content.filter((W)=>W.type==="tool-call");if(J.length===0){this.finishReason=G.reason,await this.finalizeMessage(G.reason);return}let Y=await this.runTools(Z,J,$);if(Y.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:Y});return}if($===Q){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(G.reason)}}startMessage(){let Q={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()};return this.current=Q,this.history.push(Q),this.produced.push(Q),this.emit({type:"message-start",messageId:Q.id,role:"assistant"}),Q}async finalizeMessage(Q){let $=this.current;if(!$)return;this.current=null;let Z=this.outputTruncated;if(this.outputTruncated=!1,$.finishReason=Q,Z)$.outputTruncated=!0;for(let G of $.content)if(G.type==="text"||G.type==="reasoning"){if(typeof G.text==="string")G.text=ZQ(G.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Q,...Z?{outputTruncated:!0}:{}}),await this.report($),await this.reportDeferred()}async report(Q){if(!this.params.onMessage)return;try{await this.params.onMessage(Q)}catch{}}async runStep(Q){let $=this.controller.signal,Z=this.config.provider,G={reason:"stop"},J=new Map,Y="",K=Z.stream({messages:this.historyForProvider(Q),systemPrompt:await this.systemPrompt(),tools:this.config.providerTools.length>0?this.config.providerTools:void 0,output:this.config.output?QQ(this.config.output):void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:$})[Symbol.asyncIterator]();for(;;){let X=await T(Promise.resolve(K.next()),$);if(X.done)break;let H=X.value;switch(H.type){case"text-delta":{l(Q,"text",H.delta),this.emit({type:"text-delta",messageId:Q.id,delta:H.delta});break}case"reasoning-delta":{GQ(Q,H.id,H.delta),this.emit({type:"reasoning-delta",messageId:Q.id,delta:H.delta,id:H.id});break}case"output-delta":{Y+=H.delta,this.emit({type:"output-delta",messageId:Q.id,delta:H.delta,snapshot:e(Y)});break}case"tool-search":{this.emit({type:"tool-search",loaded:H.loaded});break}case"tool-call-delta":{let B=J.get(H.toolCallId)??{name:H.name,args:""};B.args+=H.argsDelta,B.name=H.name||B.name,J.set(H.toolCallId,B),this.emit({type:"tool-call",messageId:Q.id,part:{type:"tool-call",toolCallId:H.toolCallId,name:B.name,input:e(B.args),partial:!0}});break}case"tool-call":{J.delete(H.toolCallId);let B={type:"tool-call",toolCallId:H.toolCallId,name:H.name,input:h9(H.args)};Q.content.push(B),this.emit({type:"tool-call",messageId:Q.id,part:B});break}case"finish":{if(this.usage=q(this.usage,H.usage),!G.error)G={reason:H.reason};break}case"error":{G={reason:"error",error:H.error,detail:M(H)};break}}}for(let[X,H]of J){let B={type:"tool-call",toolCallId:X,name:H.name,input:h9(H.args)};Q.content.push(B),this.emit({type:"tool-call",messageId:Q.id,part:B})}let V=G.reason==="length";if(V)this.outputTruncated=!0;if(this.config.output&&Y&&!G.error&&!V){let X=$Q(this.config.output,Y);if(X.ok===!0)this.output=X.value,Q.content.push({type:"output",value:X.value});else this.emit({type:"error",error:X.error})}return G}async systemPrompt(){let Q=[this.config.instructions,this.params.instructions].filter(($)=>Boolean($&&$.trim()));return Q.length>0?Q.join(`
13
+ `)),J.touch()}}catch{}J.stop();try{V.close()}catch{}},cancel:()=>{G=!0,J.stop()}});return new Response(W,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(Q){if(!Q?.throwOnError)return this.settled;return this.settled.then(($)=>{if($.error)throw new t({...$,error:$.error});return $})}stop(Q){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Q?.reason,this.controller.abort()}expire(Q){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=Q,this.stopReason=`The run reached its time limit of ${iQ(Q)} 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 $=await this.ingestTurn();if($.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:$});else await this.loop()}catch($){if($ instanceof S||this.controller.signal.aborted)await this.finalizeAborted();else this.fail(this.config.provider.normalizeError($),T($)),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();let Q=this.finishReason==="error"?this.failure:void 0;if(Q&&this.config.logErrors)this.logFailure(Q);return{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,output:this.output,...Q?{error:Q}:{}}}fail(Q,$={}){let Z={...Q,...$};this.failure=Z,this.emit({type:"error",error:this.redact(Z,{source:"run",failure:Z})})}redact(Q,$){let Z=$$(this.params.redactError,Q,$,(G)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:G}));return Z$(Z,Q),Z}logFailure(Q){let $=`[gemi/ai] agent "${this.config.name}" run failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`;this.writeLog($,{error:Q})}logToolFailure(Q,$){let Z=$ instanceof Error?$.message:String($);this.writeLog(`[gemi/ai] agent "${this.config.name}" tool "${String(Q.name)}" threw: ${Z}`,{toolCallId:Q.toolCallId,error:$})}writeLog(Q,$){let Z={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},...$},G=!1;try{s.error(Q,Z),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.error(Q,Z)}async loop(){let Q=Math.max(1,this.config.maxSteps);for(let $=1;$<=Q;$++){let Z=this.startMessage(),G=await this.runStep(Z);if(G.error){this.fail(G.error,G.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let J=Z.content.filter((V)=>V.type==="tool-call");if(J.length===0){this.finishReason=G.reason,await this.finalizeMessage(G.reason);return}let W=await this.runTools(Z,J,$);if(W.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:W});return}if($===Q){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(G.reason)}}startMessage(){let Q={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()};return this.current=Q,this.history.push(Q),this.produced.push(Q),this.emit({type:"message-start",messageId:Q.id,role:"assistant"}),Q}async finalizeMessage(Q){let $=this.current;if(!$)return;this.current=null;let Z=this.outputTruncated;if(this.outputTruncated=!1,$.finishReason=Q,Z)$.outputTruncated=!0;for(let G of $.content)if(G.type==="text"||G.type==="reasoning"){if(typeof G.text==="string")G.text=KQ(G.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Q,...Z?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{}}),await this.report($),await this.reportDeferred()}async report(Q){if(!this.params.onMessage)return;try{await this.params.onMessage(Q)}catch{}}async runStep(Q){let $=this.controller.signal,Z=this.config.provider,G={reason:"stop"},J=new Map,W="",X=Z.stream({messages:this.historyForProvider(Q),systemPrompt:await this.systemPrompt(),tools:this.config.providerTools.length>0?this.config.providerTools:void 0,output:this.config.output?XQ(this.config.output):void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:$})[Symbol.asyncIterator]();for(;;){let Y=await v(Promise.resolve(X.next()),$);if(Y.done)break;let H=Y.value;switch(H.type){case"text-delta":{n(Q,"text",H.delta),this.emit({type:"text-delta",messageId:Q.id,delta:H.delta});break}case"reasoning-delta":{HQ(Q,H.id,H.delta),this.emit({type:"reasoning-delta",messageId:Q.id,delta:H.delta,id:H.id});break}case"output-delta":{W+=H.delta,this.emit({type:"output-delta",messageId:Q.id,delta:H.delta,snapshot:VQ(W)});break}case"tool-search":{this.emit({type:"tool-search",loaded:H.loaded});break}case"tool-call-delta":{let z=J.get(H.toolCallId)??{name:H.name,args:""};z.args+=H.argsDelta,z.name=H.name||z.name,J.set(H.toolCallId,z),this.emit({type:"tool-call",messageId:Q.id,part:{type:"tool-call",toolCallId:H.toolCallId,name:z.name,input:VQ(z.args),partial:!0}});break}case"tool-call":{J.delete(H.toolCallId);let z={type:"tool-call",toolCallId:H.toolCallId,name:H.name,input:Q$(H.args)};Q.content.push(z),this.emit({type:"tool-call",messageId:Q.id,part:z});break}case"finish":{if(this.usage=E(this.usage,H.usage),Q.usage=E(Q.usage??I(),H.usage),!G.error)G={reason:H.reason};break}case"error":{G={reason:"error",error:H.error,detail:T(H)};break}case"file-rejected":{this.markFileRejected(H.fileId,H.message,T(H));break}}}for(let[Y,H]of J){let z={type:"tool-call",toolCallId:Y,name:H.name,input:Q$(H.args)};Q.content.push(z),this.emit({type:"tool-call",messageId:Q.id,part:z})}let K=G.reason==="length";if(K)this.outputTruncated=!0;if(this.config.output&&W&&!G.error&&!K){let Y=YQ(this.config.output,W);if(Y.ok===!0)this.output=Y.value,Q.content.push({type:"output",value:Y.value});else this.emit({type:"error",error:Y.error})}return G}async systemPrompt(){let Q=[this.config.instructions,this.params.instructions].filter(($)=>Boolean($&&$.trim()));return Q.length>0?Q.join(`
14
14
 
15
- `):void 0}async runTools(Q,$,Z){let G=[],J=[];for(let Y of $){let W=this.config.registry.get(String(Y.name));if(!W){this.addResult(Q,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(Y.name)}".`,toolCallId:Y.toolCallId,retryable:!0}});continue}let K=W.tool.inputSchema.safeParse(Y.input);if(K.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(Y.name)}": ${K.errors.join(", ")}`,toolCallId:Y.toolCallId,retryable:!0}});continue}Y.input=K.value;let V=y9(W.tool);if(V){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(Y));continue}G.push({toolCallId:Y.toolCallId,name:Y.name,input:K.value,kind:V,signature:L9(this.claimsFor(Y.toolCallId,String(Y.name),V,K.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}J.push(this.executeTool(W,Q.id,Y,K.value,Z).then(async(X)=>{this.addResult(Q,X),await this.settleShown(Y.toolCallId)}).catch((X)=>{if(X instanceof x){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(Y));return}G.push(...X.pending);return}}))}return await T(Promise.all(J).then(()=>{return}),this.controller.signal),G}claimsFor(Q,$,Z,G){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:G,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0}}deniedByPolicy(Q){return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"refused",reason:`"${String(Q.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Q,$,Z,G,J,Y){let W=Q.tool.timeoutMs;if(W===void 0)return this.runToolBody(Q,$,Z,G,J,Y,this.controller.signal,()=>!1);let K=new AbortController,V=this.controller.signal,X=()=>K.abort(V.reason);if(V.aborted)X();else V.addEventListener("abort",X,{once:!0});let H=!1,B=this.runToolBody(Q,$,Z,G,J,Y,K.signal,()=>H),z=()=>{},U=new Promise((F)=>{z=A9(W,()=>{let D=`"${String(Z.name)}" did not finish within ${wQ(W)} (timeoutMs: ${W}) and was cancelled.`;K.abort(new DOMException(D,"TimeoutError")),F({type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"timeout",message:D,toolCallId:Z.toolCallId,retryable:!0}})})});B.catch(()=>{});try{return await Promise.race([B,U])}finally{H=!0,z()}}async runToolBody(Q,$,Z,G,J,Y,W,K){let V=this.toolFiles(Z,W),X={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:W,step:J,depth:this.depth,resumed:Y!==void 0,attachments:V.attachments,generateImage:V.generateImage,editImage:V.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,W,Y),generate:(H)=>this.generateForTool(H,W,Z.toolCallId)};try{let H=Q.tool.execute(G,X),B;if(r$(H)){let z=await H.next();while(!z.done){if(K())throw H.return(void 0).catch(()=>{}),new _;this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:z.value}),z=await H.next()}B=z.value}else B=await H;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:B}}catch(H){if(H instanceof _||this.controller.signal.aborted)throw new _;if(H instanceof x)throw H;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"tool_error",message:H instanceof Error?H.message:String(H),toolCallId:Z.toolCallId,retryable:!0}}}}async generateForTool(Q,$,Z){let G=this.controller.signal;return RQ({...Q,signal:Q.signal?AbortSignal.any([$,Q.signal]):$},{origin:{agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},toolCallId:Z},settled:(J)=>{if(this.usage=q(this.usage,J.usage),G.aborted)throw new _}})}nestedRunner(Q,$,Z,G){let J=new vQ(()=>$.nested,()=>$.nested=[]);return async(Y,W={})=>{let{at:K,recorded:V,write:X}=J.next();if(V){let H=Q3(V,Y,W);if(H)throw Error(`Nested run ${K} of "${String($.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(V.finishReason!=="awaiting-input")return{runId:V.runId,agent:V.agent,messages:V.messages,finishReason:V.finishReason??"stop",usage:V.usage??A(),output:b9(V.messages),nested:V}}return this.runNested(Q,$,Z,Y,W,X,V,G?.answers??[])}}async runNested(Q,$,Z,G,J,Y,W,K){let V=[...this.chain,G.name];if(this.chain.includes(G.name))throw Error(`"${G.name}" is already running further up this chain: ${V.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let X=this.depth+1;if(X>this.maxDepth)throw Error(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${X}: ${V.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let H=J.label,B=[...this.pathPrefix,$.toolCallId],z=this.onPending==="deny"?"deny":J.onPending??"escalate",U=W!==void 0,F=U?BQ(W.messages):new Set,D=U?K.filter((N)=>{let y=v9(N.path,B);if(y===null)return!1;return F.has(y.length>0?y[0]:N.toolCallId)}):[],L=G.stream({messages:U?W.messages:J.messages??[],turn:U?{toolResults:D}:J.prompt?{text:J.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:Z,threadId:this.params.threadId,instructions:J.instructions,maxOutputTokens:J.maxOutputTokens,temperature:J.temperature,runId:U?W.runId:void 0,nesting:{depth:X,maxDepth:this.maxDepth,chain:V,signingRunId:this.signingRunId,signingPath:B,onPending:z}}),O=[],f=(async()=>{for await(let N of L){if(N.type==="awaiting-input")O=N.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:L.runId,agent:G.name,label:H,event:N})}})(),R=(async()=>{let N=await L.result();await f;let y=U?x9(W.messages,N.messages):x9(J.messages??[],N.messages),H9={runId:L.runId,agent:G.name,label:H,messages:y,finishReason:N.finishReason,usage:U?q(W.usage??A(),N.usage):N.usage,...N.finishReason==="awaiting-input"?{signature:P9({runId:this.signingRunId,path:B,nestedRunId:L.runId,open:[...BQ(y)],input:$.input})}:{}};return Y(H9),this.usage=q(this.usage,N.usage),{result:N,record:H9}})(),C=R.then(()=>{return},()=>{return});this.nestedSettling.add(C);let v,k;try{({result:v,record:k}=await R)}finally{this.nestedSettling.delete(C)}if(this.controller.signal.aborted)throw new _;if(v.finishReason==="awaiting-input"){if(O.length===0)throw Error(`"${G.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Q,part:$,resent:!0}),new x({pending:O,path:B,nested:k})}return{runId:k.runId,agent:G.name,messages:k.messages,finishReason:v.finishReason,usage:k.usage??A(),output:v.output??b9(k.messages),...v.error?{error:v.error}:{},nested:k}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolFiles(Q,$){let Z=this.params.attachments??null,G=new vQ(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),J=()=>{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},Y=async(X,H,B)=>{let z=J(),U=H.mimeType||X.type||"",F=H.name??(X instanceof File?X.name:"attachment"),D;if(H.showModel){let O=this.config.provider;if(!O.capabilities.fileInput)throw Error(`"${String(Q.name)}" asked to show a file to ${O.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.`);D=await O.upload(new File([X],F,{type:U||void 0}))}return{attachment:await z.put(X,{name:F,mimeType:U,fileId:D}),...B?{generated:B}:{},...D?{shown:{fileId:D,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},W=(X,H,B)=>{let z=X.generated?"image":"put";if(z===H)return;throw Error(`Attachment ${B} of "${String(Q.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.`)},K=async(X,H,B)=>{let{at:z,recorded:U,write:F}=G.next();if(U&&"attachment"in U){if(W(U,"image",z),U.shown)this.queueShown(Q.toolCallId,U);return{attachment:U.attachment,size:U.generated.size,mimeType:U.attachment.mimeType,usage:U.generated.usage}}let D=await B();this.usage=q(this.usage,D.usage);let L=D.mimeType==="image/jpeg"?"jpg":"png",O=await Y(D.image,{name:H.name??`${X.name}.${L}`,mimeType:D.mimeType,...H.showModel?{showModel:!0}:{}},{size:D.size,usage:D.usage});if(F(O),O.shown)this.queueShown(Q.toolCallId,O);return{attachment:O.attachment,size:D.size,mimeType:D.mimeType,usage:D.usage}},V=async(X)=>typeof X==="string"?await J().file(X):X;return{generateImage:(X,H)=>K(X,H,()=>X.generate({...H,signal:$})),editImage:(X,H)=>K(X,H,async()=>{let{images:B,mask:z,...U}=H;return await X.edit({...U,images:await Promise.all(B.map(V)),...z?{mask:await V(z)}:{},signal:$})}),attachments:{get:(X)=>J().get(X),read:(X)=>J().read(X),file:(X)=>J().file(X),put:async(X,H={})=>{let{at:B,recorded:z,write:U}=G.next();if(z&&"attachment"in z){W(z,"put",B);let D=e$(z,X,H);if(D)throw Error(`Attachment ${B} of "${String(Q.name)}" ${D}. `+"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(Q.toolCallId,z);return z.attachment}let F=await Y(X,H);if(U(F),F.shown)this.queueShown(Q.toolCallId,F);return F.attachment}}}}toolTurn(Q){let $=this.history.findIndex((Y)=>Y.id===Q),Z=w9(this.history),G;for(let Y=$-1;Y>=0;Y--){let W=this.history[Y];if(W.role!=="user"||Z.has(W.id))continue;G=W;break}let J=[];for(let Y of G?.content??[]){if(Y.type!=="file")continue;let W=Y.attachmentId;if(typeof W!=="string"||!W.startsWith(j))continue;if(!J.includes(W))J.push(W)}return Object.freeze({attachments:Object.freeze(J)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let G=this.shownQueue.get(Q)??[];if(G.some((J)=>J.id===Z.messageId))return;G.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set(Q,G)}async settleShown(Q){let $=this.shownQueue.get(Q);if(!$||$.length===0)return;if(this.shownQueue.delete(Q),this.ended||this.controller.signal.aborted)return;for(let Z of $){if(this.history.some((G)=>G.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider(Q){let $=this.history.filter((Y)=>Y!==Q),Z=w9($),G=[];for(let Y of $){if(!Z.has(Y.id))continue;for(let W of Y.content)if(W.type==="file")G.push(W)}if(G.length<=f9)return $;let J=new Set(G.slice(0,G.length-f9));return $.map((Y)=>{if(!Y.content.some((W)=>W.type==="file"&&J.has(W)))return Y;return{...Y,content:Y.content.map((W)=>W.type==="file"&&J.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 Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let G=new Set,J=new Set,Y=new Map;for(let W of Q?.toolResults??[]){let K=`${(W.path??[]).join("/")}#${W.toolCallId}`;if(J.has(K))continue;J.add(K);let V=(z)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:W.toolCallId,retryable:!1}}),X=v9(W.path,this.pathPrefix);if(X===null){V(`The answer for "${W.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(X.length>0){let z=X[0],U=$.find((L)=>L.call.toolCallId===z);if(!U){V(`No pending tool call with id "${z}" to deliver a nested answer to.`);continue}let F=this.parkedBelow(U.call,X,W.toolCallId);if(F.ok===!1){let L=`The answer for "${W.toolCallId}" is addressed under "${z}", which`;V(F.reason==="unparked"?`${L} has no sub-agent run waiting on that question.`:F.reason==="expired"?`${L} parked a sub-agent run that has since expired. Ask again.`:`${L} carries a record of a parked sub-agent run the server did not sign.`);continue}let D=Y.get(z);if(!D){if(!q9(F.signature)){V(`The answer for "${W.toolCallId}" is addressed under "${z}", which has already been re-entered on that record. Ask again.`);continue}D=[],Y.set(z,D),G.add(z)}D.push(W);continue}let H=$.find((z)=>z.call.toolCallId===W.toolCallId);if(!H){V(`No pending tool call with id "${W.toolCallId}".`);continue}let B=await this.resolveAnswer(H,W,Z);if(B===null)continue;if(G.add(W.toolCallId),B!=="open")this.attachToHistory(H,B),await this.settleShown(W.toolCallId)}for(let[W,K]of Y){let V=$.find((H)=>H.call.toolCallId===W),X=await this.reenter(V,K,Z);if(X)this.attachToHistory(V,X),await this.settleShown(W)}for(let W of $){if(G.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(Q&&(Q.text||Q.files&&Q.files.length>0)){let G={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((J)=>({type:"file",...J.fileId?{fileId:J.fileId}:{},name:J.name,mimeType:J.mimeType,...J.attachmentId?{attachmentId:J.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(G),this.produced.push(G),await this.report(G)}return Z}parkedBelow(Q,$,Z){let G=$.length>1?$[1]:Z,J=[...this.pathPrefix,Q.toolCallId],Y=(Q.nested??[]).find((K)=>K.finishReason==="awaiting-input"&&BQ(K.messages).has(G));if(!Y)return{ok:!1,reason:"unparked"};if(typeof Y.signature!=="string")return{ok:!1,reason:"unsigned"};let W=_9(Y.signature,{path:J,nestedRunId:Y.runId,open:[...BQ(Y.messages)],input:Q.input});if(W.ok===!1)return{ok:!1,reason:W.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:Y.signature}}async reenter(Q,$,Z){let G=String(Q.call.name),J=this.config.registry.get(G);if(!J||!J.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${G}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let Y=J.tool.inputSchema.safeParse(Q.call.input);if(Y.ok===!1)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${G}": ${Y.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let W=this.amendCall(Q);W.input=Y.value;try{return await T(this.executeTool(J,Q.message.id,W,Y.value,0,{answers:$}),this.controller.signal)}catch(K){if(K instanceof x)return Z.push(...K.pending),null;throw K}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),G={...Q.call,nested:(Q.call.nested??[]).map((J)=>({...J})),...Q.call.attachments?{attachments:Q.call.attachments.map((J)=>({...J}))}:{}};if(Z>=0)$.content[Z]=G;return this.unreported.add($),G}openCalls(){let Q=new Set;for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-result")Q.add(G.toolCallId);let $=[];for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-call"&&!Q.has(G.toolCallId))$.push({message:Z,call:G});return $}async resolveAnswer(Q,$,Z){let G=Q.call,J=String(G.name),Y=this.config.registry.get(J),W=(H)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:H,toolCallId:G.toolCallId,retryable:!1}}),null};if(!Y)return W(`The tool "${J}" no longer exists, so its answer cannot be checked.`);let K=y9(Y.tool);if(!K)return W(`"${J}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return W(`The answer for "${J}" carried no signature.`);let V=XQ($.signature);if(!V)return W(`The signature for "${J}" is malformed.`);let X=N9($.signature,{...this.claimsFor(G.toolCallId,J,K,G.input),runId:V.runId});if(X.ok===!1)return W(X.reason==="expired"?`The approval for "${J}" has expired. Ask again.`:`The answer for "${J}" does not match the call the server made.`);if(!M9($.signature))return W(`The answer for "${J}" has already been used. Ask again.`);if("approve"in $){if(K!=="approval")return W(`"${J}" is answered by the client, not approved.`);if($.approve===!0){let H=this.amendCall(Q);try{return await T(this.executeTool(Y,Q.message.id,H,H.input,0),this.controller.signal)}catch(B){if(B instanceof x)return Z.push(...B.pending),"open";throw B}}return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(K==="approval")return W(`"${J}" is approved, not answered: the server produces its result.`);let H=Y.tool.outputSchema,B=H?H.safeParse($.output):{ok:!0,value:$.output};if(B.ok===!1)return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${J}" did not match its output schema: ${B.errors.join(", ")}`,toolCallId:G.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"ok",output:B.value}}return W(`The answer for "${J}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let Z=this.amend(Q.message);Z.content.push($),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:$})}amend(Q){let $=this.amended.get(Q.id);if($)return $;let Z={...Q,content:[...Q.content]},G=this.history.indexOf(Q);if(G>=0)this.history[G]=Z;return this.produced.push(Z),this.amended.set(Q.id,Z),Z}async reportDeferred(){let Q=[...this.unreported];this.unreported.clear();for(let $ of Q)await this.report($)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let $ of this.openCalls()){if($.message===this.current)continue;this.attachToHistory($,{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let Q=this.current;if(Q){let $=new Set(Q.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...Q.content]){if(Z.type!=="tool-call"||$.has(Z.toolCallId))continue;delete Z.partial,this.addResult(Q,{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 ${wQ(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 y9(Q){if(Q.answeredBy==="client")return Q.inputSchema===yQ?"question":"client";return Q.requiresApproval?"approval":null}function h9(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function $3(Q,$){return Q.descriptors($).map((Z)=>b.create({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,requiresApproval:Z.requiresApproval,execute:(G,J)=>{let Y=zQ.getStore()?.req;if(!Y)throw Error(`"${Z.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 Q.execute({kind:"local",req:Y},Z.name,G,J)}}))}function Z3(Q){if(Q==="auto")return;let $=/^(\d+)x(\d+)$/.exec(Q);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(Q)}.`);let Z=Number($[1]),G=Number($[2]);if(Z%16!==0||G%16!==0)throw Error(`Image size ${Q} is not supported: width and height must both be divisible by 16.`);if(Math.max(Z/G,G/Z)>3)throw Error(`Image size ${Q} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function p9(Q,$){if(Q.size!==void 0)try{Z3(Q.size)}catch(Z){throw Error(`${$}: ${Z.message}`)}if(Q.background==="transparent"&&Q.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(Q.compression!==void 0){let Z=Q.compression;if(!Number.isInteger(Z)||Z<0||Z>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Z}.`)}}function l9(Q,$){if(Q instanceof File)return Q;let Z=Q.type||"image/png",G=Z==="image/jpeg"?"jpg":Z.split("/")[1]??"png";return new File([Q],`${$}.${G}`,{type:Z})}class cQ{name;provider;settings;constructor(Q){let{name:$,provider:Z,...G}=Q;p9(G,`ImageModel "${$}"`),this.name=$,this.provider=Z,this.settings=G}static create(Q){return new cQ(Q)}async generate(Q){let $=this.merge(Q);return d9(await this.provider.generate({prompt:Q.prompt,...$,signal:Q.signal}))}async edit(Q){let $=this.merge(Q);return d9(await this.provider.edit({prompt:Q.prompt,...$,images:Q.images.map((Z,G)=>l9(Z,`image-${G}`)),...Q.mask?{mask:l9(Q.mask,"mask")}:{},signal:Q.signal}))}merge(Q){let $={...this.settings,...Q.size!==void 0?{size:Q.size}:{},...Q.quality!==void 0?{quality:Q.quality}:{},...Q.background!==void 0?{background:Q.background}:{},...Q.format!==void 0?{format:Q.format}:{},...Q.compression!==void 0?{compression:Q.compression}:{}};return p9($,`ImageModel "${this.name}"`),$}}function d9(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}function I(Q){return typeof process>"u"?void 0:process.env?.[Q]}var G3="preview";function i9(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function J3(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function UQ(Q,$={}){return{base:(Q.baseURL??I("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let G=Q.apiKey??I("OPENAI_API_KEY");return{...G?{authorization:`Bearer ${G}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}function Y3(Q){let $=Q.baseURL??Q.endpoint??I("AZURE_OPENAI_ENDPOINT");if($)return i9($);let Z=Q.resourceName??I("AZURE_OPENAI_RESOURCE_NAME")??I("AZURE_RESOURCE_NAME");return Z?i9(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function FQ(Q,$={}){let Z=Q.apiVersion??I("AZURE_OPENAI_API_VERSION")??G3;return{base:`${Y3(Q)}${J3(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let G=Q.apiKey??I("AZURE_OPENAI_API_KEY");return{...G?{"api-key":G}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}var W3=500,n9=20000;function X3(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let G=Date.parse(Z);if(Number.isNaN(G))return;return Math.max(0,G-$)}function o9(Q,$){let Z=Math.min(n9,W3*2**Q);return Math.round(Z*(0.5+$()*0.5))}function V3(Q){return Q===429||Q===408||Q===409||Q>=500}function K3(Q,$){return V3(Q)&&P($).retryable}function s9(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function H3(Q,$){return new Promise((Z,G)=>{let J=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(J),G(s9($))},{once:!0})})}async function s(Q,$,Z){let G=Z.fetchImpl??((H,B)=>fetch(H,B)),J=Z.sleep??H3,Y=Z.random??Math.random,W=Z.now??Date.now,K=Math.max(0,Z.maxRetries),V=async(H)=>{let B=Z.signal;if(!B)return await J(H);B.throwIfAborted();let z;try{await Promise.race([J(H,B),new Promise((U,F)=>{z=()=>F(s9(B)),B.addEventListener("abort",z,{once:!0})})])}finally{if(z)B.removeEventListener("abort",z)}},X;for(let H=0;H<=K;H++){Z.signal?.throwIfAborted();let B=new AbortController,z=()=>B.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",z,{once:!0});let U=!1,F=Z.timeoutMs>0?setTimeout(()=>{U=!0,B.abort()},Z.timeoutMs):void 0,D;try{D=await G(Q,{...$,signal:B.signal})}catch(R){if(F!==void 0)clearTimeout(F);if(Z.signal?.removeEventListener("abort",z),Z.signal?.aborted)throw R;if(X=U?new a(Z.timeoutMs):R,U&&Z.retryTimeouts===!1)throw X;if(H===K)throw X;await V(o9(H,Y));continue}if(F!==void 0)clearTimeout(F);if(D.ok)return D;Z.signal?.removeEventListener("abort",z);let L=await B3(D),O=new h(D.status,L,D.headers.get("x-request-id")??void 0);if(H===K||!K3(D.status,O))throw O;let f=X3(D.headers.get("retry-after"),W());await V(f===void 0?o9(H,Y):Math.min(f,n9)),X=O}throw X??Error("Provider request failed with no response.")}async function B3(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var mQ=300000;function pQ(Q){return{generationsUrl:`${Q.base}/images/generations${Q.query}`,editsUrl:`${Q.base}/images/edits${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}class OQ extends Error{code;retryable;constructor(Q,$={}){super(Q.message,$);this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable}}var z3={png:"image/png",jpeg:"image/jpeg"};function D3(Q){let $=Number(Q?.input_tokens??0),Z=Number(Q?.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q?.total_tokens??$+Z)},J=Q?.input_tokens_details?.image_tokens;if(typeof J==="number")G.imageInputTokens=J;let Y=Q?.output_tokens_details?.image_tokens;if(typeof Y==="number")G.imageOutputTokens=Y;return G}function U3(Q){let $=atob(Q),Z=new Uint8Array($.length);for(let G=0;G<$.length;G++)Z[G]=$.charCodeAt(G);return Z}function F3(Q){let Z=Q?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new OQ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let G=typeof Q.output_format==="string"?Q.output_format:"png";return{bytes:U3(Z),mimeType:z3[G]??`image/${G}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:D3(Q.usage)}}async function t9(Q,$,Z,G){let J;try{J=await s(Q,$,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:G.signal,fetchImpl:Z.fetchImpl})}catch(Y){if(G.signal?.aborted)throw Y;throw new OQ(P(Y),{cause:Y})}return F3(await J.json())}async function r9(Q,$,Z={}){return await t9(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},Q,Z)}async function a9(Q,$,Z={}){return await t9(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:$},Q,Z)}class LQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await r9(this.endpoint(),this.body(Q),{signal:Q.signal})}async edit(Q){let $=new FormData;for(let[Z,G]of Object.entries(this.body(Q)))if(G!==void 0)$.set(Z,String(G));for(let Z of Q.images)$.append("image[]",Z,Z.name);if(Q.mask)$.set("mask",Q.mask,Q.mask.name);return await a9(this.endpoint(),$,{signal:Q.signal})}body(Q){return{model:this.modelName(),prompt:Q.prompt,...Q.size?{size:Q.size}:{},...Q.quality?{quality:Q.quality}:{},...Q.background?{background:Q.background}:{},...Q.format?{output_format:Q.format}:{},...Q.compression!==void 0?{output_compression:Q.compression}:{}}}normalizeError(Q){return P(Q)}}var e9=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class lQ extends LQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new lQ(Q,$)}static models(){return e9}endpoint(){return pQ(UQ(this.config,{timeoutMs:mQ}))}}class dQ extends LQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new dQ(Q,$)}static models(){return e9}modelName(){return this.config.deployment??this.model}endpoint(){return pQ(FQ(this.config,{timeoutMs:mQ}))}}async function*O3(Q){let $="",Z="",G=[],J,Y=()=>{if(G.length===0&&!Z)return null;let V={event:Z,data:G.join(`
16
- `),id:J};return Z="",G=[],J=void 0,V.data?V:null},W=(V)=>{let X=V.endsWith("\r")?V.slice(0,-1):V;if(X==="")return Y();if(X.startsWith(":"))return null;let H=X.indexOf(":"),B=H===-1?X:X.slice(0,H),z=H===-1?"":X.slice(H+1);if(z.startsWith(" "))z=z.slice(1);if(B==="event")Z=z;else if(B==="data")G.push(z);else if(B==="id")J=z;return null};for await(let V of Q){$+=V;let X=$.indexOf(`
17
- `);while(X!==-1){let H=$.slice(0,X);$=$.slice(X+1);let B=W(H);if(B)yield B;X=$.indexOf(`
18
- `)}}if($.length>0){let V=W($);if(V)yield V}let K=Y();if(K)yield K}async function*Q$(Q,$={}){let Z=new Map,G=new Set,J=!1;for await(let Y of O3(Q)){if(Y.data==="[DONE]")break;let W;try{W=JSON.parse(Y.data)}catch{continue}switch(typeof W.type==="string"?W.type:Y.event){case"response.output_text.delta":{let V=String(W.delta??"");if(!V)break;yield $.structuredOutput?{type:"output-delta",delta:V}:{type:"text-delta",delta:V};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let V=String(W.delta??"");if(!V)break;yield{type:"reasoning-delta",delta:V,id:W.item_id};break}case"response.output_item.added":{let V=W.item;if(!V)break;if(V.type==="function_call"){let X=String(V.id??W.item_id??V.call_id??"");Z.set(X,{callId:String(V.call_id??X),name:String(V.name??""),namespace:typeof V.namespace==="string"&&V.namespace?V.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let V=Z.get(String(W.item_id??""));if(!V)break;let X=String(W.delta??"");if(!X)break;yield{type:"tool-call-delta",toolCallId:V.callId,name:V.name,argsDelta:X,...V.namespace?{namespace:V.namespace}:{}};break}case"response.function_call_arguments.done":{let V=String(W.item_id??""),X=Z.get(V);if(!X)break;X.done=!0,yield{type:"tool-call",toolCallId:X.callId,name:X.name,args:String(W.arguments??""),...X.namespace?{namespace:X.namespace}:{}};break}case"response.output_item.done":{let V=W.item;if(!V)break;if(V.type==="function_call"){let X=String(V.id??W.item_id??V.call_id??""),H=Z.get(X);if(H?.done)break;let B=(typeof V.namespace==="string"?V.namespace:"")||H?.namespace;if(yield{type:"tool-call",toolCallId:String(V.call_id??X),name:String(V.name??H?.name??""),args:String(V.arguments??""),...B?{namespace:B}:{}},H)H.done=!0;break}if(V.type==="tool_search_call"||V.type==="tool_search_output"){let X=L3(V);if(X.loaded.length===0&&X.namespaces.length===0)break;let H=String(V.tool_search_call_id??V.id??"");if(G.has(H))break;G.add(H),yield{type:"tool-search",...X}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(W.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{J=!0,yield{type:"finish",reason:"stop",usage:iQ(W.response?.usage)};break}case"response.incomplete":{J=!0;let V=iQ(W.response?.usage),X=W.response?.incomplete_details?.reason;if(X==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:N3(W.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:V};break}yield{type:"finish",reason:X==="max_output_tokens"?"length":"stop",usage:V};break}case"response.failed":case"error":{J=!0;let V=W.response?.error??W.error??W;yield{type:"error",error:C3(V)},yield{type:"finish",reason:"error",usage:iQ(W.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{type:"finish",reason:"error",usage:c()}}function L3(Q){let $=[],Z=[];return $$(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:oQ($),namespaces:oQ(Z)}}function $$(Q,$,Z,G){if(!Array.isArray(Q)||G>4)return;for(let J of Q){if(typeof J==="string"){$.push(J);continue}if(!J||typeof J!=="object")continue;let Y=J,W=typeof Y.name==="string"?Y.name:typeof Y.tool_name==="string"?Y.tool_name:"",K=Y.tools??Y.functions;if(Array.isArray(K)){if(W)Z.push(W);$$(K,$,Z,G+1);continue}if(W)$.push(W)}}function oQ(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function N3(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let G of Q){if(!G||typeof G!=="object")continue;let J=G,Y=J.content_filter_results;if(!Y||typeof Y!=="object")continue;for(let[W,K]of Object.entries(Y))if(K&&typeof K==="object"&&K.filtered===!0)Z.push(`${W} (${String(J.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${oQ(Z).join(", ")}.`}function C3(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",Z=String(Q?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function c(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function iQ(Q){if(!Q)return c();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},J=Q.output_tokens_details?.reasoning_tokens;if(typeof J==="number")G.reasoningTokens=J;let Y=Q.input_tokens_details?.cached_tokens;if(typeof Y==="number")G.cachedInputTokens=Y;return G}async function*Z$(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:J,value:Y}=await $.read();if(J)break;if(Y)yield Z.decode(Y,{stream:!0})}let G=Z.decode();if(G)yield G}finally{$.releaseLock()}}function nQ(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}async function*sQ(Q,$,Z){let G;try{G=await s(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(J){let Y=P(J);if(Y.code!=="aborted")yield{type:"error",error:Y,...M(J)};yield{type:"finish",reason:Y.code==="aborted"?"aborted":"error",usage:c()};return}try{yield*Q$(Z$(G.body),{structuredOutput:Z.structuredOutput})}catch(J){let Y=P(J);if(Y.code==="aborted"){yield{type:"finish",reason:"aborted",usage:c()};return}yield{type:"error",error:Y},yield{type:"finish",reason:"error",usage:c()}}}async function tQ(Q,$,Z="user_data"){let G=new FormData;G.set("purpose",Z),G.set("file",$);let Y=await(await s(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:G},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!Y?.id)throw Error("The provider accepted the upload but returned no file id.");return Y.id}function rQ(Q){let $=P3(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=_3($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:G$(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:G$(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function G$(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function P3(Q){return Q.trim().toLowerCase()}function _3(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec(Q);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function aQ(Q,$){let{capabilities:Z}=$,G={model:$.model,input:j3(Q.messages,Z),stream:!0};if(Q.systemPrompt)G.instructions=Q.systemPrompt;let J=x3(Q.tools,Z);if(J.length>0){if(G.tools=J,!Z.parallelToolCalls)G.parallel_tool_calls=!1}if(Q.output)G.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&Z.reasoning)G.reasoning=Q.reasoning==="none"?{effort:"none"}:{effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")G.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")G.max_output_tokens=Q.maxOutputTokens;return G}function j3(Q,$){let Z=[];for(let G of Q){let J=G.role,Y=[],W=()=>{if(Y.length===0)return;Z.push({type:"message",role:J,content:Y}),Y=[]};for(let K of G.content??[])switch(K.type){case"text":{if(!K.text)break;Y.push(NQ(J,K.text));break}case"output":{if(K.partial)break;Y.push(NQ(J,JSON.stringify(K.value)));break}case"file":{if(J==="assistant")break;let V=S3(K);if(!$.fileInput){if(V)Y.push(NQ(J,J$(K,!1)));break}if(K.fileId?.startsWith(j))throw Error(`FilePart.fileId holds a gemi attachment id (${K.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(!K.fileId&&!V)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(V)Y.push(NQ(J,J$(K,!!K.fileId)));if(K.fileId)Y.push(R3(K));break}case"reasoning":{W();let V=A3(K);if(V)Z.push(V);break}case"tool-call":{if(K.partial)break;W(),Z.push({type:"function_call",call_id:K.toolCallId,name:String(K.name),arguments:JSON.stringify(K.input??{})});break}case"tool-result":{W(),Z.push({type:"function_call_output",call_id:K.toolCallId,output:E3(K)});break}}W()}return q3(Z)}var M3="No result was recorded for this tool call. Assume it did not complete.";function q3(Q){let $=new Set,Z=new Set,G=[];for(let Y of Q){if(Y.type==="function_call"){let W=String(Y.call_id);if($.has(W))continue;$.add(W)}else if(Y.type==="function_call_output"){let W=String(Y.call_id);if(!$.has(W)||Z.has(W))continue;Z.add(W)}G.push(Y)}if(Z.size===$.size)return G;let J=[];for(let Y of G){if(J.push(Y),Y.type!=="function_call")continue;let W=String(Y.call_id);if(Z.has(W))continue;Z.add(W),J.push({type:"function_call_output",call_id:W,output:M3})}return J}function NQ(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function S3(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(j)?$:void 0}function J$(Q,$){let Z=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)Z.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)Z.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let G=`attachment ${Z.join(" ")}`;return $?`[${G}]`:`[${G} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function R3(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":k3(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function k3(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&T3.has($[1])}var T3=new Set(["jpeg","jpg","png","gif","webp"]);function A3(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function E3(Q){if(Q.status==="ok")return typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??null);if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function Y$(Q){return Array.isArray(Q.tools)}function x3(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let J=[];for(let Y of Q)if(Y$(Y))for(let W of Y.tools)J.push(CQ(W,!1));else J.push(CQ(Y,!1));return J}let Z=[],G=!1;for(let J of Q)if(Y$(J)){let Y=J.tools.map((W)=>{if(W.deferred)G=!0;return CQ(W,!0)});Z.push({type:"namespace",name:J.name,description:J.description,tools:Y})}else{if(J.deferred)G=!0;Z.push(CQ(J,!0))}if(G)Z.push({type:"tool_search"});return Z}function CQ(Q,$){let Z={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)Z.defer_loading=!0;return Z}class PQ{static models(){return[]}normalizeError(Q){return P(Q)}}var W$=["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 eQ extends PQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=rQ(Q),this.config=$}static model(Q,$){return new eQ(Q,$)}static models(){return W$}stream(Q){let $=aQ(Q,{model:this.model,capabilities:this.capabilities});return sQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return tQ(this.endpoint(),Q)}endpoint(){return nQ(UQ(this.config))}}class Q9 extends PQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=rQ(Q),this.config=$}static model(Q,$){return new Q9(Q,$)}static models(){return W$}stream(Q){let $=aQ(Q,{model:this.deployment(),capabilities:this.capabilities});return sQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return tQ(this.endpoint(),Q,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return nQ(FQ(this.config))}}class m extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,Z){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=Z}}class t extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class _Q{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096,this.maxAgeMs=Q.maxAgeMs===void 0?3600000:Q.maxAgeMs}register(Q,$={}){let Z={run:Q,threadId:$.threadId,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(Q.runId,Z),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);return this.scheduleExpiry(Z,$.maxRunDurationMs),this.pump(Z,$)}findByClientRunId(Q){let $=this.byClientRun.get(Q);return $&&this.runs.has($)?$:null}async find(Q){let $=this.byThread.get(Q.threadId);if(!$)return null;let Z=this.runs.get($);if(!Z)return null;return{runId:$,seq:Z.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new t(Q);if($!==void 0&&$<Z.lostBefore)throw new m(Q,$,Z.lostBefore);let G=Z.frames[0]?.seq;return this.drain(Z,Q,$??G??Z.lastSeq+1)}clear(){for(let Q of this.runs.values()){if(Q.evictAt)clearTimeout(Q.evictAt);if(Q.expireAt)clearTimeout(Q.expireAt);Q.ended=!0,this.notify(Q)}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 G of Q.run.frames()){if(Q.evicted){let Y=$.onEvent;if(Y)Z=Z.then(()=>Y(G.event)).catch((W)=>$9($,W));continue}if(Q.frames.push(G),Q.lastSeq=G.seq,Q.frames.length>this.maxFrames){let Y=Q.frames.shift();if(Y)Q.lostBefore=Y.seq+1}this.notify(Q);let J=$.onEvent;if(J)Z=Z.then(()=>J(G.event)).catch((Y)=>$9($,Y))}}catch(G){$9($,G)}finally{if(Q.ended=!0,Q.expireAt)clearTimeout(Q.expireAt),Q.expireAt=null;this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let G=Z;while(!0){let J=Q.version;for(;;){if(G<Q.lostBefore)throw new m($,G,Q.lostBefore);let Y=Q.frames,W=Y[0]?.seq;if(W===void 0)break;let K=Math.max(0,G-W);if(K>=Y.length)break;let V=Y[K];yield V,G=V.seq+1}if(Q.ended&&G>Q.lastSeq||Q.evicted)return;await this.wait(Q,J)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((Z)=>Q.wake.add(Z))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let Z of $)Z()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let Z=Q.run.runId;if(!Q.ended)Q.evicted=!0,Q.frames=[];if(this.runs.get(Z)===Q)this.runs.delete(Z);if(Q.threadId&&this.byThread.get(Q.threadId)===Z)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===Z)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}scheduleExpiry(Q,$){if(this.maxAgeMs===null||$===null)return;let Z=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Z)||Z>2147483647)return;let G=setTimeout(()=>{if(Q.expireAt=null,Q.ended)return;try{Q.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(Q)},Z);G.unref?.(),Q.expireAt=G}}var Z9=new _Q;function $9(Q,$){try{Q.onInternalError?.($)}catch{}}class jQ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??86400000,this.clientOwnedIds=Q.clientOwnedIds??!1}async createThread(Q){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(Q){this.sweep();let $=this.threads.get(Q);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set(Q,Z)}for(let G of $){let J=Z.messages.findIndex((Y)=>Y.id===G.id);if(J===-1)Z.messages.push(G);else Z.messages[J]=G}Z.touchedAt=Date.now()}delete(Q){this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<60000)return;this.lastSweep=Q;for(let[$,Z]of this.threads)if(Q-Z.touchedAt>this.ttlMs)this.threads.delete($)}}var G9=new jQ;function H$(Q={}){return{messages:Q.messages?[...Q.messages]:[],pending:Q.pending?[...Q.pending]:[],error:null,threadId:Q.threadId,seq:Q.seq??-1,cursorRunId:Q.cursorRunId,runMessageIds:[],loadedTools:[]}}function B$(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...z$(Q,$.event,Z),seq:$.seq}}function z$(Q,$,Z){switch($.type){case"run-start":return{...Q,runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0};case"message-start":return w(Q,$.messageId,Z,(G)=>({...G,role:$.role}));case"text-delta":if(V$(Q,$.messageId))return Q;return w(Q,$.messageId,Z,(G)=>({...G,content:y3(G.content,$.delta)}));case"reasoning-delta":if(V$(Q,$.messageId))return Q;return w(Q,$.messageId,Z,(G)=>({...G,content:h3(G.content,$.delta,$.id)}));case"output-delta":return w(Q,$.messageId,Z,(G)=>({...G,content:K$(G.content,{type:"output",value:$.snapshot,partial:!0},(J)=>J.type==="output")}));case"tool-call":return w(Q,$.messageId,Z,(G)=>{let J=G.content.findIndex((B)=>B.type==="tool-call"&&B.toolCallId===$.part.toolCallId),Y=J===-1?void 0:G.content[J],W=$.part.progress??Y?.progress,K=$.part.nested??Y?.nested,V=$.part.attachments??Y?.attachments,X={...$.part,...W?{progress:W}:{},...K?{nested:K}:{},...V?{attachments:V}:{}},H=G.content.slice();if(J===-1)H.push(X);else H[J]=X;return{...G,content:H}});case"tool-search":{let G=$.loaded.filter((J)=>!Q.loadedTools.includes(J));if(G.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...G]}}case"tool-progress":return X$(Q,$.toolCallId,(G)=>({...G,progress:[...G.progress??[],$.data]}));case"nested-event":{let G=$;return X$(Q,$.toolCallId,(J)=>{let Y=J.nested??[],W=Y.findIndex((H)=>H.runId===G.runId),K=Y[W]??{runId:G.runId,agent:G.agent,messages:[]},V=w3(K,G,Z),X=W===-1?[...Y,V]:Y.map((H,B)=>B===W?V:H);return{...J,nested:X}})}case"tool-result":{let G=w(Q,$.messageId,Z,(J)=>({...J,content:K$(J.content,$.part,(Y)=>Y.type==="tool-result"&&Y.toolCallId===$.part.toolCallId)}));return{...G,pending:G.pending.filter((J)=>J.toolCallId!==$.part.toolCallId)}}case"message":{let G=Q.messages.findIndex((W)=>W.id===$.message.id),J=Q.messages.slice();if(G===-1)J.push($.message);else J[G]=$.message;let Y=Q.runMessageIds.includes($.message.id)?Q.runMessageIds:[...Q.runMessageIds,$.message.id];return{...Q,messages:J,runMessageIds:Y}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return w(Q,$.messageId,Z,(G)=>({...G,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},content:$.outputTruncated||$.finishReason==="length"?G.content.filter((J)=>!(J.type==="output"&&J.partial)):G.content.map((J)=>J.type==="output"&&J.partial?{...J,partial:!1}:J)}));case"usage":{let G=v3(Q.messages,(Y)=>Y.role==="assistant");if(G===-1)return Q;let J=Q.messages.slice();return J[G]={...J[G],usage:$.usage},{...Q,messages:J}}case"error":return{...Q,error:$.error,pending:[]};case"run-end":return{...Q,runId:void 0,finishReason:$.finishReason,messages:D$(Q,$.finishReason)};default:return Q}}function D$(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?b3(Z,$):Z)}function b3(Q,$){let Z=Q.content.map((J)=>J.type==="tool-call"&&J.nested?.some((Y)=>Y.finishReason===void 0)?{...J,nested:J.nested.map((Y)=>Y.finishReason===void 0?I3(Y,$):Y)}:J);if(Q.finishReason===void 0)return{...Q,finishReason:$,content:Z};return Z.some((J,Y)=>J!==Q.content[Y])?{...Q,content:Z}:Q}function I3(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((G)=>G.id),loadedTools:[]};return{...Q,finishReason:$,messages:D$(Z,$)}}function X$(Q,$,Z){for(let G=Q.messages.length-1;G>=0;G--){let J=Q.messages[G],Y=J.content.findIndex((X)=>X.type==="tool-call"&&X.toolCallId===$);if(Y===-1)continue;if(J.finishReason!==void 0&&!f3(Q,J,$))return Q;let W=J.content.slice();W[Y]=Z(W[Y]);let K=Q.messages.slice();K[G]={...J,content:W};let V=Q.runMessageIds.includes(J.id)?Q.runMessageIds:[...Q.runMessageIds,J.id];return{...Q,runMessageIds:V,messages:K}}return Q}function w3(Q,$,Z){let G={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((Y)=>Y.id),loadedTools:[],finishReason:Q.finishReason},J=z$(G,$.event,Z);return{...Q,...$.label!==void 0?{label:$.label}:{},messages:J.messages,...J.finishReason!==void 0?{finishReason:J.finishReason}:{},...$.event.type==="usage"?{usage:$.event.usage}:{}}}function f3(Q,$,Z){if($.finishReason!=="awaiting-input")return!1;return!Q.messages.some((G)=>G.content.some((J)=>J.type==="tool-result"&&J.toolCallId===Z))}function V$(Q,$){let Z=Q.messages.find((G)=>G.id===$);return Z!==void 0&&Z.finishReason!==void 0}function v3(Q,$){for(let Z=Q.length-1;Z>=0;Z--)if($(Q[Z]))return Z;return-1}function w(Q,$,Z,G){let J=Q.messages.findIndex((K)=>K.id===$),Y=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(J===-1){let K={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:Y,messages:[...Q.messages,G(K)]}}let W=Q.messages.slice();return W[J]=G(W[J]),{...Q,runMessageIds:Y,messages:W}}function y3(Q,$){let Z=Q[Q.length-1];if(Z&&Z.type==="text")return[...Q.slice(0,-1),{type:"text",text:Z.text+$}];return[...Q,{type:"text",text:$}]}function h3(Q,$,Z){let G=Q[Q.length-1];if(G&&G.type==="reasoning"&&G.id===Z)return[...Q.slice(0,-1),{...G,text:(G.text??"")+$}];return[...Q,Z?{type:"reasoning",id:Z,text:$}:{type:"reasoning",text:$}]}function K$(Q,$,Z){let G=Q.findIndex(Z);if(G===-1)return[...Q,$];let J=Q.slice();return J[G]=$,J}class Y9{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(Q,$,Z,G){this.store=Q;this.threadId=$;this.report=G;this.state=H$({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[J9(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=B$(this.state,Q),$.type){case"message":this.write(()=>[J9($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(Q=[]){this.closed=!0;for(let $ of Q)this.done.add($.id)}settled(){return this.chain}checkpoint(Q){if(this.done.has(Q))return;let $=this.state.messages.find((G)=>G.id===Q);if(!$)return;let Z=this.runId;this.write(()=>{let G=J9($);if(G.finishReason===void 0&&Z)G.runId=Z;return[G]})}write(Q){let $;try{$=Q()}catch(Z){this.report(Z);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Z)=>this.report(Z))}}function J9(Q){return structuredClone(Q)}async function U$(Q,$){let Z=[],G=null,J=Q.slice();for(let Y=0;Y<J.length;Y++){let W=J[Y];if(W.role!=="assistant"||W.finishReason!==void 0)continue;if(W.runId&&await $(W.runId))continue;G??=new Set(Q.flatMap((X)=>X.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let K=W.content.map((X)=>X.type==="tool-call"?F$(X):X);for(let X of W.content){if(X.type!=="tool-call"||G.has(X.toolCallId))continue;let H={type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"denied",cause:"interrupted"};K.push(H)}let V={...W,content:K,finishReason:"interrupted"};J[Y]=V,Z.push(V)}return{messages:J,settled:Z}}function F$(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((G)=>G.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(u3)}}function u3(Q){if(Q.finishReason!==void 0)return Q;return{...Q,finishReason:"interrupted",messages:Q.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Z)=>Z.type==="tool-call"?F$(Z):Z)}:$)}}var g3=P$,MQ=new Map,O$=new WeakMap,qQ=new Map;class j$ extends g3{static kind="agent-controller";store=G9;liveRuns=Z9;attachments=HQ;attachmentStorage=_$;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;authorizeRequest(Q,$){}async stream(Q=new r){let $=await W9(Q);if($.error)return SQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:void 0,J=d3(Z);if(J.error)return SQ({body:{},error:J.error});let Y=J.turn,W=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,K=M$(Z);if(this.requireThread&&!G)return S(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});let V=W?{cancelled:!1}:null;if(V)qQ.set(W,V);let X=async()=>{let H;if(G){let C=await this.store.loadThread(G);if(!C)return S(404,{code:"thread_not_found",message:`Thread ${G} does not exist here, or has expired.`});H=await this.settleThread(G,C,{write:!0})}else H=Array.isArray(Z.messages)?Z.messages:[];let B=await this.instructions(Q,{body:K})||void 0,z=await this.context(Q,{body:K}),U=await this.attachmentsFor(Q,G,{body:K});if(V?.cancelled)return N$();let F=G?new Y9(this.store,G,H,(C)=>this.reportHookFailure(C)):null,D=this.agent.stream({messages:H,turn:Y,threadId:G,...F?{onMessage:(C)=>F.finish(C)}:{},instructions:B,context:z,attachments:U,body:K}),L={req:Q,runId:D.runId,threadId:G},O=this.liveRuns.register(D,{threadId:G,clientRunId:W,onEvent:(C)=>this.dispatchEvent(C,L),onInternalError:(C)=>this.reportHookFailure(C),maxRunDurationMs:this.agent.maxRunDurationMs});if(F)this.follow(D,F);let{stored:f,hooks:R}=this.persistRun(D,L,O,F);return O$.set(D,f),Q.ctx?.()?.waitUntil(R),D.toResponse()};try{if(await this.authorizeRequest(Q,{route:"stream",threadId:G,body:K}),V?.cancelled)return N$();return G?await this.withThread(G,X):await X()}finally{if(V&&qQ.get(W)===V)qQ.delete(W)}}async withThread(Q,$){let Z=MQ.get(Q)??Promise.resolve(),G,J=new Promise((W)=>{G=W}),Y=Z.then(()=>J);MQ.set(Q,Y),await Z;try{let W=await this.liveRuns.find({threadId:Q}),K=W?this.liveRuns.get(W.runId):null;if(K)K.stop({reason:"superseded by a later turn on this thread"}),await O$.get(K);return await $()}finally{if(G(),MQ.get(Q)===Y)MQ.delete(Q)}}async attach(Q=new r){let $=await W9(Q);if($.error)return SQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:n3(Q,"threadId");if(!G)return S(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:G});let J=await this.liveRuns.find({threadId:G});if(!J)return S(404,{code:"no_live_run",message:`No run in progress for thread ${G} in this process.`});let Y=typeof Z.runId==="string"?Z.runId:void 0,W=Y&&Y!==J.runId?void 0:o3(Q,Z);try{return k9(this.liveRuns.replay(J.runId,W))}catch(K){if(K instanceof m)return S(410,{code:K.code,message:K.message,oldestSeq:K.oldest});if(K instanceof t)return S(404,{code:K.code,message:K.message});throw K}}async stop(Q=new r){let $=await W9(Q);if($.error)return SQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let 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 Y=qQ.get(Z.clientRunId);if(Y)return Y.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};return J.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$,Z){let G=Q.ctx()?.user,J=G?.id??G?.publicId;if(J!==void 0&&J!==null&&String(J)!=="")return{key:`user:${String(J)}`};if($)return{key:`thread:${$}`};return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$,Z={body:{}}){let G=await this.attachmentScope(Q,$,Z);if(!G)return null;return new o(this.attachments,this.attachmentStorage,G)}async upload(Q=new r){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let G=Z instanceof File&&Z.name?Z.name:"upload",J=Z.type||"application/octet-stream",Y=m3($.get("body")),W=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof W==="string"&&W.length>0?W:void 0,body:Y});let K=typeof W==="string"&&W.length>0&&await this.store.loadThread(W)!==null?W:void 0,V=await this.attachmentDestination(Z,Q),X=s3(V,$.get("destination")),H=await this.attachmentScope(Q,K,{body:Y}),B=X!=="provider"&&!H;if(B){if(X==="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()`.');t3()}if(X==="provider"||!H){let O={fileId:await L$(this.agent.provider,Z),name:G,mimeType:J,size:Z.size,destination:"provider"};if(B)O.downgraded="no_scope";return O}let z=EQ(),U=await this.attachmentStorage.put({name:xQ(z,G),body:Z,contentType:J}),F=X==="both"?await L$(this.agent.provider,Z):void 0,D={id:z,scopeKey:H.key,fileId:F,objectName:U,name:G,mimeType:J,size:Z.size,createdAt:new Date().toISOString(),destination:X};return await this.attachments.put(H,D),{fileId:F,attachmentId:z,name:G,mimeType:J,size:Z.size,destination:X}}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}onError(Q,$){}onStreamComplete(Q,$){}reportHookFailure(Q){console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,$){switch(Q.type){case"tool-call":if(!Q.part.partial&&!Q.resent)await this.onToolCall({toolCallId:Q.part.toolCallId,name:String(Q.part.name),input:Q.part.input},$);return;case"awaiting-input":await this.onAwaitingInput(Q.pending,$);return;case"error":await this.onError(Q.error,$);return;default:return}}async readThread(Q){let $=await this.store.loadThread(Q);return $?await this.settleThread(Q,$,{write:!1}):null}isRunLive(Q,$){return this.liveRuns.get(Q)!==null}async settleThread(Q,$,{write:Z}){let{messages:G,settled:J}=await U$($,(Y)=>this.isRunLive(Y,Q));if(Z&&J.length>0)try{await this.store.appendMessages(Q,J)}catch(Y){this.reportHookFailure(Y)}return G}follow(Q,$){(async()=>{try{for await(let Z of Q.frames())$.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun(Q,$,Z,G=null){let J=Promise.resolve(),Y=(async()=>{let K;try{K=await Q.result()}catch(X){G?.close(),await G?.settled(),J=this.safely(()=>this.onError({code:"unknown",message:X instanceof Error?X.message:String(X),retryable:!1},$));return}let V=K.messages;if(G?.close(V),await G?.settled(),$.threadId&&V.length>0)try{await this.store.appendMessages($.threadId,V)}catch(X){this.reportHookFailure(X)}J=this.notifyRun(K,V,$)})(),W=Y.then(()=>a3(Promise.all([J,Z]).then(()=>{}),this.hookHoldMs));return{stored:Y,hooks:W}}async notifyRun(Q,$,Z){for(let G of $)await this.safely(()=>this.onMessage(G,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}var X9=["turn","clientRunId","threadId","messages"],c3=["text","files","toolResults"];function M$(Q,$=S$(Q)?X9:[...X9,...c3]){let Z={};for(let[G,J]of Object.entries(Q)){if($.includes(G))continue;Object.defineProperty(Z,G,{value:J,writable:!0,enumerable:!0,configurable:!0})}return Z}function m3(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new V9("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new V9("The upload's `body` field must be a JSON object.");return M$($,X9)}class V9 extends K9{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function L$(Q,$){try{return await Q.upload($)}catch(Z){if(Z instanceof h&&p3.has(Z.status))throw new q$(P(Z).message);throw Z}}var p3=new Set([400,413,415,422]);class q$ extends K9{constructor(Q){super(Q);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(Q)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}async function W9(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!l3($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z;try{Z=await $.text()}catch{return{body:{},error:"The request body could not be read."}}if(!Z.trim())return{body:{}};let G;try{G=JSON.parse(Z)}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 l3(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function SQ(Q){return S(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function S$(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function d3(Q){let $=S$(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let G=i3($.files);if(typeof G==="string")return{error:G};Z.files=G}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function i3(Q){let $=[];for(let[Z,G]of Q.entries()){let J=`turn.files[${Z}]`;if(!G||typeof G!=="object"||Array.isArray(G))return`${J} must be an object.`;let Y={};for(let H of["fileId","attachmentId","name","mimeType"]){let B=G[H];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${J}.${H} must be a string.`;Y[H]=B}let{fileId:W,attachmentId:K,name:V,mimeType:X}=Y;if(W?.startsWith(j))return`${J}.fileId holds a gemi attachment id (${W}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(K!==void 0&&!K.startsWith(j))return`${J}.attachmentId is not a gemi attachment id: it must start with "${j}".`;if(!W&&!K)return`${J} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...W?{fileId:W}:{},...K?{attachmentId:K}:{},...V!==void 0?{name:V}:{},...X!==void 0?{mimeType:X}:{}})}return $}function o3(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let G=Math.floor($.cursor);if(G>=0)return G+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let G=Number.parseInt(Z,10);if(Number.isFinite(G))return Math.max(0,G+1)}return}function n3(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function N$(){return S(409,{code:"stopped",message:"The turn was stopped before it started."})}function S(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function s3(Q,$){if(typeof $!=="string"||$.length===0)return Q;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===Q||Q==="both"&&$==="storage")return $;if(Q==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${Q}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var C$=!1;function t3(){if(C$)return;C$=!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 r3=2147483647;function a3(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=r3))return Z;let G,J=new Promise((Y)=>{G=setTimeout(Y,$)});return Promise.race([Z,J]).finally(()=>clearTimeout(G))}export{$3 as toAgentTools,p as supportsStrict,e3 as s,Z9 as liveRuns,x$ as generate,HQ as defaultAttachmentStore,G9 as defaultAgentStore,DQ as ToolNamespace,hQ as Skill,o as ScopedAttachments,n as SKILLS_NAMESPACE,x as PendingEscalation,eQ as OpenAIProvider,lQ as OpenAIImageProvider,_Q as MemoryLiveRuns,KQ as MemoryAttachmentStore,jQ as MemoryAgentStore,t as LiveRunNotFoundError,g as InvalidAttachmentScopeError,OQ as ImageRequestError,LQ as ImageProvider,cQ as ImageModel,m as FrameCursorEvictedError,uQ as DEFAULT_MAX_RUN_DURATION_MS,Q9 as AzureOpenAIProvider,dQ as AzureOpenAIImageProvider,i as AttachmentNotFoundError,b as AgentTool,d as AgentRunError,PQ as AgentProvider,j$ as AgentController,gQ as Agent};
15
+ `):void 0}async runTools(Q,$,Z){let G=[],J=[];for(let W of $){let V=this.config.registry.get(String(W.name));if(!V){this.addResult(Q,{type:"tool-result",toolCallId:W.toolCallId,name:W.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(W.name)}".`,toolCallId:W.toolCallId,retryable:!0}});continue}let X=V.tool.inputSchema.safeParse(W.input);if(X.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:W.toolCallId,name:W.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(W.name)}": ${X.errors.join(", ")}`,toolCallId:W.toolCallId,retryable:!0}});continue}W.input=X.value;let K=e9(V.tool);if(K){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(W));continue}G.push({toolCallId:W.toolCallId,name:W.name,input:X.value,kind:K,signature:v9(this.claimsFor(W.toolCallId,String(W.name),K,X.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}J.push(this.executeTool(V,Q.id,W,X.value,Z).then(async(Y)=>{this.addResult(Q,Y),await this.settleShown(W.toolCallId)}).catch((Y)=>{if(Y instanceof h){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(W));return}G.push(...Y.pending);return}}))}return await v(Promise.all(J).then(()=>{return}),this.controller.signal),G}claimsFor(Q,$,Z,G){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:G,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0}}deniedByPolicy(Q){return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"refused",reason:`"${String(Q.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Q,$,Z,G,J,W){let V=Q.tool.timeoutMs;if(V===void 0)return this.runToolBody(Q,$,Z,G,J,W,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,z=this.runToolBody(Q,$,Z,G,J,W,X.signal,()=>H),B=()=>{},U=new Promise((F)=>{B=i9(V,()=>{let D=`"${String(Z.name)}" did not finish within ${iQ(V)} (timeoutMs: ${V}) and was cancelled.`;X.abort(new DOMException(D,"TimeoutError")),F({type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"timeout",message:D,toolCallId:Z.toolCallId,retryable:!0}})})});z.catch(()=>{});try{return await Promise.race([z,U])}finally{H=!0,B()}}async runToolBody(Q,$,Z,G,J,W,V,X){let K=this.toolFiles(Z,V),Y={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:V,step:J,depth:this.depth,resumed:W!==void 0,attachments:K.attachments,generateImage:K.generateImage,editImage:K.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,V,W),generate:(H)=>this.generateForTool(H,V,Z.toolCallId)};try{let H=Q.tool.execute(G,Y),z;if(E3(H)){let B=await H.next();while(!B.done){if(X())throw H.return(void 0).catch(()=>{}),new S;this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:B.value}),B=await H.next()}z=B.value}else z=await H;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:z}}catch(H){if(H instanceof S||this.controller.signal.aborted)throw new S;if(H instanceof h)throw H;let z=H instanceof j;if(!z&&this.config.logErrors)this.logToolFailure(Z,H);let B={code:"tool_error",message:H instanceof Error?H.message:String(H),toolCallId:Z.toolCallId,retryable:z?H.retryable:!0};return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:this.redact(B,{source:"tool",toolName:String(Z.name),cause:H})}}}async generateForTool(Q,$,Z){let G=this.controller.signal;return fQ({...Q,signal:Q.signal?AbortSignal.any([$,Q.signal]):$},{origin:{agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},toolCallId:Z},settled:(J)=>{if(this.usage=E(this.usage,J.usage),G.aborted)throw new S}})}nestedRunner(Q,$,Z,G){let J=new nQ(()=>$.nested,()=>$.nested=[]);return async(W,V={})=>{let{at:X,recorded:K,write:Y}=J.next();if(K){let H=w3(K,W,V);if(H)throw new j(`Nested run ${X} of "${String($.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??I(),output:s9(K.messages),nested:K}}return this.runNested(Q,$,Z,W,V,Y,K,G?.answers??[])}}async runNested(Q,$,Z,G,J,W,V,X){let K=[...this.chain,G.name];if(this.chain.includes(G.name))throw new j(`"${G.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=J.label,z=[...this.pathPrefix,$.toolCallId],B=this.onPending==="deny"?"deny":J.onPending??"escalate",U=V!==void 0,F=U?CQ(V.messages):new Set,D=U?X.filter((O)=>{let b=r9(O.path,z);if(b===null)return!1;return F.has(b.length>0?b[0]:O.toolCallId)}):[],C=G.stream({messages:U?V.messages:J.messages??[],turn:U?{toolResults:D}:J.prompt?{text:J.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,instructions:J.instructions,maxOutputTokens:J.maxOutputTokens,temperature:J.temperature,runId:U?V.runId:void 0,nesting:{depth:Y,maxDepth:this.maxDepth,chain:K,signingRunId:this.signingRunId,signingPath:z,onPending:B}}),L=[],R=(async()=>{for await(let O of C){if(O.type==="awaiting-input")L=O.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:C.runId,agent:G.name,label:H,event:O})}})(),P=(async()=>{let O=await C.result();await R;let b=U?n9(V.messages,O.messages):n9(J.messages??[],O.messages),JQ={runId:C.runId,agent:G.name,label:H,messages:b,finishReason:O.finishReason,usage:U?E(V.usage??I(),O.usage):O.usage,...O.finishReason==="awaiting-input"?{signature:y9({runId:this.signingRunId,path:z,nestedRunId:C.runId,open:[...CQ(b)],input:$.input})}:{}};return W(JQ),this.usage=E(this.usage,O.usage),{result:O,record:JQ}})(),x=P.then(()=>{return},()=>{return});this.nestedSettling.add(x);let k,N;try{({result:k,record:N}=await P)}finally{this.nestedSettling.delete(x)}if(this.controller.signal.aborted)throw new S;if(k.finishReason==="awaiting-input"){if(L.length===0)throw new j(`"${G.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Q,part:$,resent:!0}),new h({pending:L,path:z,nested:N})}return{runId:N.runId,agent:G.name,messages:N.messages,finishReason:k.finishReason,usage:N.usage??I(),output:k.output??s9(N.messages),...k.error?{error:k.error}:{},nested:N}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolFiles(Q,$){let Z=this.params.attachments??null,G=new nQ(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),J=()=>{if(!Z)throw new m("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},W=async(Y,H,z)=>{let B=J(),U=H.mimeType||Y.type||"",F=H.name??(Y instanceof File?Y.name:"attachment"),D;if(H.showModel){let L=this.config.provider;if(!L.capabilities.fileInput)throw new j(`"${String(Q.name)}" asked to show a file to ${L.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.`);D=await L.upload(new File([Y],F,{type:U||void 0}))}return{attachment:await B.put(Y,{name:F,mimeType:U,fileId:D}),...z?{generated:z}:{},...D?{shown:{fileId:D,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},V=(Y,H,z)=>{let B=Y.generated?"image":"put";if(B===H)return;throw new j(`Attachment ${z} of "${String(Q.name)}" was ${B==="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,z)=>{let{at:B,recorded:U,write:F}=G.next();if(U&&"attachment"in U){if(V(U,"image",B),U.shown)this.queueShown(Q.toolCallId,U);return{attachment:U.attachment,size:U.generated.size,mimeType:U.attachment.mimeType,usage:U.generated.usage}}let D=await z();this.usage=E(this.usage,D.usage);let C=D.mimeType==="image/jpeg"?"jpg":"png",L=await W(D.image,{name:H.name??`${Y.name}.${C}`,mimeType:D.mimeType,...H.showModel?{showModel:!0}:{}},{size:D.size,usage:D.usage});if(F(L),L.shown)this.queueShown(Q.toolCallId,L);return{attachment:L.attachment,size:D.size,mimeType:D.mimeType,usage:D.usage}},K=async(Y)=>typeof Y==="string"?await J().file(Y):Y;return{generateImage:(Y,H)=>X(Y,H,()=>Y.generate({...H,signal:$})),editImage:(Y,H)=>X(Y,H,async()=>{let{images:z,mask:B,...U}=H;return await Y.edit({...U,images:await Promise.all(z.map(K)),...B?{mask:await K(B)}:{},signal:$})}),attachments:{get:(Y)=>J().get(Y),read:(Y)=>J().read(Y),file:(Y)=>J().file(Y),put:async(Y,H={})=>{let{at:z,recorded:B,write:U}=G.next();if(B&&"attachment"in B){V(B,"put",z);let D=b3(B,Y,H);if(D)throw new j(`Attachment ${z} of "${String(Q.name)}" ${D}. `+"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(B.shown)this.queueShown(Q.toolCallId,B);return B.attachment}let F=await W(Y,H);if(U(F),F.shown)this.queueShown(Q.toolCallId,F);return F.attachment}}}}toolTurn(Q){let $=this.history.findIndex((W)=>W.id===Q),Z=OQ(this.history),G;for(let W=$-1;W>=0;W--){let V=this.history[W];if(V.role!=="user"||Z.has(V.id))continue;G=V;break}let J=[];for(let W of G?.content??[]){if(W.type!=="file")continue;let V=W.attachmentId;if(typeof V!=="string"||!V.startsWith(A))continue;if(!J.includes(V))J.push(V)}return Object.freeze({attachments:Object.freeze(J)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let G=this.shownQueue.get(Q)??[];if(G.some((J)=>J.id===Z.messageId))return;G.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set(Q,G)}async settleShown(Q){let $=this.shownQueue.get(Q);if(!$||$.length===0)return;if(this.shownQueue.delete(Q),this.ended||this.controller.signal.aborted)return;for(let Z of $){if(this.history.some((G)=>G.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider(Q){let $=this.history.filter((W)=>W!==Q),Z=OQ($),G=[];for(let W of $){if(!Z.has(W.id))continue;for(let V of W.content)if(V.type==="file")G.push(V)}if(G.length<=a9)return $;let J=new Set(G.slice(0,G.length-a9));return $.map((W)=>{if(!W.content.some((V)=>V.type==="file"&&J.has(V)))return W;return{...W,content:W.content.map((V)=>V.type==="file"&&J.has(V)?{type:"text",text:`[A ${V.mimeType||"file"} produced by a tool (attachment ${V.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.]`}:V)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let G=new Set,J=new Set,W=new Map;for(let V of Q?.toolResults??[]){let X=`${(V.path??[]).join("/")}#${V.toolCallId}`;if(J.has(X))continue;J.add(X);let K=(B)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:B,toolCallId:V.toolCallId,retryable:!1}}),Y=r9(V.path,this.pathPrefix);if(Y===null){K(`The answer for "${V.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(Y.length>0){let B=Y[0],U=$.find((C)=>C.call.toolCallId===B);if(!U){K(`No pending tool call with id "${B}" to deliver a nested answer to.`);continue}let F=this.parkedBelow(U.call,Y,V.toolCallId);if(F.ok===!1){let C=`The answer for "${V.toolCallId}" is addressed under "${B}", which`;K(F.reason==="unparked"?`${C} has no sub-agent run waiting on that question.`:F.reason==="expired"?`${C} parked a sub-agent run that has since expired. Ask again.`:`${C} carries a record of a parked sub-agent run the server did not sign.`);continue}let D=W.get(B);if(!D){if(!await this.spend(c9,F.signature)){K(`The answer for "${V.toolCallId}" is addressed under "${B}", which has already been re-entered on that record. Ask again.`);continue}D=[],W.set(B,D),G.add(B)}D.push(V);continue}let H=$.find((B)=>B.call.toolCallId===V.toolCallId);if(!H){K(`No pending tool call with id "${V.toolCallId}".`);continue}let z=await this.resolveAnswer(H,V,Z);if(z===null)continue;if(G.add(V.toolCallId),z!=="open")this.attachToHistory(H,z),await this.settleShown(V.toolCallId)}for(let[V,X]of W){let K=$.find((H)=>H.call.toolCallId===V),Y=await this.reenter(K,X,Z);if(Y)this.attachToHistory(K,Y),await this.settleShown(V)}for(let V of $){if(G.has(V.call.toolCallId))continue;this.attachToHistory(V,{type:"tool-result",toolCallId:V.call.toolCallId,name:V.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if(Q&&(Q.text||Q.files&&Q.files.length>0)){let G={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((J)=>({type:"file",...J.fileId?{fileId:J.fileId}:{},name:J.name,mimeType:J.mimeType,...J.attachmentId?{attachmentId:J.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(G),this.produced.push(G),await this.report(G)}return Z}parkedBelow(Q,$,Z){let G=$.length>1?$[1]:Z,J=[...this.pathPrefix,Q.toolCallId],W=(Q.nested??[]).find((X)=>X.finishReason==="awaiting-input"&&CQ(X.messages).has(G));if(!W)return{ok:!1,reason:"unparked"};if(typeof W.signature!=="string")return{ok:!1,reason:"unsigned"};let V=g9(W.signature,{path:J,nestedRunId:W.runId,open:[...CQ(W.messages)],input:Q.input});if(V.ok===!1)return{ok:!1,reason:V.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:W.signature}}async reenter(Q,$,Z){let G=String(Q.call.name),J=this.config.registry.get(G);if(!J||!J.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${G}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let W=J.tool.inputSchema.safeParse(Q.call.input);if(W.ok===!1)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${G}": ${W.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let V=this.amendCall(Q);V.input=W.value;try{return await v(this.executeTool(J,Q.message.id,V,W.value,0,{answers:$}),this.controller.signal)}catch(X){if(X instanceof h)return Z.push(...X.pending),null;throw X}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),G={...Q.call,nested:(Q.call.nested??[]).map((J)=>({...J})),...Q.call.attachments?{attachments:Q.call.attachments.map((J)=>({...J}))}:{}};if(Z>=0)$.content[Z]=G;return this.unreported.add($),G}openCalls(){let Q=new Set;for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-result")Q.add(G.toolCallId);let $=[];for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-call"&&!Q.has(G.toolCallId))$.push({message:Z,call:G});return $}async spend(Q,$){try{return await Q($,this.params.nonces??p)}catch(Z){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not spend a nonce`,{error:Z}),!1}}async resolveAnswer(Q,$,Z){let G=Q.call,J=String(G.name),W=this.config.registry.get(J),V=(H)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:H,toolCallId:G.toolCallId,retryable:!1}}),null};if(!W)return V(`The tool "${J}" no longer exists, so its answer cannot be checked.`);let X=e9(W.tool);if(!X)return V(`"${J}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return V(`The answer for "${J}" carried no signature.`);let K=DQ($.signature);if(!K)return V(`The signature for "${J}" is malformed.`);let Y=f9($.signature,{...this.claimsFor(G.toolCallId,J,X,G.input),runId:K.runId});if(Y.ok===!1)return V(Y.reason==="expired"?`The approval for "${J}" has expired. Ask again.`:`The answer for "${J}" does not match the call the server made.`);if(!await this.spend(u9,$.signature))return V(`The answer for "${J}" has already been used. Ask again.`);if("approve"in $){if(X!=="approval")return V(`"${J}" is answered by the client, not approved.`);if($.approve===!0){let H=this.amendCall(Q);try{return await v(this.executeTool(W,Q.message.id,H,H.input,0),this.controller.signal)}catch(z){if(z instanceof h)return Z.push(...z.pending),"open";throw z}}return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(X==="approval")return V(`"${J}" is approved, not answered: the server produces its result.`);let H=W.tool.outputSchema,z=H?H.safeParse($.output):{ok:!0,value:$.output};if(z.ok===!1)return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${J}" did not match its output schema: ${z.errors.join(", ")}`,toolCallId:G.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"ok",output:z.value}}return V(`The answer for "${J}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let Z=this.amend(Q.message);Z.content.push($),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:$})}markFileRejected(Q,$,Z){for(let V of this.history){if(!V.content.some((Y)=>Y.type==="file"&&Y.fileId===Q&&!Y.providerRejected))continue;let K=this.produced.includes(V)?V:this.amend(V);if(K.content=K.content.map((Y)=>Y.type==="file"&&Y.fileId===Q&&!Y.providerRejected?{...Y,providerRejected:!0}:Y),K!==this.current)this.unreported.add(K)}if(!this.config.logErrors)return;let G=`[gemi/ai] agent "${this.config.name}": the provider refused file ${Q}${Z.status!==void 0?` (${Z.status})`:""}; it was left out of the request and will not be sent again: ${$}`,J={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},fileId:Q,...Z},W=!1;try{s.warning(G,J),W=!0}catch{}if(!W||Bun.env.NODE_ENV==="development")console.warn(G,J)}amend(Q){let $=this.amended.get(Q.id);if($)return $;let Z={...Q,content:[...Q.content]},G=this.history.indexOf(Q);if(G>=0)this.history[G]=Z;return this.produced.push(Z),this.amended.set(Q.id,Z),Z}async reportDeferred(){let Q=[...this.unreported];this.unreported.clear();for(let $ of Q)await this.report($)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let $ of this.openCalls()){if($.message===this.current)continue;this.attachToHistory($,{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let Q=this.current;if(Q){let $=new Set(Q.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...Q.content]){if(Z.type!=="tool-call"||$.has(Z.toolCallId))continue;delete Z.partial,this.addResult(Q,{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 ${iQ(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 e9(Q){if(Q.answeredBy==="client")return Q.inputSchema===sQ?"question":"client";return Q.requiresApproval?"approval":null}function Q$(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function I3(Q,$){return Q.descriptors($).map((Z)=>y.create({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,requiresApproval:Z.requiresApproval,execute:(G,J)=>{let W=PQ.getStore()?.req;if(!W)throw new j(`"${Z.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 Q.execute({kind:"local",req:W},Z.name,G,J)}}))}function v3(Q){if(Q==="auto")return;let $=/^(\d+)x(\d+)$/.exec(Q);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(Q)}.`);let Z=Number($[1]),G=Number($[2]);if(Z%16!==0||G%16!==0)throw Error(`Image size ${Q} is not supported: width and height must both be divisible by 16.`);if(Math.max(Z/G,G/Z)>3)throw Error(`Image size ${Q} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function X$(Q,$){if(Q.size!==void 0)try{v3(Q.size)}catch(Z){throw Error(`${$}: ${Z.message}`)}if(Q.background==="transparent"&&Q.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(Q.compression!==void 0){let Z=Q.compression;if(!Number.isInteger(Z)||Z<0||Z>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Z}.`)}}function Y$(Q,$){if(Q instanceof File)return Q;let Z=Q.type||"image/png",G=Z==="image/jpeg"?"jpg":Z.split("/")[1]??"png";return new File([Q],`${$}.${G}`,{type:Z})}class eQ{name;provider;settings;constructor(Q){let{name:$,provider:Z,...G}=Q;X$(G,`ImageModel "${$}"`),this.name=$,this.provider=Z,this.settings=G}static create(Q){return new eQ(Q)}async generate(Q){let $=this.merge(Q);return K$(await this.provider.generate({prompt:Q.prompt,...$,signal:Q.signal}))}async edit(Q){let $=this.merge(Q);return K$(await this.provider.edit({prompt:Q.prompt,...$,images:Q.images.map((Z,G)=>Y$(Z,`image-${G}`)),...Q.mask?{mask:Y$(Q.mask,"mask")}:{},signal:Q.signal}))}merge(Q){let $={...this.settings,...Q.size!==void 0?{size:Q.size}:{},...Q.quality!==void 0?{quality:Q.quality}:{},...Q.background!==void 0?{background:Q.background}:{},...Q.format!==void 0?{format:Q.format}:{},...Q.compression!==void 0?{compression:Q.compression}:{}};return X$($,`ImageModel "${this.name}"`),$}}function K$(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}function g(Q){return typeof process>"u"?void 0:process.env?.[Q]}var f3="preview";function H$(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function h3(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function NQ(Q,$={}){return{base:(Q.baseURL??g("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let G=Q.apiKey??g("OPENAI_API_KEY");return{...G?{authorization:`Bearer ${G}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}function y3(Q){let $=Q.baseURL??Q.endpoint??g("AZURE_OPENAI_ENDPOINT");if($)return H$($);let Z=Q.resourceName??g("AZURE_OPENAI_RESOURCE_NAME")??g("AZURE_RESOURCE_NAME");return Z?H$(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function _Q(Q,$={}){let Z=Q.apiVersion??g("AZURE_OPENAI_API_VERSION")??f3;return{base:`${y3(Q)}${h3(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let G=Q.apiKey??g("AZURE_OPENAI_API_KEY");return{...G?{"api-key":G}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}var g3=500,B$=20000;function u3(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let G=Date.parse(Z);if(Number.isNaN(G))return;return Math.max(0,G-$)}function z$(Q,$){let Z=Math.min(B$,g3*2**Q);return Math.round(Z*(0.5+$()*0.5))}function c3(Q){return Q===429||Q===408||Q===409||Q>=500}function p3(Q,$){return c3(Q)&&_($).retryable}function D$(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function m3(Q,$){return new Promise((Z,G)=>{let J=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(J),G(D$($))},{once:!0})})}async function $Q(Q,$,Z){let G=Z.fetchImpl??((H,z)=>fetch(H,z)),J=Z.sleep??m3,W=Z.random??Math.random,V=Z.now??Date.now,X=Math.max(0,Z.maxRetries),K=async(H)=>{let z=Z.signal;if(!z)return await J(H);z.throwIfAborted();let B;try{await Promise.race([J(H,z),new Promise((U,F)=>{B=()=>F(D$(z)),z.addEventListener("abort",B,{once:!0})})])}finally{if(B)z.removeEventListener("abort",B)}},Y;for(let H=0;H<=X;H++){Z.signal?.throwIfAborted();let z=new AbortController,B=()=>z.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",B,{once:!0});let U=!1,F=Z.timeoutMs>0?setTimeout(()=>{U=!0,z.abort()},Z.timeoutMs):void 0,D;try{D=await G(Q,{...$,signal:z.signal})}catch(P){if(F!==void 0)clearTimeout(F);if(Z.signal?.removeEventListener("abort",B),Z.signal?.aborted)throw P;if(Y=U?new WQ(Z.timeoutMs):P,U&&Z.retryTimeouts===!1)throw Y;if(H===X)throw Y;await K(z$(H,W));continue}if(F!==void 0)clearTimeout(F);if(D.ok)return D;Z.signal?.removeEventListener("abort",B);let C=await d3(D),L=new w(D.status,C,D.headers.get("x-request-id")??void 0);if(H===X||!p3(D.status,L))throw L;let R=u3(D.headers.get("retry-after"),V());await K(R===void 0?z$(H,W):Math.min(R,B$)),Y=L}throw Y??Error("Provider request failed with no response.")}async function d3(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var Q9=300000;function $9(Q){return{generationsUrl:`${Q.base}/images/generations${Q.query}`,editsUrl:`${Q.base}/images/edits${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}class MQ extends Error{code;retryable;constructor(Q,$={}){super(Q.message,$);this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable}}var l3={png:"image/png",jpeg:"image/jpeg"};function i3(Q){let $=Number(Q?.input_tokens??0),Z=Number(Q?.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q?.total_tokens??$+Z)},J=Q?.input_tokens_details?.image_tokens;if(typeof J==="number")G.imageInputTokens=J;let W=Q?.output_tokens_details?.image_tokens;if(typeof W==="number")G.imageOutputTokens=W;return G}function o3(Q){let $=atob(Q),Z=new Uint8Array($.length);for(let G=0;G<$.length;G++)Z[G]=$.charCodeAt(G);return Z}function n3(Q){let Z=Q?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new MQ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let G=typeof Q.output_format==="string"?Q.output_format:"png";return{bytes:o3(Z),mimeType:l3[G]??`image/${G}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:i3(Q.usage)}}async function U$(Q,$,Z,G){let J;try{J=await $Q(Q,$,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:G.signal,fetchImpl:Z.fetchImpl})}catch(W){if(G.signal?.aborted)throw W;throw new MQ(_(W),{cause:W})}return n3(await J.json())}async function F$(Q,$,Z={}){return await U$(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},Q,Z)}async function L$(Q,$,Z={}){return await U$(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:$},Q,Z)}class qQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await F$(this.endpoint(),this.body(Q),{signal:Q.signal})}async edit(Q){let $=new FormData;for(let[Z,G]of Object.entries(this.body(Q)))if(G!==void 0)$.set(Z,String(G));for(let Z of Q.images)$.append("image[]",Z,Z.name);if(Q.mask)$.set("mask",Q.mask,Q.mask.name);return await L$(this.endpoint(),$,{signal:Q.signal})}body(Q){return{model:this.modelName(),prompt:Q.prompt,...Q.size?{size:Q.size}:{},...Q.quality?{quality:Q.quality}:{},...Q.background?{background:Q.background}:{},...Q.format?{output_format:Q.format}:{},...Q.compression!==void 0?{output_compression:Q.compression}:{}}}normalizeError(Q){return _(Q)}}var C$=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class Z9 extends qQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new Z9(Q,$)}static models(){return C$}endpoint(){return $9(NQ(this.config,{timeoutMs:Q9}))}}class G9 extends qQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new G9(Q,$)}static models(){return C$}modelName(){return this.config.deployment??this.model}endpoint(){return $9(_Q(this.config,{timeoutMs:Q9}))}}var j$=3;function J9(Q){let $=new Map;for(let Z of Q)for(let G of Z.content??[]){if(G.type!=="file"||!G.fileId||$.has(G.fileId))continue;$.set(G.fileId,{name:G.name,mimeType:G.mimeType})}return $}function N$(Q,$,Z=new Map){if(!($ instanceof w))return[];if($.status!==400&&$.status!==404)return[];let G=t3($.body);if(!G)return[];let J=s3(Q.input);if(J.length===0)return[];let W=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(G.param??"");if(W){let Y=Q.input[Number(W[1])],H=V9(Y)[Number(W[2])],z=H&&typeof H.file_id==="string"?H.file_id:void 0;if(z)return[z]}let V=G.message??"",X=P$(J.map((Y)=>Y.fileId).filter((Y)=>a3(V,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(V);if(K){let Y=K[1].toLowerCase()==="image type"?"input_image":"input_file",H=K[2].toLowerCase(),z=P$(J.filter((U)=>U.type===Y).map((U)=>U.fileId)),B=z.filter((U)=>(Z.get(U)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(B.length===1)return B;if(B.length===0&&z.length===1)return z}return[]}function _$(Q,$,Z=new Map){return{...Q,input:Q.input.map((G)=>{let J=V9(G);if(!J.some((W)=>O$(W,$)))return G;return{...G,content:J.map((W)=>O$(W,$)?{type:"input_text",text:W9(Z.get(String(W.file_id))?.name)}:W)}})}}function W9(Q){return`[${Q?`attachment ${JSON.stringify(Q)}`:"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 O$(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function V9(Q){let $=Q?.content;return Array.isArray($)?$:[]}function s3(Q){let $=[];for(let Z of Q)for(let G of V9(Z))if(typeof G.file_id==="string"&&G.file_id)$.push({type:String(G.type),fileId:G.file_id});return $}function t3(Q){if(!Q||typeof Q!=="object")return null;let $=Q,Z=$.error&&typeof $.error==="object"?$.error:Q;return{message:typeof Z.message==="string"?Z.message:void 0,param:typeof Z.param==="string"?Z.param:void 0}}function a3(Q,$){let Z=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Z}($|[^A-Za-z0-9_-])`).test(Q)}function P$(Q){return[...new Set(Q)]}async function*r3(Q){let $="",Z="",G=[],J,W=()=>{if(G.length===0&&!Z)return null;let K={event:Z,data:G.join(`
16
+ `),id:J};return Z="",G=[],J=void 0,K.data?K:null},V=(K)=>{let Y=K.endsWith("\r")?K.slice(0,-1):K;if(Y==="")return W();if(Y.startsWith(":"))return null;let H=Y.indexOf(":"),z=H===-1?Y:Y.slice(0,H),B=H===-1?"":Y.slice(H+1);if(B.startsWith(" "))B=B.slice(1);if(z==="event")Z=B;else if(z==="data")G.push(B);else if(z==="id")J=B;return null};for await(let K of Q){$+=K;let Y=$.indexOf(`
17
+ `);while(Y!==-1){let H=$.slice(0,Y);$=$.slice(Y+1);let z=V(H);if(z)yield z;Y=$.indexOf(`
18
+ `)}}if($.length>0){let K=V($);if(K)yield K}let X=W();if(X)yield X}async function*M$(Q,$={}){let Z=new Map,G=new Set,J=!1;for await(let W of r3(Q)){if(W.data==="[DONE]")break;let V;try{V=JSON.parse(W.data)}catch{continue}switch(typeof V.type==="string"?V.type:W.event){case"response.output_text.delta":{let K=String(V.delta??"");if(!K)break;yield $.structuredOutput?{type:"output-delta",delta:K}:{type:"text-delta",delta:K};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let K=String(V.delta??"");if(!K)break;yield{type:"reasoning-delta",delta:K,id:V.item_id};break}case"response.output_item.added":{let K=V.item;if(!K)break;if(K.type==="function_call"){let Y=String(K.id??V.item_id??K.call_id??"");Z.set(Y,{callId:String(K.call_id??Y),name:String(K.name??""),namespace:typeof K.namespace==="string"&&K.namespace?K.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let K=Z.get(String(V.item_id??""));if(!K)break;let Y=String(V.delta??"");if(!Y)break;yield{type:"tool-call-delta",toolCallId:K.callId,name:K.name,argsDelta:Y,...K.namespace?{namespace:K.namespace}:{}};break}case"response.function_call_arguments.done":{let K=String(V.item_id??""),Y=Z.get(K);if(!Y)break;Y.done=!0,yield{type:"tool-call",toolCallId:Y.callId,name:Y.name,args:String(V.arguments??""),...Y.namespace?{namespace:Y.namespace}:{}};break}case"response.output_item.done":{let K=V.item;if(!K)break;if(K.type==="function_call"){let Y=String(K.id??V.item_id??K.call_id??""),H=Z.get(Y);if(H?.done)break;let z=(typeof K.namespace==="string"?K.namespace:"")||H?.namespace;if(yield{type:"tool-call",toolCallId:String(K.call_id??Y),name:String(K.name??H?.name??""),args:String(K.arguments??""),...z?{namespace:z}:{}},H)H.done=!0;break}if(K.type==="tool_search_call"||K.type==="tool_search_output"){let Y=e3(K);if(Y.loaded.length===0&&Y.namespaces.length===0)break;let H=String(K.tool_search_call_id??K.id??"");if(G.has(H))break;G.add(H),yield{type:"tool-search",...Y}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(V.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{J=!0,yield{type:"finish",reason:"stop",usage:X9(V.response?.usage)};break}case"response.incomplete":{J=!0;let K=X9(V.response?.usage),Y=V.response?.incomplete_details?.reason;if(Y==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:QZ(V.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:K};break}yield{type:"finish",reason:Y==="max_output_tokens"?"length":"stop",usage:K};break}case"response.failed":case"error":{J=!0;let K=V.response?.error??V.error??V;yield{type:"error",error:$Z(K)},yield{type:"finish",reason:"error",usage:X9(V.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{type:"finish",reason:"error",usage:d()}}function e3(Q){let $=[],Z=[];return q$(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:Y9($),namespaces:Y9(Z)}}function q$(Q,$,Z,G){if(!Array.isArray(Q)||G>4)return;for(let J of Q){if(typeof J==="string"){$.push(J);continue}if(!J||typeof J!=="object")continue;let W=J,V=typeof W.name==="string"?W.name:typeof W.tool_name==="string"?W.tool_name:"",X=W.tools??W.functions;if(Array.isArray(X)){if(V)Z.push(V);q$(X,$,Z,G+1);continue}if(V)$.push(V)}}function Y9(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function QZ(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let G of Q){if(!G||typeof G!=="object")continue;let J=G,W=J.content_filter_results;if(!W||typeof W!=="object")continue;for(let[V,X]of Object.entries(W))if(X&&typeof X==="object"&&X.filtered===!0)Z.push(`${V} (${String(J.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${Y9(Z).join(", ")}.`}function $Z(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",Z=String(Q?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function d(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function X9(Q){if(!Q)return d();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},J=Q.output_tokens_details?.reasoning_tokens;if(typeof J==="number")G.reasoningTokens=J;let W=Q.input_tokens_details?.cached_tokens;if(typeof W==="number")G.cachedInputTokens=W;return G}async function*S$(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:J,value:W}=await $.read();if(J)break;if(W)yield Z.decode(W,{stream:!0})}let G=Z.decode();if(G)yield G}finally{$.releaseLock()}}function K9(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}async function*H9(Q,$,Z){let G,J=$,W=new Set;for(let V=0;G===void 0;V++)try{G=await $Q(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(J)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(X){let K=V<j$?N$(J,X,Z.files).filter((H)=>!W.has(H)):[];if(K.length>0){let H=_(X).message;for(let z of K)W.add(z),yield{type:"file-rejected",fileId:z,message:H,...T(X)};J=_$(J,new Set(K),Z.files);continue}let Y=_(X);if(Y.code!=="aborted")yield{type:"error",error:Y,...T(X)};yield{type:"finish",reason:Y.code==="aborted"?"aborted":"error",usage:d()};return}try{yield*M$(S$(G.body),{structuredOutput:Z.structuredOutput})}catch(V){let X=_(V);if(X.code==="aborted"){yield{type:"finish",reason:"aborted",usage:d()};return}yield{type:"error",error:X},yield{type:"finish",reason:"error",usage:d()}}}async function z9(Q,$,Z="user_data"){let G=new FormData;G.set("purpose",Z),G.set("file",$);let W=await(await $Q(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:G},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!W?.id)throw Error("The provider accepted the upload but returned no file id.");return W.id}function B9(Q){let $=ZZ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=GZ($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:R$(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:R$(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function R$(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function ZZ(Q){return Q.trim().toLowerCase()}function GZ(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec(Q);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function U9(Q,$){let{capabilities:Z}=$,G={model:$.model,input:JZ(Q.messages,Z),stream:!0};if(Q.systemPrompt)G.instructions=Q.systemPrompt;let J=DZ(Q.tools,Z);if(J.length>0){if(G.tools=J,!Z.parallelToolCalls)G.parallel_tool_calls=!1}if(Q.output)G.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&Z.reasoning)G.reasoning=Q.reasoning==="none"?{effort:"none"}:{effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")G.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")G.max_output_tokens=Q.maxOutputTokens;return G}function JZ(Q,$){let Z=[];for(let G of Q){let J=G.role,W=[],V=()=>{if(W.length===0)return;Z.push({type:"message",role:J,content:W}),W=[]};for(let X of G.content??[])switch(X.type){case"text":{if(!X.text)break;W.push(l(J,X.text));break}case"output":{if(X.partial)break;W.push(l(J,JSON.stringify(X.value)));break}case"file":{if(J==="assistant")break;let K=XZ(X);if(!$.fileInput){if(K)W.push(l(J,D9(X,!1)));break}if(X.fileId?.startsWith(A))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&&!K)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(K)W.push(l(J,D9(X,!1)));W.push(l(J,W9(X.name)));break}if(K)W.push(l(J,D9(X,!!X.fileId)));if(X.fileId)W.push(YZ(X));break}case"reasoning":{V();let K=zZ(X);if(K)Z.push(K);break}case"tool-call":{if(X.partial)break;V(),Z.push({type:"function_call",call_id:X.toolCallId,name:String(X.name),arguments:JSON.stringify(X.input??{})});break}case"tool-result":{V(),Z.push({type:"function_call_output",call_id:X.toolCallId,output:BZ(X)});break}}V()}return VZ(Z)}var WZ="No result was recorded for this tool call. Assume it did not complete.";function VZ(Q){let $=new Set,Z=new Set,G=[];for(let W of Q){if(W.type==="function_call"){let V=String(W.call_id);if($.has(V))continue;$.add(V)}else if(W.type==="function_call_output"){let V=String(W.call_id);if(!$.has(V)||Z.has(V))continue;Z.add(V)}G.push(W)}if(Z.size===$.size)return G;let J=[];for(let W of G){if(J.push(W),W.type!=="function_call")continue;let V=String(W.call_id);if(Z.has(V))continue;Z.add(V),J.push({type:"function_call_output",call_id:V,output:WZ})}return J}function l(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function XZ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(A)?$:void 0}function D9(Q,$){let Z=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)Z.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)Z.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let G=`attachment ${Z.join(" ")}`;return $?`[${G}]`:`[${G} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function YZ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":KZ(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function KZ(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&HZ.has($[1])}var HZ=new Set(["jpeg","jpg","png","gif","webp"]);function zZ(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function BZ(Q){if(Q.status==="ok")return typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??null);if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function k$(Q){return Array.isArray(Q.tools)}function DZ(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let J=[];for(let W of Q)if(k$(W))for(let V of W.tools)J.push(SQ(V,!1));else J.push(SQ(W,!1));return J}let Z=[],G=!1;for(let J of Q)if(k$(J)){let W=J.tools.map((V)=>{if(V.deferred)G=!0;return SQ(V,!0)});Z.push({type:"namespace",name:J.name,description:J.description,tools:W})}else{if(J.deferred)G=!0;Z.push(SQ(J,!0))}if(G)Z.push({type:"tool_search"});return Z}function SQ(Q,$){let Z={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)Z.defer_loading=!0;return Z}class RQ{static models(){return[]}normalizeError(Q){return _(Q)}}var T$=["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 F9 extends RQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=B9(Q),this.config=$}static model(Q,$){return new F9(Q,$)}static models(){return T$}stream(Q){let $=U9(Q,{model:this.model,capabilities:this.capabilities});return H9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:J9(Q.messages)})}upload(Q){return z9(this.endpoint(),Q)}endpoint(){return K9(NQ(this.config))}}class L9 extends RQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=B9(Q),this.config=$}static model(Q,$){return new L9(Q,$)}static models(){return T$}stream(Q){let $=U9(Q,{model:this.deployment(),capabilities:this.capabilities});return H9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:J9(Q.messages)})}upload(Q){return z9(this.endpoint(),Q,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return K9(_Q(this.config))}}class i extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,Z){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=Z}}class ZQ extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class kQ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096,this.maxAgeMs=Q.maxAgeMs===void 0?3600000:Q.maxAgeMs}register(Q,$={}){let Z={run:Q,threadId:$.threadId,owner:$.owner??null,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(Q.runId,Z),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);return this.scheduleExpiry(Z,$.maxRunDurationMs),this.pump(Z,$)}findByClientRunId(Q){let $=this.byClientRun.get(Q);return $&&this.runs.has($)?$:null}async find(Q){let $=this.byThread.get(Q.threadId);if(!$)return null;let Z=this.runs.get($);if(!Z)return null;return{runId:$,seq:Z.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}ownerOf(Q){return this.runs.get(Q)?.owner??null}mayAccess(Q,$){let Z=this.ownerOf(Q);return Z===null||Z===$}isRunning(Q){let $=this.runs.get(Q);return!!$&&!$.ended&&!$.evicted}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new ZQ(Q);if($!==void 0&&$<Z.lostBefore)throw new i(Q,$,Z.lostBefore);let G=Z.frames[0]?.seq;return this.drain(Z,Q,$??G??Z.lastSeq+1)}clear(){for(let Q of this.runs.values()){if(Q.evictAt)clearTimeout(Q.evictAt);if(Q.expireAt)clearTimeout(Q.expireAt);Q.ended=!0,this.notify(Q)}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 G of Q.run.frames()){if(Q.evicted){let W=$.onEvent;if(W)Z=Z.then(()=>W(G.event)).catch((V)=>C9($,V));continue}if(Q.frames.push(G),Q.lastSeq=G.seq,Q.frames.length>this.maxFrames){let W=Q.frames.shift();if(W)Q.lostBefore=W.seq+1}this.notify(Q);let J=$.onEvent;if(J)Z=Z.then(()=>J(G.event)).catch((W)=>C9($,W))}}catch(G){C9($,G)}finally{if(Q.ended=!0,Q.expireAt)clearTimeout(Q.expireAt),Q.expireAt=null;this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let G=Z;while(!0){let J=Q.version;for(;;){if(G<Q.lostBefore)throw new i($,G,Q.lostBefore);let W=Q.frames,V=W[0]?.seq;if(V===void 0)break;let X=Math.max(0,G-V);if(X>=W.length)break;let K=W[X];yield K,G=K.seq+1}if(Q.ended&&G>Q.lastSeq||Q.evicted)return;await this.wait(Q,J)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((Z)=>Q.wake.add(Z))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let Z of $)Z()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let Z=Q.run.runId;if(!Q.ended)Q.evicted=!0,Q.frames=[];if(this.runs.get(Z)===Q)this.runs.delete(Z);if(Q.threadId&&this.byThread.get(Q.threadId)===Z)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===Z)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}scheduleExpiry(Q,$){if(this.maxAgeMs===null||$===null)return;let Z=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Z)||Z>2147483647)return;let G=setTimeout(()=>{if(Q.expireAt=null,Q.ended)return;try{Q.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(Q)},Z);G.unref?.(),Q.expireAt=G}}var O9=new kQ;function C9(Q,$){try{Q.onInternalError?.($)}catch{}}class TQ{maxEntries;records=new Map;constructor(Q=1e5){this.maxEntries=Q}async record(Q,$){if(this.records.has(Q))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(Q){let $=this.records.get(Q);return $?{...$}:null}}var P9=new TQ;class AQ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??86400000,this.clientOwnedIds=Q.clientOwnedIds??!1}async createThread(Q){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(Q){this.sweep();let $=this.threads.get(Q);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set(Q,Z)}for(let G of $){let J=Z.messages.findIndex((W)=>W.id===G.id);if(J===-1)Z.messages.push(G);else Z.messages[J]=G}Z.touchedAt=Date.now()}async removeMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z)return;let G=new Set($);Z.messages=Z.messages.filter((J)=>!G.has(J.id)),Z.touchedAt=Date.now()}delete(Q){this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<60000)return;this.lastSweep=Q;for(let[$,Z]of this.threads)if(Q-Z.touchedAt>this.ttlMs)this.threads.delete($)}}var j9=new AQ;function b$(Q={}){return{messages:Q.messages?[...Q.messages]:[],pending:Q.pending?[...Q.pending]:[],error:null,threadId:Q.threadId,seq:Q.seq??-1,cursorRunId:Q.cursorRunId,runMessageIds:[],loadedTools:[]}}function w$(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...I$(Q,$.event,Z),seq:$.seq}}function I$(Q,$,Z){switch($.type){case"run-start":return{...Q,runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return u(Q,$.messageId,Z,(G)=>({...G,role:$.role}));case"text-delta":if(E$(Q,$.messageId))return Q;return u(Q,$.messageId,Z,(G)=>({...G,content:OZ(G.content,$.delta)}));case"reasoning-delta":if(E$(Q,$.messageId))return Q;return u(Q,$.messageId,Z,(G)=>({...G,content:PZ(G.content,$.delta,$.id)}));case"output-delta":return u(Q,$.messageId,Z,(G)=>({...G,content:x$(G.content,{type:"output",value:$.snapshot,partial:!0},(J)=>J.type==="output")}));case"tool-call":return u(Q,$.messageId,Z,(G)=>{let J=G.content.findIndex((z)=>z.type==="tool-call"&&z.toolCallId===$.part.toolCallId),W=J===-1?void 0:G.content[J],V=$.part.progress??W?.progress,X=$.part.nested??W?.nested,K=$.part.attachments??W?.attachments,Y={...$.part,...V?{progress:V}:{},...X?{nested:X}:{},...K?{attachments:K}:{}},H=G.content.slice();if(J===-1)H.push(Y);else H[J]=Y;return{...G,content:H}});case"tool-search":{let G=$.loaded.filter((J)=>!Q.loadedTools.includes(J));if(G.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...G]}}case"tool-progress":return A$(Q,$.toolCallId,(G)=>({...G,progress:[...G.progress??[],$.data]}));case"nested-event":{let G=$;return A$(Q,$.toolCallId,(J)=>{let W=J.nested??[],V=W.findIndex((H)=>H.runId===G.runId),X=W[V]??{runId:G.runId,agent:G.agent,messages:[]},K=LZ(X,G,Z),Y=V===-1?[...W,K]:W.map((H,z)=>z===V?K:H);return{...J,nested:Y}})}case"tool-result":{let G=u(Q,$.messageId,Z,(J)=>({...J,content:x$(J.content,$.part,(W)=>W.type==="tool-result"&&W.toolCallId===$.part.toolCallId)}));return{...G,pending:G.pending.filter((J)=>J.toolCallId!==$.part.toolCallId)}}case"message":{let G=Q.messages.findIndex((V)=>V.id===$.message.id),J=Q.messages.slice();if(G===-1)J.push($.message);else J[G]=$.message;let W=Q.runMessageIds.includes($.message.id)?Q.runMessageIds:[...Q.runMessageIds,$.message.id];return{...Q,messages:J,runMessageIds:W}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return u(Q,$.messageId,Z,(G)=>({...G,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?G.content.filter((J)=>!(J.type==="output"&&J.partial)):G.content.map((J)=>J.type==="output"&&J.partial?{...J,partial:!1}:J)}));case"usage":return{...Q,usage:$.usage};case"error":return{...Q,error:$.error,pending:[]};case"run-end":return{...Q,runId:void 0,finishReason:$.finishReason,messages:v$(Q,$.finishReason)};default:return Q}}function v$(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?UZ(Z,$):Z)}function UZ(Q,$){let Z=Q.content.map((J)=>J.type==="tool-call"&&J.nested?.some((W)=>W.finishReason===void 0)?{...J,nested:J.nested.map((W)=>W.finishReason===void 0?FZ(W,$):W)}:J);if(Q.finishReason===void 0)return{...Q,finishReason:$,content:Z};return Z.some((J,W)=>J!==Q.content[W])?{...Q,content:Z}:Q}function FZ(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((G)=>G.id),loadedTools:[]};return{...Q,finishReason:$,messages:v$(Z,$)}}function A$(Q,$,Z){for(let G=Q.messages.length-1;G>=0;G--){let J=Q.messages[G],W=J.content.findIndex((Y)=>Y.type==="tool-call"&&Y.toolCallId===$);if(W===-1)continue;if(J.finishReason!==void 0&&!CZ(Q,J,$))return Q;let V=J.content.slice();V[W]=Z(V[W]);let X=Q.messages.slice();X[G]={...J,content:V};let K=Q.runMessageIds.includes(J.id)?Q.runMessageIds:[...Q.runMessageIds,J.id];return{...Q,runMessageIds:K,messages:X}}return Q}function LZ(Q,$,Z){let G={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((W)=>W.id),loadedTools:[],finishReason:Q.finishReason},J=I$(G,$.event,Z);return{...Q,...$.label!==void 0?{label:$.label}:{},messages:J.messages,...J.finishReason!==void 0?{finishReason:J.finishReason}:{},...J.usage!==void 0?{usage:J.usage}:{}}}function CZ(Q,$,Z){if($.finishReason!=="awaiting-input")return!1;return!Q.messages.some((G)=>G.content.some((J)=>J.type==="tool-result"&&J.toolCallId===Z))}function E$(Q,$){let Z=Q.messages.find((G)=>G.id===$);return Z!==void 0&&Z.finishReason!==void 0}function u(Q,$,Z,G){let J=Q.messages.findIndex((X)=>X.id===$),W=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(J===-1){let X={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:W,messages:[...Q.messages,G(X)]}}let V=Q.messages.slice();return V[J]=G(V[J]),{...Q,runMessageIds:W,messages:V}}function OZ(Q,$){let Z=Q[Q.length-1];if(Z&&Z.type==="text")return[...Q.slice(0,-1),{type:"text",text:Z.text+$}];return[...Q,{type:"text",text:$}]}function PZ(Q,$,Z){let G=Q[Q.length-1];if(G&&G.type==="reasoning"&&G.id===Z)return[...Q.slice(0,-1),{...G,text:(G.text??"")+$}];return[...Q,Z?{type:"reasoning",id:Z,text:$}:{type:"reasoning",text:$}]}function x$(Q,$,Z){let G=Q.findIndex(Z);if(G===-1)return[...Q,$];let J=Q.slice();return J[G]=$,J}class _9{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(Q,$,Z,G){this.store=Q;this.threadId=$;this.report=G;this.state=b$({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[N9(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=w$(this.state,Q),$.type){case"message":this.write(()=>[N9($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(Q=[]){this.closed=!0;for(let $ of Q)this.done.add($.id)}settled(){return this.chain}checkpoint(Q){if(this.done.has(Q))return;let $=this.state.messages.find((G)=>G.id===Q);if(!$)return;let Z=this.runId;this.write(()=>{let G=N9($);if(G.finishReason===void 0&&Z)G.runId=Z;return[G]})}write(Q){let $;try{$=Q()}catch(Z){this.report(Z);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Z)=>this.report(Z))}}function N9(Q){return structuredClone(Q)}async function f$(Q,$){let Z=[],G=null,J=Q.slice();for(let W=0;W<J.length;W++){let V=J[W];if(V.role!=="assistant"||V.finishReason!==void 0)continue;if(V.runId&&await $(V.runId))continue;G??=new Set(Q.flatMap((Y)=>Y.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let X=V.content.map((Y)=>Y.type==="tool-call"?h$(Y):Y);for(let Y of V.content){if(Y.type!=="tool-call"||G.has(Y.toolCallId))continue;let H={type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"denied",cause:"interrupted"};X.push(H)}let K={...V,content:X,finishReason:"interrupted"};J[W]=K,Z.push(K)}return{messages:J,settled:Z}}function h$(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((G)=>G.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(jZ)}}function jZ(Q){if(Q.finishReason!==void 0)return Q;return{...Q,finishReason:"interrupted",messages:Q.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Z)=>Z.type==="tool-call"?h$(Z):Z)}:$)}}var NZ=o$,EQ=new Map,y$=new WeakMap,xQ=new Map,_Z=4194304,MZ=1000,qZ=5,g$=65536,r$=()=>{};class e${byKey=new Map;take(Q,$,Z){let G=this.byKey.get(Q);if(!G?.has($)&&(G?.size??0)>=Z)return null;if(!G)G=new Map,this.byKey.set(Q,G);G.set($,(G.get($)??0)+1);let J=!1;return()=>{if(J)return;J=!0;let W=this.byKey.get(Q),V=(W?.get($)??1)-1;if(!W)return;if(V>0)W.set($,V);else if(W.delete($),W.size===0)this.byKey.delete(Q)}}}var u$=new WeakMap;function SZ(Q){let $=u$.get(Q);if(!$)$=new e$,u$.set(Q,$);return $}class Q3 extends NZ{static kind="agent-controller";store=j9;liveRuns=O9;attachments=LQ;attachmentStorage=t$;fileOwners=P9;nonces=p;requireKnownFiles=!1;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;maxBodyBytes=_Z;maxHistoryMessages=MZ;maxConcurrentRuns=qZ;runLimitKey(Q,$){return $.owner}authorizeRequest(Q,$){}runOwner(Q){let $=Q.ctx?.()?.user,Z=$?.id??$?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}async stream(Q=new GQ){let $=await M9(Q,this.maxBodyBytes);if($.error)return bQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:void 0,J=wZ(Z);if(J.error)return bQ({body:{},error:J.error});let W=J.turn,V=G!==void 0&&Z.regenerate===!0,X=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,K=$3(Z);if(this.requireThread&&!G)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(V&&!this.store.removeMessages)return M(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!G&&Array.isArray(Z.messages)&&Z.messages.length>this.maxHistoryMessages)return R9(413,"history_too_long",`The conversation has ${Z.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(Q),H=X?{cancelled:!1,owner:Y}:null;if(H)xQ.set(X,H);let z=null,B=[],U=async()=>{try{return await F()}finally{if(G&&B.length>0&&z===null)await this.store.appendMessages(G,B).catch((D)=>this.reportHookFailure(D))}},F=async()=>{let D;if(G){let q=await this.store.loadThread(G);if(!q)return M(404,{code:"thread_not_found",message:`Thread ${G} does not exist here, or has expired.`});if(D=await this.settleThread(G,q,{write:!0}),V){let c=hZ(D);if(!c)return M(409,{code:"nothing_to_regenerate",message:`Thread ${G} has no user turn to answer again.`});B=D.slice(c.index),await this.store.removeMessages(G,B.map((W3)=>W3.id)),D=D.slice(0,c.index),W=c.turn}}else D=Array.isArray(Z.messages)?Z.messages:[],dZ(this.nonces);let C=await this.instructions(Q,{body:K})||void 0,L=await this.context(Q,{body:K}),R=await this.attachmentsFor(Q,G,{body:K});if(H?.cancelled)return d$();let P=G?new _9(this.store,G,D,(q)=>this.reportHookFailure(q)):null,x=`run_${crypto.randomUUID()}`,k={req:Q,runId:x,threadId:G},N=this.agent.stream({runId:x,messages:D,turn:W,threadId:G,...P?{onMessage:(q)=>P.finish(q)}:{},instructions:C,context:L,attachments:R,body:K,redactError:(q,c)=>this.redactError(q,c,k),nonces:this.nonces}),O=this.liveRuns.register(N,{threadId:G,owner:Y,clientRunId:X,onEvent:(q)=>this.dispatchEvent(q,k),onInternalError:(q)=>this.reportHookFailure(q),maxRunDurationMs:this.agent.maxRunDurationMs});if(z=N,P)this.follow(N,P);let{stored:b,hooks:JQ}=this.persistRun(N,k,O,P);return y$.set(N,b),Q.ctx?.()?.waitUntil(JQ),N.toResponse()};try{await this.authorizeRequest(Q,{route:"stream",threadId:G,body:K});let D=await this.foreignFile([...W?.files??[],...G?[]:gZ(Z.messages)],Y);if(D)return D;if(H?.cancelled)return d$();let C=await this.runLimitKey(Q,{owner:Y,threadId:G}),L=C===null?r$:SZ(this.liveRuns).take(C,G?`thread:${G}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!L)return R9(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return G?await this.withThread(G,Y,U):await U()}finally{let R=z;if(R)R.result().then(L,L);else L()}}finally{if(H&&xQ.get(X)===H)xQ.delete(X)}}async withThread(Q,$,Z){let G=EQ.get(Q)??Promise.resolve(),J,W=new Promise((X)=>{J=X}),V=G.then(()=>W);EQ.set(Q,V),await G;try{let X=await this.liveRuns.find({threadId:Q});if(X&&this.liveRuns.isRunning(X.runId)&&!this.liveRuns.mayAccess(X.runId,$))return wQ();let K=X?this.liveRuns.get(X.runId):null;if(K)K.stop({reason:"superseded by a later turn on this thread"}),await y$.get(K);return await Z()}finally{if(J(),EQ.get(Q)===V)EQ.delete(Q)}}async attach(Q=new GQ){let $=await M9(Q,g$);if($.error)return bQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:fZ(Q,"threadId");if(!G)return M(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:G});let J=await this.liveRuns.find({threadId:G});if(J&&!this.liveRuns.mayAccess(J.runId,await this.runOwner(Q)))return wQ();if(!J)return M(404,{code:"no_live_run",message:`No run in progress for thread ${G} in this process.`});let W=typeof Z.runId==="string"?Z.runId:void 0,V=W&&W!==J.runId?void 0:vZ(Q,Z);try{return d9(this.liveRuns.replay(J.runId,V))}catch(X){if(X instanceof i)return M(410,{code:X.code,message:X.message,oldestSeq:X.oldest});if(X instanceof ZQ)return M(404,{code:X.code,message:X.message});throw X}}async stop(Q=new GQ){let $=await M9(Q,g$);if($.error)return bQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let G=await this.runOwner(Q),J=typeof Z.runId==="string"?Z.runId:void 0;if(!J&&typeof Z.clientRunId==="string"){if(J=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!J){let V=xQ.get(Z.clientRunId);if(V){if(V.owner!==null&&V.owner!==G)return wQ();return V.cancelled=!0,{stopped:!0}}}}if(!J&&typeof Z.threadId==="string")J=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let W=J?this.liveRuns.get(J):null;if(!W)return{stopped:!1};if(!this.liveRuns.mayAccess(W.runId,G))return wQ();return W.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$,Z){let G=Q.ctx()?.user,J=G?.id??G?.publicId;if(J!==void 0&&J!==null&&String(J)!=="")return{key:`user:${String(J)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(Q){return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$,Z={body:{}}){let G=await this.attachmentScope(Q,$,Z);if(!G)return null;return new e(this.attachments,this.attachmentStorage,G)}async upload(Q=new GQ){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let G=Z instanceof File&&Z.name?Z.name:"upload",J=Z.type||"application/octet-stream",W=kZ($.get("body")),V=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof V==="string"&&V.length>0?V:void 0,body:W});let X=AZ(await this.attachmentLimits(Q),Z,G,J);if(X)throw new Z3(X.code,X.message);let K=typeof V==="string"&&V.length>0&&await this.store.loadThread(V)!==null?V:void 0,Y=await this.runOwner(Q),H=(P)=>this.fileOwners.record(P,{owner:Y,name:G,mimeType:J,size:Z.size,createdAt:new Date().toISOString()}),z=await this.attachmentDestination(Z,Q),B=uZ(z,$.get("destination")),U=await this.attachmentScope(Q,K,{body:W}),F=B!=="provider"&&!U;if(F){if(B==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');cZ()}if(B==="provider"||!U){let P=await c$(this.agent.provider,Z);await H(P);let x={fileId:P,name:G,mimeType:J,size:Z.size,destination:"provider"};if(F)x.downgraded="no_scope";return x}let D=pQ(),C=await this.attachmentStorage.put({name:mQ(D,G),body:Z,contentType:J}),L=B==="both"?await c$(this.agent.provider,Z):void 0;if(L)await H(L);let R={id:D,scopeKey:U.key,fileId:L,objectName:C,name:G,mimeType:J,size:Z.size,createdAt:new Date().toISOString(),destination:B};return await this.attachments.put(U,R),{fileId:L,attachmentId:D,name:G,mimeType:J,size:Z.size,destination:B}}async foreignFile(Q,$){let Z=new Set(Q.map((G)=>G.fileId).filter((G)=>typeof G==="string"));for(let G of Z){let J=await this.fileOwners.get(G);if(J?J.owner!==null&&J.owner!==$:this.requireKnownFiles)return yZ()}return null}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}redactError(Q,$,Z){return k9(Q,$)}onError(Q,$){}onStreamComplete(Q,$){}reportHookFailure(Q){console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,$){switch(Q.type){case"tool-call":if(!Q.part.partial&&!Q.resent)await this.onToolCall({toolCallId:Q.part.toolCallId,name:String(Q.part.name),input:Q.part.input},$);return;case"awaiting-input":await this.onAwaitingInput(Q.pending,$);return;case"error":await this.onError(a$(Q.error),$);return;default:return}}async readThread(Q){let $=await this.store.loadThread(Q);return $?await this.settleThread(Q,$,{write:!1}):null}isRunLive(Q,$){return this.liveRuns.get(Q)!==null}async settleThread(Q,$,{write:Z}){let{messages:G,settled:J}=await f$($,(W)=>this.isRunLive(W,Q));if(Z&&J.length>0)try{await this.store.appendMessages(Q,J)}catch(W){this.reportHookFailure(W)}return G}follow(Q,$){(async()=>{try{for await(let Z of Q.frames())$.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun(Q,$,Z,G=null){let J=Promise.resolve(),W=(async()=>{let X;try{X=await Q.result()}catch(Y){G?.close(),await G?.settled(),J=this.safely(()=>this.onError({code:"unknown",message:Y instanceof Error?Y.message:String(Y),retryable:!1},$));return}let K=X.messages;if(G?.close(K),await G?.settled(),$.threadId&&K.length>0)try{await this.store.appendMessages($.threadId,K)}catch(Y){this.reportHookFailure(Y)}J=this.notifyRun(X,K,$)})(),V=W.then(()=>mZ(Promise.all([J,Z]).then(()=>{}),this.hookHoldMs));return{stored:W,hooks:V}}async notifyRun(Q,$,Z){for(let G of $)await this.safely(()=>this.onMessage(G,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}var q9=["turn","clientRunId","threadId","messages","regenerate"],RZ=["text","files","toolResults"];function $3(Q,$=J3(Q)?q9:[...q9,...RZ]){let Z={};for(let[G,J]of Object.entries(Q)){if($.includes(G))continue;Object.defineProperty(Z,G,{value:J,writable:!0,enumerable:!0,configurable:!0})}return Z}function kZ(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new S9("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new S9("The upload's `body` field must be a JSON object.");return $3($,q9)}class S9 extends IQ{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function c$(Q,$){try{return await Q.upload($)}catch(Z){if(Z instanceof w&&TZ.has(Z.status))throw new G3(_(Z).message);throw Z}}var TZ=new Set([400,413,415,422]);class Z3 extends IQ{constructor(Q,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}function AZ(Q,$,Z,G){if(!Q)return null;let{maxBytes:J,accept:W}=Q;if(typeof J==="number"&&$.size>J)return{code:"file_too_large",message:`${JSON.stringify(Z)} is ${p$($.size)}; the limit is ${p$(J)}.`};if(W&&W.length>0&&!W.some((V)=>EZ(V,Z,G)))return{code:"unsupported_file_type",message:`${JSON.stringify(Z)} is not a type this chat accepts. Accepted: ${W.join(", ")}.`};return null}function EZ(Q,$,Z){let G=Q.trim().toLowerCase();if(!G)return!1;if(G.startsWith("."))return $.toLowerCase().endsWith(G);let J=Z.toLowerCase().split(";")[0].trim();if(G.endsWith("/*"))return J.startsWith(G.slice(0,-1));return J===G}function p$(Q){if(Q<1024)return`${Q} B`;let $=["KB","MB","GB"],Z=Q/1024,G=0;while(Z>=1024&&G<$.length-1)Z/=1024,G++;return`${Math.round(Z*10)/10} ${$[G]}`}class G3 extends IQ{constructor(Q){super(Q);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(Q)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}async function M9(Q,$){let Z=Q?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!xZ(Z.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let G=Number(Z.headers.get("Content-Length"));if(Number.isFinite(G)&&G>$)return m$($);let J;try{let V=await bZ(Z,$);if(V===null)return m$($);J=V}catch{return{body:{},error:"The request body could not be read."}}if(!J.trim())return{body:{}};let W;try{W=JSON.parse(J)}catch{return{body:{},error:"The request body is not valid JSON."}}if(W===null||typeof W!=="object"||Array.isArray(W))return{body:{},error:"The request body must be a JSON object."};return{body:W}}function xZ(Q){return s$(Q)==="application/json"}async function bZ(Q,$){if(!Number.isFinite($)||!Q.body)return await Q.text();let Z=Q.body.getReader(),G=[],J=0;for(;;){let{done:X,value:K}=await Z.read();if(X)break;if(J+=K.byteLength,J>$)return await Z.cancel().catch(r$),null;G.push(K)}let W=new Uint8Array(J),V=0;for(let X of G)W.set(X,V),V+=X.byteLength;return new TextDecoder().decode(W)}function m$(Q){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${Q} bytes).`}}function R9(Q,$,Z){return M(Q,{...vQ(n$(Q),Z,Q),code:$})}function bQ(Q){if(Q.status===413)return R9(413,Q.code??"body_too_large",Q.error??"");return M(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function J3(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function wZ(Q){let $=J3(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let G=IZ($.files);if(typeof G==="string")return{error:G};Z.files=G}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function IZ(Q){let $=[];for(let[Z,G]of Q.entries()){let J=`turn.files[${Z}]`;if(!G||typeof G!=="object"||Array.isArray(G))return`${J} must be an object.`;let W={};for(let H of["fileId","attachmentId","name","mimeType"]){let z=G[H];if(z===void 0||z===null||z==="")continue;if(typeof z!=="string")return`${J}.${H} must be a string.`;W[H]=z}let{fileId:V,attachmentId:X,name:K,mimeType:Y}=W;if(V?.startsWith(A))return`${J}.fileId holds a gemi attachment id (${V}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(X!==void 0&&!X.startsWith(A))return`${J}.attachmentId is not a gemi attachment id: it must start with "${A}".`;if(!V&&!X)return`${J} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...V?{fileId:V}:{},...X?{attachmentId:X}:{},...K!==void 0?{name:K}:{},...Y!==void 0?{mimeType:Y}:{}})}return $}function vZ(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let G=Math.floor($.cursor);if(G>=0)return G+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let G=Number.parseInt(Z,10);if(Number.isFinite(G))return Math.max(0,G+1)}return}function fZ(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function hZ(Q){let $=OQ(Q);for(let Z=Q.length-1;Z>=0;Z--){let G=Q[Z];if(G.role!=="user"||$.has(G.id))continue;let J="",W=[];for(let V of G.content){if(V.type==="text")J+=V.text;if(V.type==="file")W.push({...V.fileId?{fileId:V.fileId}:{},...V.attachmentId?{attachmentId:V.attachmentId}:{},...V.name?{name:V.name}:{},...V.mimeType?{mimeType:V.mimeType}:{}})}if(!J&&W.length===0)continue;return{index:Z,turn:{...J?{text:J}:{},...W.length>0?{files:W}:{}}}}return null}function d$(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function wQ(){return M(403,vQ("permission","This run belongs to someone else.",403))}function yZ(){return M(403,vQ("permission","A file in this turn was uploaded by someone else.",403))}function gZ(Q){if(!Array.isArray(Q))return[];let $=[];for(let Z of Q){let G=Z?.content;if(!Array.isArray(G))continue;for(let J of G)if(J&&typeof J==="object"&&typeof J.fileId==="string")$.push({fileId:J.fileId})}return $}function M(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function uZ(Q,$){if(typeof $!=="string"||$.length===0)return Q;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===Q||Q==="both"&&$==="storage")return $;if(Q==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${Q}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var l$=!1;function cZ(){if(l$)return;l$=!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 pZ=2147483647;function mZ(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=pZ))return Z;let G,J=new Promise((W)=>{G=setTimeout(W,$)});return Promise.race([Z,J]).finally(()=>clearTimeout(G))}var i$=!1;function dZ(Q){if(i$||Bun.env.NODE_ENV!=="production")return;if(!(Q instanceof a))return;i$=!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.")}export{I3 as toAgentTools,o as supportsStrict,lZ as s,k9 as redactError,O9 as liveRuns,z3 as generate,p as defaultNonceStore,P9 as defaultFileOwners,LQ as defaultAttachmentStore,j9 as defaultAgentStore,jQ as ToolNamespace,j as ToolError,tQ as Skill,e as ScopedAttachments,QQ as SKILLS_NAMESPACE,yQ as RedisNonceStore,h as PendingEscalation,F9 as OpenAIProvider,Z9 as OpenAIImageProvider,a as MemoryNonceStore,kQ as MemoryLiveRuns,TQ as MemoryFileOwners,FQ as MemoryAttachmentStore,AQ as MemoryAgentStore,ZQ as LiveRunNotFoundError,m as InvalidAttachmentScopeError,MQ as ImageRequestError,qQ as ImageProvider,eQ as ImageModel,i as FrameCursorEvictedError,aQ as DEFAULT_MAX_RUN_DURATION_MS,L9 as AzureOpenAIProvider,G9 as AzureOpenAIImageProvider,r as AttachmentNotFoundError,y as AgentTool,t as AgentRunError,RQ as AgentProvider,Q3 as AgentController,rQ as Agent};
19
19
 
20
- //# debugId=2F24C8E957DB2B5564756E2164756E21
20
+ //# debugId=C9CADBDC97D38E0564756E2164756E21