gemi 0.123.0 → 0.124.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 (206) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/app/index.js +1 -1
  4. package/dist/bun/plugin.js +1 -1
  5. package/dist/bun/preload.js +1 -1
  6. package/dist/{chunk-vwnd4jb5.js → chunk-019wz697.js} +2 -2
  7. package/dist/{chunk-vwnd4jb5.js.map → chunk-019wz697.js.map} +1 -1
  8. package/dist/{chunk-f1thqe6j.js → chunk-121p4g9j.js} +2 -2
  9. package/dist/{chunk-f1thqe6j.js.map → chunk-121p4g9j.js.map} +1 -1
  10. package/dist/{chunk-ay8nat73.js → chunk-17dndh5z.js} +2 -2
  11. package/dist/{chunk-53hc0ah1.js.map → chunk-17dndh5z.js.map} +1 -1
  12. package/dist/{chunk-r5tadf14.js → chunk-1qwhty9p.js} +2 -2
  13. package/dist/{chunk-r5tadf14.js.map → chunk-1qwhty9p.js.map} +1 -1
  14. package/dist/{chunk-k17wx7gz.js → chunk-1rnh9qrp.js} +2 -2
  15. package/dist/{chunk-k17wx7gz.js.map → chunk-1rnh9qrp.js.map} +1 -1
  16. package/dist/{chunk-6gjvqtcp.js → chunk-2affxmkn.js} +2 -2
  17. package/dist/{chunk-6gjvqtcp.js.map → chunk-2affxmkn.js.map} +1 -1
  18. package/dist/{chunk-nvngb4ed.js → chunk-2n4490pk.js} +2 -2
  19. package/dist/{chunk-nvngb4ed.js.map → chunk-2n4490pk.js.map} +1 -1
  20. package/dist/{chunk-0qmc7snf.js → chunk-34fkx6kb.js} +2 -2
  21. package/dist/{chunk-0qmc7snf.js.map → chunk-34fkx6kb.js.map} +1 -1
  22. package/dist/{chunk-kdjhgtp9.js → chunk-3hqwz48c.js} +4 -4
  23. package/dist/{chunk-kdjhgtp9.js.map → chunk-3hqwz48c.js.map} +1 -1
  24. package/dist/{chunk-4qpypa3h.js → chunk-3j6s5bmx.js} +1 -1
  25. package/dist/{chunk-pfm9ngch.js → chunk-3y294mb8.js} +2 -2
  26. package/dist/{chunk-pfm9ngch.js.map → chunk-3y294mb8.js.map} +1 -1
  27. package/dist/{chunk-58ffbwdc.js → chunk-4drnyymm.js} +2 -2
  28. package/dist/{chunk-58ffbwdc.js.map → chunk-4drnyymm.js.map} +1 -1
  29. package/dist/{chunk-wqharhrp.js → chunk-5e22tm7m.js} +1 -1
  30. package/dist/chunk-5j50q4g8.js +57 -0
  31. package/dist/{chunk-gvp6brdt.js.map → chunk-5j50q4g8.js.map} +6 -6
  32. package/dist/{chunk-j0cnsgjq.js → chunk-65s834td.js} +1 -1
  33. package/dist/{chunk-vd6zn8c4.js → chunk-6bgb1nhq.js} +2 -2
  34. package/dist/{chunk-vd6zn8c4.js.map → chunk-6bgb1nhq.js.map} +1 -1
  35. package/dist/chunk-70nnh0y7.js +5 -0
  36. package/dist/{chunk-tazvfppr.js.map → chunk-70nnh0y7.js.map} +1 -1
  37. package/dist/{chunk-dmj6ysym.js → chunk-75ewjc4a.js} +2 -2
  38. package/dist/{chunk-dmj6ysym.js.map → chunk-75ewjc4a.js.map} +1 -1
  39. package/dist/{chunk-qen6587t.js → chunk-7gfdts60.js} +2 -2
  40. package/dist/{chunk-qen6587t.js.map → chunk-7gfdts60.js.map} +1 -1
  41. package/dist/{chunk-de7hxe73.js → chunk-8m2htvjn.js} +2 -2
  42. package/dist/{chunk-de7hxe73.js.map → chunk-8m2htvjn.js.map} +1 -1
  43. package/dist/{chunk-08fcqny0.js → chunk-92sk56n0.js} +2 -2
  44. package/dist/{chunk-08fcqny0.js.map → chunk-92sk56n0.js.map} +1 -1
  45. package/dist/{chunk-y67evsdy.js → chunk-9tr92nwy.js} +2 -2
  46. package/dist/{chunk-y67evsdy.js.map → chunk-9tr92nwy.js.map} +1 -1
  47. package/dist/{chunk-fyk07w01.js → chunk-a3g7y70h.js} +3 -3
  48. package/dist/{chunk-fyk07w01.js.map → chunk-a3g7y70h.js.map} +1 -1
  49. package/dist/{chunk-fsy344zb.js → chunk-b5afy6k9.js} +2 -2
  50. package/dist/{chunk-fsy344zb.js.map → chunk-b5afy6k9.js.map} +1 -1
  51. package/dist/{chunk-w0jfqnw9.js → chunk-bnt8kx6x.js} +2 -2
  52. package/dist/{chunk-w0jfqnw9.js.map → chunk-bnt8kx6x.js.map} +1 -1
  53. package/dist/{chunk-sxa70wgn.js → chunk-bt9qv2jj.js} +3 -3
  54. package/dist/{chunk-sxa70wgn.js.map → chunk-bt9qv2jj.js.map} +1 -1
  55. package/dist/{chunk-xhmtph39.js → chunk-c4jnxmf2.js} +1 -1
  56. package/dist/{chunk-9p7eq7bz.js → chunk-cfdwsvtx.js} +2 -2
  57. package/dist/{chunk-9p7eq7bz.js.map → chunk-cfdwsvtx.js.map} +1 -1
  58. package/dist/{chunk-h76mddt3.js → chunk-dxfhhw5h.js} +2 -2
  59. package/dist/{chunk-h76mddt3.js.map → chunk-dxfhhw5h.js.map} +1 -1
  60. package/dist/{chunk-aafanq8n.js → chunk-f29pktad.js} +3 -3
  61. package/dist/{chunk-aafanq8n.js.map → chunk-f29pktad.js.map} +1 -1
  62. package/dist/{chunk-9t08wbkd.js → chunk-f4cmz31h.js} +2 -2
  63. package/dist/{chunk-9t08wbkd.js.map → chunk-f4cmz31h.js.map} +1 -1
  64. package/dist/{chunk-5a4qbtez.js → chunk-fn2qfwgx.js} +2 -2
  65. package/dist/{chunk-5a4qbtez.js.map → chunk-fn2qfwgx.js.map} +1 -1
  66. package/dist/{chunk-j8vc3bze.js → chunk-fvrmptd0.js} +3 -3
  67. package/dist/{chunk-j8vc3bze.js.map → chunk-fvrmptd0.js.map} +1 -1
  68. package/dist/{chunk-0tc0j3pf.js → chunk-fw7ds23a.js} +2 -2
  69. package/dist/{chunk-0tc0j3pf.js.map → chunk-fw7ds23a.js.map} +1 -1
  70. package/dist/{chunk-q1e3q01h.js → chunk-h3p8qzft.js} +2 -2
  71. package/dist/{chunk-q1e3q01h.js.map → chunk-h3p8qzft.js.map} +1 -1
  72. package/dist/{chunk-8x73yyfs.js → chunk-j7v7dft7.js} +1 -1
  73. package/dist/{chunk-d3ywmeb7.js → chunk-jctb7v53.js} +2 -2
  74. package/dist/{chunk-d3ywmeb7.js.map → chunk-jctb7v53.js.map} +1 -1
  75. package/dist/{chunk-52xkw2bs.js → chunk-jys8y39p.js} +2 -2
  76. package/dist/{chunk-52xkw2bs.js.map → chunk-jys8y39p.js.map} +1 -1
  77. package/dist/{chunk-kvas36p6.js → chunk-kzsjyvvc.js} +2 -2
  78. package/dist/{chunk-kvas36p6.js.map → chunk-kzsjyvvc.js.map} +1 -1
  79. package/dist/{chunk-1f1sb3w7.js → chunk-mqtfaqx5.js} +2 -2
  80. package/dist/{chunk-1f1sb3w7.js.map → chunk-mqtfaqx5.js.map} +1 -1
  81. package/dist/{chunk-gwnmgkq5.js → chunk-mrswc6qw.js} +2 -2
  82. package/dist/{chunk-gwnmgkq5.js.map → chunk-mrswc6qw.js.map} +1 -1
  83. package/dist/{chunk-mxbtcaed.js → chunk-mvkz22p4.js} +2 -2
  84. package/dist/{chunk-mxbtcaed.js.map → chunk-mvkz22p4.js.map} +1 -1
  85. package/dist/{chunk-z23h4s1a.js → chunk-n0r5xyk2.js} +2 -2
  86. package/dist/{chunk-z23h4s1a.js.map → chunk-n0r5xyk2.js.map} +1 -1
  87. package/dist/{chunk-1kdga1b2.js → chunk-nkzmk7v3.js} +2 -2
  88. package/dist/{chunk-1kdga1b2.js.map → chunk-nkzmk7v3.js.map} +1 -1
  89. package/dist/{chunk-53hc0ah1.js → chunk-nn2jeat2.js} +2 -2
  90. package/dist/{chunk-ay8nat73.js.map → chunk-nn2jeat2.js.map} +1 -1
  91. package/dist/{chunk-eevna943.js → chunk-nnarmbjv.js} +2 -2
  92. package/dist/{chunk-eevna943.js.map → chunk-nnarmbjv.js.map} +1 -1
  93. package/dist/{chunk-73v34hw8.js → chunk-pe46a5a5.js} +2 -2
  94. package/dist/{chunk-73v34hw8.js.map → chunk-pe46a5a5.js.map} +1 -1
  95. package/dist/{chunk-6pxavyh3.js → chunk-pmyh33v5.js} +2 -2
  96. package/dist/{chunk-6pxavyh3.js.map → chunk-pmyh33v5.js.map} +1 -1
  97. package/dist/{chunk-d0wr9jk4.js → chunk-pya4rqm2.js} +2 -2
  98. package/dist/{chunk-d0wr9jk4.js.map → chunk-pya4rqm2.js.map} +1 -1
  99. package/dist/{chunk-rjtmgbay.js → chunk-qdj8ek8z.js} +2 -2
  100. package/dist/{chunk-rjtmgbay.js.map → chunk-qdj8ek8z.js.map} +1 -1
  101. package/dist/{chunk-nf608sb1.js → chunk-qhz0x97z.js} +2 -2
  102. package/dist/{chunk-nf608sb1.js.map → chunk-qhz0x97z.js.map} +1 -1
  103. package/dist/{chunk-2vc72qez.js → chunk-qycwjzsv.js} +3 -3
  104. package/dist/{chunk-2vc72qez.js.map → chunk-qycwjzsv.js.map} +1 -1
  105. package/dist/{chunk-hnrzm5pf.js → chunk-rpyczdta.js} +3 -3
  106. package/dist/{chunk-hnrzm5pf.js.map → chunk-rpyczdta.js.map} +1 -1
  107. package/dist/{chunk-enta97jb.js → chunk-rtawbqec.js} +2 -2
  108. package/dist/{chunk-enta97jb.js.map → chunk-rtawbqec.js.map} +1 -1
  109. package/dist/{chunk-hs88b8gt.js → chunk-rttrpjqk.js} +2 -2
  110. package/dist/{chunk-hs88b8gt.js.map → chunk-rttrpjqk.js.map} +1 -1
  111. package/dist/{chunk-2amj1eyp.js → chunk-sd0c2001.js} +2 -2
  112. package/dist/{chunk-2amj1eyp.js.map → chunk-sd0c2001.js.map} +1 -1
  113. package/dist/chunk-skf89vrv.js +5 -0
  114. package/dist/chunk-skf89vrv.js.map +10 -0
  115. package/dist/chunk-szn2n976.js +24 -0
  116. package/dist/{chunk-vpgbn494.js.map → chunk-szn2n976.js.map} +2 -2
  117. package/dist/{chunk-fxxbwyce.js → chunk-v2ggafz1.js} +2 -2
  118. package/dist/{chunk-fxxbwyce.js.map → chunk-v2ggafz1.js.map} +1 -1
  119. package/dist/{chunk-ebx5hnqn.js → chunk-v8v5qfnh.js} +2 -2
  120. package/dist/{chunk-ebx5hnqn.js.map → chunk-v8v5qfnh.js.map} +1 -1
  121. package/dist/{chunk-9a9ef0f1.js → chunk-w3812s34.js} +2 -2
  122. package/dist/{chunk-9a9ef0f1.js.map → chunk-w3812s34.js.map} +1 -1
  123. package/dist/{chunk-zjej5vqh.js → chunk-w4z6x54b.js} +2 -2
  124. package/dist/{chunk-zjej5vqh.js.map → chunk-w4z6x54b.js.map} +1 -1
  125. package/dist/{chunk-rjm1kj8n.js → chunk-wbg2tza5.js} +1 -1
  126. package/dist/{chunk-ywgvxx35.js → chunk-y434jc1c.js} +2 -2
  127. package/dist/{chunk-ywgvxx35.js.map → chunk-y434jc1c.js.map} +1 -1
  128. package/dist/{chunk-bk2aheea.js → chunk-ykz38t0t.js} +2 -2
  129. package/dist/{chunk-bk2aheea.js.map → chunk-ykz38t0t.js.map} +1 -1
  130. package/dist/{chunk-ycsrpf47.js → chunk-yzhv93b0.js} +3 -3
  131. package/dist/{chunk-ycsrpf47.js.map → chunk-yzhv93b0.js.map} +1 -1
  132. package/dist/{chunk-rkgsvsrj.js → chunk-z5jydj5r.js} +2 -2
  133. package/dist/{chunk-rkgsvsrj.js.map → chunk-z5jydj5r.js.map} +1 -1
  134. package/dist/chunk-zmf3vhex.js +10 -0
  135. package/dist/{chunk-39dx7xrz.js.map → chunk-zmf3vhex.js.map} +4 -4
  136. package/dist/{chunk-x0jahbqj.js → chunk-zsfwcdqn.js} +2 -2
  137. package/dist/{chunk-x0jahbqj.js.map → chunk-zsfwcdqn.js.map} +1 -1
  138. package/dist/{chunk-kzstewtm.js → chunk-zsvav1dk.js} +2 -2
  139. package/dist/{chunk-kzstewtm.js.map → chunk-zsvav1dk.js.map} +1 -1
  140. package/dist/chunks/{ThemeProvider-CgK2mmVV.js → ThemeProvider-CbOx8IRl.js} +8 -3
  141. package/dist/chunks/ThemeProvider-CbOx8IRl.js.map +1 -0
  142. package/dist/client/index.js +1 -1
  143. package/dist/client/realtime/RealtimeClient.d.ts +8 -1
  144. package/dist/client/realtime/RealtimeClient.d.ts.map +1 -1
  145. package/dist/config/index.js +1 -1
  146. package/dist/console/run.js +2 -2
  147. package/dist/console/run.js.map +1 -1
  148. package/dist/container/index.js +2 -2
  149. package/dist/container/index.js.map +1 -1
  150. package/dist/database/index.js +2 -2
  151. package/dist/database/index.js.map +1 -1
  152. package/dist/email/index.js +2 -2
  153. package/dist/email/index.js.map +1 -1
  154. package/dist/facades/index.js +2 -2
  155. package/dist/facades/index.js.map +1 -1
  156. package/dist/foundation/index.js +2 -2
  157. package/dist/foundation/index.js.map +1 -1
  158. package/dist/http/index.js +2 -2
  159. package/dist/http/index.js.map +1 -1
  160. package/dist/i18n/dictionaryRuntime.js +2 -2
  161. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  162. package/dist/i18n/index.js +2 -2
  163. package/dist/i18n/index.js.map +2 -2
  164. package/dist/kernel/index.js +2 -2
  165. package/dist/kernel/index.js.map +2 -2
  166. package/dist/orm/index.js +2 -2
  167. package/dist/orm/index.js.map +1 -1
  168. package/dist/server/index.js +2 -2
  169. package/dist/server/index.js.map +1 -1
  170. package/dist/services/broadcast/BroadcastDriver.d.ts +3 -1
  171. package/dist/services/broadcast/BroadcastDriver.d.ts.map +1 -1
  172. package/dist/services/broadcast/BroadcastManager.d.ts.map +1 -1
  173. package/dist/services/broadcast/BroadcastServiceProvider.d.ts +10 -0
  174. package/dist/services/broadcast/BroadcastServiceProvider.d.ts.map +1 -1
  175. package/dist/services/broadcast/RedisBroadcastDriver.d.ts +155 -0
  176. package/dist/services/broadcast/RedisBroadcastDriver.d.ts.map +1 -0
  177. package/dist/services/broadcast/SocketHub.d.ts +9 -0
  178. package/dist/services/broadcast/SocketHub.d.ts.map +1 -1
  179. package/dist/services/broadcast/config.d.ts +16 -3
  180. package/dist/services/broadcast/config.d.ts.map +1 -1
  181. package/dist/services/broadcast/workerWarning.d.ts +10 -0
  182. package/dist/services/broadcast/workerWarning.d.ts.map +1 -0
  183. package/dist/services/index.d.ts +2 -1
  184. package/dist/services/index.d.ts.map +1 -1
  185. package/dist/services/index.js +3 -3
  186. package/dist/services/index.js.map +2 -2
  187. package/dist/services/queue/WorkerProcess.d.ts.map +1 -1
  188. package/dist/services/queue/work.js +2 -2
  189. package/dist/services/queue/work.js.map +5 -4
  190. package/dist/stats/route-table.js +1 -1
  191. package/dist/support/index.js +2 -2
  192. package/dist/support/index.js.map +1 -1
  193. package/dist/testing/index.js +1 -1
  194. package/dist/vitest/index.js +1 -1
  195. package/package.json +1 -1
  196. package/dist/chunk-39dx7xrz.js +0 -10
  197. package/dist/chunk-gvp6brdt.js +0 -57
  198. package/dist/chunk-tazvfppr.js +0 -5
  199. package/dist/chunk-vpgbn494.js +0 -24
  200. package/dist/chunks/ThemeProvider-CgK2mmVV.js.map +0 -1
  201. /package/dist/{chunk-4qpypa3h.js.map → chunk-3j6s5bmx.js.map} +0 -0
  202. /package/dist/{chunk-wqharhrp.js.map → chunk-5e22tm7m.js.map} +0 -0
  203. /package/dist/{chunk-j0cnsgjq.js.map → chunk-65s834td.js.map} +0 -0
  204. /package/dist/{chunk-xhmtph39.js.map → chunk-c4jnxmf2.js.map} +0 -0
  205. /package/dist/{chunk-8x73yyfs.js.map → chunk-j7v7dft7.js.map} +0 -0
  206. /package/dist/{chunk-rjm1kj8n.js.map → chunk-wbg2tza5.js.map} +0 -0
package/dist/ai/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$b as VZ,Ub as LQ,Vb as P6,Wb as C9,Zb as QZ,_b as ZZ,ac as GZ,bc as JZ,cc as WZ,dc as YZ,ec as XZ,fc as j,gc as F9,hc as KZ,ic as HZ,jc as N6}from"../chunk-d0wr9jk4.js";import{Ac as DZ}from"../chunk-675kzd7z.js";import{Gc as _Q,Rc as qQ}from"../chunk-08fcqny0.js";import{Xf as D6,Xg as w9,Zg as X9,_f as L6,_g as JQ,ah as $Z,ch as U6,og as l0,pg as v9,qg as W9,rg as M9}from"../chunk-z23h4s1a.js";import{dh as F6,fh as J$,gh as W$}from"../chunk-n1a2zj5z.js";import{kh as p9}from"../chunk-kc924zjz.js";import"../chunk-1f1sb3w7.js";import"../chunk-73v34hw8.js";import{Ai as OZ,li as NZ,mi as CZ}from"../chunk-2vc72qez.js";import"../chunk-mxbtcaed.js";import{nj as I9}from"../chunk-hnrzm5pf.js";import"../chunk-kzstewtm.js";import"../chunk-eevna943.js";import"../chunk-1kdga1b2.js";import"../chunk-ay8nat73.js";class h extends Error{status;body;requestId;constructor($,Q,Z){super(`Provider request failed with status ${$}: ${j6(Q)}`);this.name="ProviderHttpError",this.status=$,this.body=Q,this.requestId=Z}}class R9 extends Error{timeoutMs;constructor($){super(`Provider request timed out after ${$}ms`);this.name="ProviderTimeoutError",this.timeoutMs=$}}function j6($){let Q=PQ($);if(Q?.message)return Q.message;if(typeof $==="string")return $.slice(0,500);return"no error body"}function PQ($){if(!$||typeof $!=="object")return null;let Q=$,V=Q.error&&typeof Q.error==="object"?Q.error:$;if(typeof V.message!=="string"&&typeof V.code!=="string"&&typeof V.type!=="string")return null;let G=V.innererror?.code??V.code;return{message:V.message,type:V.type,code:G,param:V.param}}function b($){if(!$||typeof $!=="object")return{};let{status:Q,requestId:Z}=$;return{...typeof Q==="number"&&Q>=100&&Q<=599?{status:Q}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function I($){if($ instanceof R9)return{code:"provider_error",message:$.message,retryable:!0};if(k6($))return{code:"aborted",message:"The request was aborted.",retryable:!1};if($ instanceof h)return A6($.status,PQ($.body),$.message);if($ instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${$.message}`,retryable:!0};if($ instanceof Error)return{code:"provider_error",message:$.message,retryable:!1};return{code:"unknown",message:String($),retryable:!1}}function A6($,Q,Z){let V=Q?.message??Z,G=(Q?.code??"").toLowerCase(),J=(Q?.type??"").toLowerCase(),W=`${G} ${J} ${V}`.toLowerCase();if($===429){let X=G==="insufficient_quota"||W.includes("quota");return{code:"rate_limited",message:V,retryable:!X}}if($>=500||$===408||$===409)return{code:"provider_error",message:V,retryable:!0};if(T6(W))return{code:"context_length_exceeded",message:V,retryable:!1};if(E6(W))return{code:"content_filtered",message:V,retryable:!1};if(Q?.param?.startsWith("tools")||W.includes("invalid schema for function"))return{code:"invalid_tool_input",message:V,retryable:!1};return{code:"provider_error",message:V,retryable:!1}}function T6($){return $.includes("context_length_exceeded")||$.includes("maximum context length")||$.includes("context window")||$.includes("reduce the length")}function E6($){return $.includes("content_filter")||$.includes("content_policy_violation")||$.includes("responsibleaipolicyviolation")||$.includes("content management policy")}function k6($){if(!$||typeof $!=="object")return!1;let Q=$;return Q.name==="AbortError"||Q.code==="ABORT_ERR"}class w extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function c($,Q){if(Q.aborted)return Promise.reject(new w);return new Promise((Z,V)=>{let G=()=>V(new w);Q.addEventListener("abort",G,{once:!0}),$.then(Z,V).finally(()=>Q.removeEventListener("abort",G))})}function R(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function M($,Q){if(!Q)return $;let Z={inputTokens:$.inputTokens+(Q.inputTokens??0),outputTokens:$.outputTokens+(Q.outputTokens??0),totalTokens:$.totalTokens+(Q.totalTokens??0)};if(Q.reasoningTokens!==void 0||$.reasoningTokens!==void 0)Z.reasoningTokens=($.reasoningTokens??0)+(Q.reasoningTokens??0);if(Q.cachedInputTokens!==void 0||$.cachedInputTokens!==void 0)Z.cachedInputTokens=($.cachedInputTokens??0)+(Q.cachedInputTokens??0);if(Q.imageInputTokens!==void 0||$.imageInputTokens!==void 0)Z.imageInputTokens=($.imageInputTokens??0)+(Q.imageInputTokens??0);if(Q.imageOutputTokens!==void 0||$.imageOutputTokens!==void 0)Z.imageOutputTokens=($.imageOutputTokens??0)+(Q.imageOutputTokens??0);return Z}function S9($){if(!$.trim())return{};try{return JSON.parse($)}catch{}let Q=[],Z=!1,V=!1;for(let W of $){if(Z){if(V)V=!1;else if(W==="\\")V=!0;else if(W==='"')Z=!1;continue}if(W==='"')Z=!0;else if(W==="{")Q.push("}");else if(W==="[")Q.push("]");else if(W==="}"||W==="]")Q.pop()}let G=$;if(Z)G+='"';G=G.replace(/[,:]\s*$/,"");let J=Q.reverse().join("");try{return JSON.parse(G+J)}catch{try{return JSON.parse(G.replace(/,?\s*"[^"]*"\s*$/,"")+J)}catch{return{}}}}function j9($){return{name:"output",schema:$.toJSONSchema(),strict:W9($)}}function A9($,Q){let Z=$.safeParse(S9(Q));if(Z.ok===!0)return{ok:!0,value:Z.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Z.errors.join(", ")}`,retryable:!0}}}function T9($){if($.length>0)$[0];return $}function Y9($,Q,Z){let V=$.content[$.content.length-1];if(V&&V.type===Q){V.text=(V.text??"")+Z;return}$.content.push(Q==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function E9($,Q,Z){let V=$.content[$.content.length-1];if(V&&V.type==="reasoning"&&V.id===Q){V.text=(V.text??"")+Z;return}$.content.push(Q?{type:"reasoning",id:Q,text:Z}:{type:"reasoning",text:Z})}function Y$($){return K9($)}async function K9($,Q={}){let Z=`gen_${crypto.randomUUID()}`,V=await I6($);if(Q.settled?.(V),!V.ok){if($.logErrors!==!1&&V.error.code!=="aborted")x6(Z,V.error,Q.origin);if($.throwOnError)throw new H9({runId:Z,messages:V.messages,finishReason:V.finishReason,usage:V.usage,error:V.error})}return V}function x6($,Q,Z){let V=`[gemi/ai] generate() failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`,G={...Z,generateId:$,error:Q},J=!1;try{X9.error(V,G),J=!0}catch{}if(!J||Bun.env.NODE_ENV==="development")console.error(V,G)}async function I6($){let Q=$.messages??[];if(Q.length===0&&!$.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...Q];if($.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:$.prompt}],createdAt:new Date().toISOString()});let V={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},G=$.signal??new AbortController().signal,J=R(),W="stop",X,K={},Y="";try{let D=$.provider.stream({messages:[...Z],systemPrompt:$.instructions?.trim()?$.instructions:void 0,output:j9($.output),reasoning:$.reasoning,maxOutputTokens:$.maxOutputTokens,temperature:$.temperature,signal:$.signal})[Symbol.asyncIterator]();try{for(;;){let L=await c(Promise.resolve(D.next()),G);if(L.done)break;let F=L.value;switch(F.type){case"output-delta":Y+=F.delta;break;case"text-delta":Y9(V,"text",F.delta);break;case"reasoning-delta":E9(V,F.id,F.delta);break;case"finish":if(J=M(J,F.usage),!X)W=F.reason;break;case"error":W="error",X=F.error,K=b(F);break}}}finally{if(G.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(z){if(z instanceof w||G.aborted)W="aborted",X=w6(G);else W="error",X=$.provider.normalizeError(z),K=b(z)}let H=!1,B;if(!X)if(W==="length")X={code:"invalid_output",message:"The model ran out of output tokens before finishing its structured answer, so it was cut off. Raise maxOutputTokens, or ask for a shorter answer.",retryable:!0};else if(!Y.trim())X={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let z=A9($.output,Y);if(z.ok===!0)H=!0,B=z.value;else X=z.error}if(H)V.content.push({type:"output",value:B});else if(Y)Y9(V,"text",Y);for(let z of V.content)if((z.type==="text"||z.type==="reasoning")&&typeof z.text==="string")z.text=T9(z.text);if(V.finishReason=W,V.usage=J,Z.push(V),H)return{ok:!0,output:B,messages:Z,usage:J,finishReason:W};return{ok:!1,error:{...X,...K},messages:Z,usage:J,finishReason:W}}function w6($){return $.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}class z9 extends j{id;code="attachment_not_found";constructor($){super(`No attachment ${$}.`);this.id=$;this.name="AttachmentNotFoundError"}}class g extends j{code="invalid_attachment_scope";constructor($){super($);this.name="InvalidAttachmentScopeError"}}function X$($){if(!$||typeof $.key!=="string"||$.key.length===0)throw new g("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return $}var v="gemi_att_";function K$(){return`${v}${crypto.randomUUID()}`}class p{store;storage;scope;constructor($,Q,Z){this.store=$;this.storage=Q;this.scope=Z;X$(Z)}get scopeKey(){return this.scope.key}async get($){let Q=await this.store.find(this.scope,$);if(!Q||Q.scopeKey!==this.scope.key)throw new z9($);return Q}async read($){return await this.readRecord($,await this.get($))}async readRecord($,Q){if(!Q.objectName)throw new z9($);return await this.storage.read({name:Q.objectName})}async file($){let Q=await this.get($),V=(await this.readRecord($,Q)).body,G=V instanceof Blob?V:V?await new Response(V).blob():new Blob([]);return new File([G],Q.name,{type:Q.mimeType})}async put($,Q={}){let Z=K$(),V=Q.mimeType??$.type??"",G=Q.name??($ instanceof File?$.name:Z),J=await this.storage.put({name:H$(Z,G),body:$,contentType:V||void 0}),W={id:Z,scopeKey:this.scope.key,objectName:J,name:G,mimeType:V||"application/octet-stream",size:$.size,createdAt:new Date().toISOString(),destination:Q.fileId?"both":"storage",...Q.fileId?{fileId:Q.fileId}:{}};return await this.store.put(this.scope,W),W}}function H$($,Q){let Z=/\.([A-Za-z0-9]{1,8})$/.exec(Q);return`attachments/${$}${Z?`.${Z[1].toLowerCase()}`:""}`}class k9{rows=new Map;async put($,Q){X$($),this.rows.set(Q.id,{...Q,scopeKey:$.key})}async find($,Q){X$($);let Z=this.rows.get(Q);if(!Z||Z.scopeKey!==$.key)return null;return Z}get size(){return this.rows.size}}var t=new k9;class B9{jobs=new Map;async create($){if(this.jobs.has($.id))throw Error(`A background job with the id ${$.id} already exists.`);let Q=Date.now(),{deadlineMs:Z,...V}=$,G={...structuredClone(V),state:"running",createdAt:Q,updatedAt:Q,deadlineAt:Q+Z};return this.jobs.set(G.id,G),this.trim(G.threadId),structuredClone(G)}async get($){let Q=this.jobs.get($);return Q?structuredClone(Q):null}async listForThread($,Q={}){let Z=[];for(let V of this.jobs.values()){if(V.threadId!==$)continue;if(Q.states&&!Q.states.includes(V.state))continue;Z.push(V)}return Z.sort(NQ),(Q.limit===void 0?Z:Z.slice(0,Q.limit)).map((V)=>structuredClone(V))}async transition($,Q,Z){let V=this.jobs.get($);if(!V||!Q.includes(V.state))return!1;let G=structuredClone(Z),J=Date.now();if(Object.assign(V,G,{updatedAt:J}),G.state&&G.state!=="running"&&V.settledAt===void 0)V.settledAt=G.settledAt??J;return!0}async overdue($,Q){let Z=[];for(let V of this.jobs.values())if(V.state==="running"&&V.deadlineAt<=$)Z.push(V);return Z.sort((V,G)=>V.deadlineAt-G.deadlineAt),Z.slice(0,Math.max(0,Q)).map((V)=>structuredClone(V))}async now(){return Date.now()}trim($){let Q=[...this.jobs.values()].filter((Z)=>Z.threadId===$&&Z.state!=="running").sort(NQ);for(let Z of Q.slice(200))this.jobs.delete(Z.id)}}function NQ($,Q){return Q.createdAt-$.createdAt||($.id<Q.id?1:$.id>Q.id?-1:0)}var MQ=Symbol.for("gemi.ai.JobHandle");class b9{id;toolCallId;summary;deadlineAt;[MQ]=!0;constructor($,Q,Z,V){this.id=$;this.toolCallId=Q;this.summary=Z;this.deadlineAt=V}}function RQ($){return typeof $==="object"&&$!==null&&$[MQ]===!0}class D9 extends j{code="jobs_require_thread";constructor($){super($,{retryable:!1});this.name="JobsRequireThreadError"}}var a=new B9,b6=["running","ok","error"],y={get store(){return a},use($){a=$},get($){return a.get($)},async settle($,Q){return x9(a,$,Q)},async fail($,Q){return x9(a,$,{error:Q})},async sweep($={}){let Q=a,Z=$.limit??100,V=await z$(Q),G=0;for(let J of await Q.overdue(V,Z))if(await B$(Q,J))G++;return G}};async function z$($){return $.now?await $.now():Date.now()}function B$($,Q){return $.transition(Q.id,["running"],{state:"error",error:{code:"timeout",message:`The background job for "${Q.toolName}" did not finish before its deadline, so it was given up on. Its result, if it ever arrives, is ignored.`,toolCallId:Q.toolCallId,retryable:!0}})}async function x9($,Q,Z){let V=await $.get(Q);if(!V||V.state!=="running")return!1;let G=Z.usage?M(V.usage??R(),Z.usage):void 0;if("error"in Z)return $.transition(Q,["running"],{state:"error",error:f6(V,Z.error),...G?{usage:G}:{}});return $.transition(Q,["running"],{state:"ok",output:SQ(Z.output,V),...G?{usage:G}:{}})}function f6($,Q){if(typeof Q==="string")return{code:"tool_error",message:Q,toolCallId:$.toolCallId,retryable:!0};if(Q instanceof Error){let Z={code:"tool_error",message:Q.message,toolCallId:$.toolCallId,retryable:Q instanceof j?Q.retryable:!0};if(!(Q instanceof j))console.error(`The background job ${$.job??"(tracked)"} for "${$.toolName}" failed.`,Q);return F9(Z,{source:"tool",toolName:$.toolName,cause:Q})}return{code:Q.code??"tool_error",message:String(Q.message),toolCallId:$.toolCallId,retryable:Q.retryable??!0}}function SQ($,Q){if($===void 0)return null;try{return JSON.parse(JSON.stringify($))}catch(Z){throw Error(`The output of the background job for "${Q.toolName}" is not JSON: ${String(Z)}`)}}var D$=3600000;function jQ($){let Q=null,Z=(V,G,J={})=>{if($.async===void 0)throw new j(`"${$.toolName}" called ctx.jobs, but the tool does not declare \`async\`. Add \`async: { deadlineMs }\` to its definition.`,{retryable:!1});if(!$.jobs||!$.threadId)throw new D9(`"${$.toolName}" can only run in the background on a conversation the server keeps (a turn with a threadId), and this one has none.`);if($.depth>0)throw new D9(`"${$.toolName}" can only run in the background from the top-level agent, not from a sub-agent.`);if(Q)throw new j(`"${$.toolName}" started a background job already: a tool call has at most one.`,{retryable:!1});let W=J.deadlineMs??$.async.deadlineMs??D$;if(!Number.isFinite(W)||W<=0)throw new j(`A job's deadlineMs must be a positive number; got ${W}.`);let{jobs:X,threadId:K}=$;return Q=(async()=>{let Y=y.store,H=(await Y.listForThread(K,{limit:50})).find((D)=>D.toolCallId===$.toolCallId);if(H)return CQ(H);let B=async()=>{let D=await Y.create({id:`ajob_${crypto.randomUUID()}`,threadId:K,runId:$.runId,toolCallId:$.toolCallId,toolName:$.toolName,owner:X.owner,job:V?V.name:null,...J.summary!==void 0?{summary:SQ(J.summary,$)}:{},attachmentScope:$.attachments?.scopeKey??null,deadlineMs:W});if(V)try{await v6(V,{jobId:D.id,args:G})}catch(L){if(Y.transaction)throw L;throw await Y.transition(D.id,["running"],{state:"error",error:{code:"tool_error",message:`The background job for "${$.toolName}" could not be queued.`,toolCallId:$.toolCallId,retryable:!0}}).catch(()=>{}),L}return D},z=Y.transaction?await Y.transaction(B):await B();return CQ(z)})(),Q};return{start:(V,G,J)=>Z(V,G,J),track:(V)=>Z(null,void 0,V)}}function CQ($){return new b9($.id,$.toolCallId,$.summary,$.deadlineAt)}function v6($,Q){if($.name==="unset"||!$.name)throw Error("Cannot start an AgentJob with no `static name`.");return I9(qQ).push($,JSON.stringify([Q]))}class F$ extends _Q{attachments=t;attachmentStorage=w9;constructor(){super();let $=this.run;this.run=(Q)=>this.$runEnvelope(Q,$)}onDeadletter($,...Q){let Z=Q[0];if(!Z?.jobId)return;x9(y.store,Z.jobId,{error:$}).catch((V)=>{console.error(`Could not record the failure of background job ${Z.jobId}.`,V)})}async $runEnvelope($,Q){let Z=y.store,V=await Z.get($.jobId);if(!V||V.state!=="running")return;let G=new AQ(V,this),J;try{J=await Q.call(this,$.args,G)}catch(W){throw await OQ(Z,V.id,G.usage),W}if(this.$outcome)return await OQ(Z,V.id,G.usage),J;return await x9(Z,V.id,{output:J,usage:G.usage}),J}}async function OQ($,Q,Z){if(Z.totalTokens===0&&Z.inputTokens===0&&Z.outputTokens===0)return;let V=await $.get(Q);if(!V)return;await $.transition(Q,b6,{usage:M(V.usage??R(),Z)}).catch(()=>{})}class AQ{id;threadId;toolCallId;toolName;owner;summary;signal=new AbortController().signal;usage=R();attachments;constructor($,Q){this.id=$.id,this.threadId=$.threadId,this.toolCallId=$.toolCallId,this.toolName=$.toolName,this.owner=$.owner,this.summary=$.summary;let Z=$.attachmentScope?new p(Q.attachments,Q.attachmentStorage,{key:$.attachmentScope}):null,V=()=>{if(!Z)throw new g("The run that started this job had no attachment scope, so the job cannot store or read files. See `attachmentScope()` on the controller.");return Z};this.attachments={put:(G,J={})=>V().put(G,J),get:(G)=>V().get(G),read:(G)=>V().read(G),file:(G)=>V().file(G)}}generate($){return K9($,{origin:{threadId:this.threadId,toolCallId:this.toolCallId,jobId:this.id},settled:(Q)=>{this.usage=M(this.usage,Q.usage)}})}async generateImage($,Q){let{name:Z,...V}=Q,G=await $.generate({...V,signal:this.signal});return this.park($,G,Z)}async editImage($,Q){let{name:Z,images:V,mask:G,...J}=Q,W=async(K)=>typeof K==="string"?await this.attachments.file(K):K,X=await $.edit({...J,images:await Promise.all(V.map(W)),...G?{mask:await W(G)}:{},signal:this.signal});return this.park($,X,Z)}async park($,Q,Z){this.usage=M(this.usage,Q.usage);let V=Q.mimeType==="image/jpeg"?"jpg":"png";return{attachment:await this.attachments.put(Q.image,{name:Z??`${$.name}.${V}`,mimeType:Q.mimeType}),size:Q.size,mimeType:Q.mimeType,usage:Q.usage}}}function m($){let Q=new Set;for(let Z of $)for(let V of Z.content??[]){if(V.type!=="tool-call")continue;for(let G of V.attachments??[])if(G&&"shown"in G&&G.shown)Q.add(G.shown.messageId)}return Q}function L9($){if($.length===0)return[];let Q=m($),Z=[0];for(let V=1;V<$.length;V++){let G=$[V];if(G.role==="user"&&!Q.has(G.id))Z.push(V)}return Z}function y6($){let Q=L9($);return Q.map((Z,V)=>$.slice(Z,Q[V+1]??$.length))}function EQ($){try{return JSON.stringify($).length}catch{return 0}}var h6=4,kQ=10,xQ="[Earlier turns of this conversation are not shown.]";function r($,Q={}){let Z=[...$],V=L9(Z),G=g6(Q),J=f9(Q.maxTurns)??1/0,W=Math.max(1,Math.floor(f9(Q.step)??kQ));if(V.length<=1||J>=V.length&&G===1/0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let X=Array.from({length:Z.length+1},()=>0);if(G!==1/0)for(let U=Z.length-1;U>=0;U--)X[U]=X[U+1]+EQ(Z[U]);let K=(U)=>V.length-U<=J&&X[V[U]]<=G,Y=-1;for(let U=0;U<V.length;U+=W)if(K(U)){Y=U;break}if(Y<0){for(let U=0;U<V.length;U++)if(K(U)){Y=U;break}}if(Y<0)Y=V.length-1;if(Y===0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let H=V[Y],B=Z.slice(0,H),z=B.filter((U)=>U.role==="system"),D=u6(B,Z.slice(H)),L={turns:Y,messages:B.length-z.length},F=typeof Q.note==="function"?Q.note(L):Q.note===void 0?xQ:Q.note;if(F){let U=D[0];D[0]={...U,content:[{type:"text",text:F},...U.content]}}return{messages:[...z,...D],start:H,omittedTurns:L.turns,omittedMessages:L.messages}}function f9($){return typeof $==="number"&&$>0?$:void 0}function g6($){let Q=f9($.maxBytes)??1/0,Z=f9($.maxTokens);return Math.min(Q,Z===void 0?1/0:Z*h6)}function TQ($,Q){let Z=Array.isArray($?.namespaces)?$.namespaces:[],V=Array.isArray($?.loaded)?$.loaded:[];return Q.namespace?Z.includes(Q.namespace):V.includes(String(Q.name))}function L$($){return Array.isArray($.toolSearches)?$.toolSearches:[]}function u6($,Q){let Z=[];for(let Y of $)for(let H of Y.content??[])if(H.type==="tool-call")Z.push(...L$(H));if(Z.length===0)return Q;let V=[],G=new Set,J;if(Q.forEach((Y,H)=>{(Y.content??[]).forEach((B,z)=>{if(B.type!=="tool-call"||B.partial)return;if(V.push(...L$(B)),V.some((L)=>TQ(L,B)))return;let D=Z.filter((L)=>TQ(L,B));if(D.length===0)return;for(let L of D)G.add(L);J??={message:H,part:z}})}),!J)return Q;let W=Z.filter((Y)=>G.has(Y)),X=[...Q],K=X[J.message];return X[J.message]={...K,content:K.content.map((Y,H)=>H===J.part&&Y.type==="tool-call"?{...Y,toolSearches:[...W,...L$(Y)]}:Y)},X}var fQ=1000,c6=24000,p6=20000,vQ=1e5,m6=120000,yQ=["You keep a running summary of a conversation between a user and an AI assistant.","The assistant will continue the conversation with only your summary and the latest turns, so the summary has to carry everything from the earlier turns it may still need.","You are given the summary so far (possibly empty) and the turns that came after it. Answer the updated summary, which replaces the old one.","Keep: the user's goals, preferences and constraints; decisions made and why; facts, names, ids, numbers, dates, file names and URLs that may matter later; what tools were used and their important results; open questions and unfinished work.","Drop greetings, repetition and anything later turns superseded. Do not invent anything, and do not answer the user.","Write terse prose or bullet points, in the language of the conversation."].join(" "),hQ="[Summary of the earlier turns of this conversation, which are not shown:]",l6=8;class N${ttlMs;threads=new Map;lastSweep=0;constructor($=86400000){this.ttlMs=$}async loadSummaries($){this.sweep();let Q=this.threads.get($);if(!Q)return[];return Q.touchedAt=Date.now(),Q.summaries.slice()}async saveSummary($,Q){this.sweep();let Z=this.threads.get($)??{summaries:[],touchedAt:Date.now()};Z.summaries=h9(Z.summaries,Q),Z.touchedAt=Date.now(),this.threads.set($,Z)}delete($){this.threads.delete($)}sweep($=Date.now()){if($-this.lastSweep<60000)return;this.lastSweep=$;for(let[Q,Z]of this.threads)if($-Z.touchedAt>this.ttlMs)this.threads.delete(Q)}}function h9($,Q){return[Q,...$.filter((Z)=>Z.cutMessageId!==Q.cutMessageId)].slice(0,l6)}var C$=new N$;function gQ($){let Q=$;return typeof Q?.loadSummaries==="function"&&typeof Q?.saveSummary==="function"}function uQ($,Q,Z){let V=u(Z.maxSummaryTokens)??fQ,G=(K)=>Math.max(1,K-V),J={...Q,...u(Q.maxTokens)?{maxTokens:G(Q.maxTokens)}:{},...u(Q.maxBytes)?{maxBytes:Math.max(1,Q.maxBytes-V*P$)}:{}},W=d6(Q,Z),X={...J,note:!1,...W?{maxTokens:Math.min(J.maxTokens??1/0,G(W))}:{}};return{plain:J,cut:r($,X),maxSummaryTokens:V}}function d6($,Q){if(Q.triggerTokens===!1)return;let Z=u(Q.triggerTokens||void 0);if(Z)return Z;if(u($.maxTokens)||u($.maxBytes))return;return vQ}async function cQ($){let{history:Q,window:Z,compact:V}=$,{plain:G,cut:J,maxSummaryTokens:W}=uQ(Q,Z,V);if(J.omittedTurns===0)return J.messages;let X=`${Q[J.start].id}:${J.start}`,K=$.memo?.get(X);if(K===void 0){try{K=await t6($,J.start,W)}catch(D){if($.signal.aborted)throw D;K=null}if(!$.signal.aborted)$.memo?.set(X,K)}if(!K)return r(Q,G).messages;let Y=Q.length-J.start,H=J.messages.slice(0,J.messages.length-Y),B=J.messages.slice(J.messages.length-Y),z=Q[J.start];return[...H,{id:`summary_${z.id}`,role:"user",content:[{type:"text",text:`${hQ}
2
+ import{$b as VZ,Ub as LQ,Vb as P6,Wb as C9,Zb as QZ,_b as ZZ,ac as GZ,bc as JZ,cc as WZ,dc as YZ,ec as XZ,fc as j,gc as F9,hc as KZ,ic as HZ,jc as N6}from"../chunk-pya4rqm2.js";import{Ac as DZ}from"../chunk-675kzd7z.js";import{Gc as _Q,Rc as qQ}from"../chunk-92sk56n0.js";import{Xf as D6,Xg as w9,Zg as X9,_f as L6,_g as JQ,ah as $Z,ch as U6,og as l0,pg as v9,qg as W9,rg as M9}from"../chunk-n0r5xyk2.js";import{dh as F6,fh as J$,gh as W$}from"../chunk-n1a2zj5z.js";import{kh as p9}from"../chunk-kc924zjz.js";import"../chunk-mqtfaqx5.js";import"../chunk-pe46a5a5.js";import{Bi as OZ,mi as NZ,ni as CZ}from"../chunk-qycwjzsv.js";import"../chunk-mvkz22p4.js";import{oj as I9}from"../chunk-rpyczdta.js";import"../chunk-zsvav1dk.js";import"../chunk-nnarmbjv.js";import"../chunk-nkzmk7v3.js";import"../chunk-17dndh5z.js";class h extends Error{status;body;requestId;constructor($,Q,Z){super(`Provider request failed with status ${$}: ${j6(Q)}`);this.name="ProviderHttpError",this.status=$,this.body=Q,this.requestId=Z}}class R9 extends Error{timeoutMs;constructor($){super(`Provider request timed out after ${$}ms`);this.name="ProviderTimeoutError",this.timeoutMs=$}}function j6($){let Q=PQ($);if(Q?.message)return Q.message;if(typeof $==="string")return $.slice(0,500);return"no error body"}function PQ($){if(!$||typeof $!=="object")return null;let Q=$,V=Q.error&&typeof Q.error==="object"?Q.error:$;if(typeof V.message!=="string"&&typeof V.code!=="string"&&typeof V.type!=="string")return null;let G=V.innererror?.code??V.code;return{message:V.message,type:V.type,code:G,param:V.param}}function b($){if(!$||typeof $!=="object")return{};let{status:Q,requestId:Z}=$;return{...typeof Q==="number"&&Q>=100&&Q<=599?{status:Q}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function I($){if($ instanceof R9)return{code:"provider_error",message:$.message,retryable:!0};if(k6($))return{code:"aborted",message:"The request was aborted.",retryable:!1};if($ instanceof h)return A6($.status,PQ($.body),$.message);if($ instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${$.message}`,retryable:!0};if($ instanceof Error)return{code:"provider_error",message:$.message,retryable:!1};return{code:"unknown",message:String($),retryable:!1}}function A6($,Q,Z){let V=Q?.message??Z,G=(Q?.code??"").toLowerCase(),J=(Q?.type??"").toLowerCase(),W=`${G} ${J} ${V}`.toLowerCase();if($===429){let X=G==="insufficient_quota"||W.includes("quota");return{code:"rate_limited",message:V,retryable:!X}}if($>=500||$===408||$===409)return{code:"provider_error",message:V,retryable:!0};if(T6(W))return{code:"context_length_exceeded",message:V,retryable:!1};if(E6(W))return{code:"content_filtered",message:V,retryable:!1};if(Q?.param?.startsWith("tools")||W.includes("invalid schema for function"))return{code:"invalid_tool_input",message:V,retryable:!1};return{code:"provider_error",message:V,retryable:!1}}function T6($){return $.includes("context_length_exceeded")||$.includes("maximum context length")||$.includes("context window")||$.includes("reduce the length")}function E6($){return $.includes("content_filter")||$.includes("content_policy_violation")||$.includes("responsibleaipolicyviolation")||$.includes("content management policy")}function k6($){if(!$||typeof $!=="object")return!1;let Q=$;return Q.name==="AbortError"||Q.code==="ABORT_ERR"}class w extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function c($,Q){if(Q.aborted)return Promise.reject(new w);return new Promise((Z,V)=>{let G=()=>V(new w);Q.addEventListener("abort",G,{once:!0}),$.then(Z,V).finally(()=>Q.removeEventListener("abort",G))})}function R(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function M($,Q){if(!Q)return $;let Z={inputTokens:$.inputTokens+(Q.inputTokens??0),outputTokens:$.outputTokens+(Q.outputTokens??0),totalTokens:$.totalTokens+(Q.totalTokens??0)};if(Q.reasoningTokens!==void 0||$.reasoningTokens!==void 0)Z.reasoningTokens=($.reasoningTokens??0)+(Q.reasoningTokens??0);if(Q.cachedInputTokens!==void 0||$.cachedInputTokens!==void 0)Z.cachedInputTokens=($.cachedInputTokens??0)+(Q.cachedInputTokens??0);if(Q.imageInputTokens!==void 0||$.imageInputTokens!==void 0)Z.imageInputTokens=($.imageInputTokens??0)+(Q.imageInputTokens??0);if(Q.imageOutputTokens!==void 0||$.imageOutputTokens!==void 0)Z.imageOutputTokens=($.imageOutputTokens??0)+(Q.imageOutputTokens??0);return Z}function S9($){if(!$.trim())return{};try{return JSON.parse($)}catch{}let Q=[],Z=!1,V=!1;for(let W of $){if(Z){if(V)V=!1;else if(W==="\\")V=!0;else if(W==='"')Z=!1;continue}if(W==='"')Z=!0;else if(W==="{")Q.push("}");else if(W==="[")Q.push("]");else if(W==="}"||W==="]")Q.pop()}let G=$;if(Z)G+='"';G=G.replace(/[,:]\s*$/,"");let J=Q.reverse().join("");try{return JSON.parse(G+J)}catch{try{return JSON.parse(G.replace(/,?\s*"[^"]*"\s*$/,"")+J)}catch{return{}}}}function j9($){return{name:"output",schema:$.toJSONSchema(),strict:W9($)}}function A9($,Q){let Z=$.safeParse(S9(Q));if(Z.ok===!0)return{ok:!0,value:Z.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Z.errors.join(", ")}`,retryable:!0}}}function T9($){if($.length>0)$[0];return $}function Y9($,Q,Z){let V=$.content[$.content.length-1];if(V&&V.type===Q){V.text=(V.text??"")+Z;return}$.content.push(Q==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function E9($,Q,Z){let V=$.content[$.content.length-1];if(V&&V.type==="reasoning"&&V.id===Q){V.text=(V.text??"")+Z;return}$.content.push(Q?{type:"reasoning",id:Q,text:Z}:{type:"reasoning",text:Z})}function Y$($){return K9($)}async function K9($,Q={}){let Z=`gen_${crypto.randomUUID()}`,V=await I6($);if(Q.settled?.(V),!V.ok){if($.logErrors!==!1&&V.error.code!=="aborted")x6(Z,V.error,Q.origin);if($.throwOnError)throw new H9({runId:Z,messages:V.messages,finishReason:V.finishReason,usage:V.usage,error:V.error})}return V}function x6($,Q,Z){let V=`[gemi/ai] generate() failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`,G={...Z,generateId:$,error:Q},J=!1;try{X9.error(V,G),J=!0}catch{}if(!J||Bun.env.NODE_ENV==="development")console.error(V,G)}async function I6($){let Q=$.messages??[];if(Q.length===0&&!$.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...Q];if($.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:$.prompt}],createdAt:new Date().toISOString()});let V={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},G=$.signal??new AbortController().signal,J=R(),W="stop",X,K={},Y="";try{let D=$.provider.stream({messages:[...Z],systemPrompt:$.instructions?.trim()?$.instructions:void 0,output:j9($.output),reasoning:$.reasoning,maxOutputTokens:$.maxOutputTokens,temperature:$.temperature,signal:$.signal})[Symbol.asyncIterator]();try{for(;;){let L=await c(Promise.resolve(D.next()),G);if(L.done)break;let F=L.value;switch(F.type){case"output-delta":Y+=F.delta;break;case"text-delta":Y9(V,"text",F.delta);break;case"reasoning-delta":E9(V,F.id,F.delta);break;case"finish":if(J=M(J,F.usage),!X)W=F.reason;break;case"error":W="error",X=F.error,K=b(F);break}}}finally{if(G.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(z){if(z instanceof w||G.aborted)W="aborted",X=w6(G);else W="error",X=$.provider.normalizeError(z),K=b(z)}let H=!1,B;if(!X)if(W==="length")X={code:"invalid_output",message:"The model ran out of output tokens before finishing its structured answer, so it was cut off. Raise maxOutputTokens, or ask for a shorter answer.",retryable:!0};else if(!Y.trim())X={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let z=A9($.output,Y);if(z.ok===!0)H=!0,B=z.value;else X=z.error}if(H)V.content.push({type:"output",value:B});else if(Y)Y9(V,"text",Y);for(let z of V.content)if((z.type==="text"||z.type==="reasoning")&&typeof z.text==="string")z.text=T9(z.text);if(V.finishReason=W,V.usage=J,Z.push(V),H)return{ok:!0,output:B,messages:Z,usage:J,finishReason:W};return{ok:!1,error:{...X,...K},messages:Z,usage:J,finishReason:W}}function w6($){return $.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}class z9 extends j{id;code="attachment_not_found";constructor($){super(`No attachment ${$}.`);this.id=$;this.name="AttachmentNotFoundError"}}class g extends j{code="invalid_attachment_scope";constructor($){super($);this.name="InvalidAttachmentScopeError"}}function X$($){if(!$||typeof $.key!=="string"||$.key.length===0)throw new g("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return $}var v="gemi_att_";function K$(){return`${v}${crypto.randomUUID()}`}class p{store;storage;scope;constructor($,Q,Z){this.store=$;this.storage=Q;this.scope=Z;X$(Z)}get scopeKey(){return this.scope.key}async get($){let Q=await this.store.find(this.scope,$);if(!Q||Q.scopeKey!==this.scope.key)throw new z9($);return Q}async read($){return await this.readRecord($,await this.get($))}async readRecord($,Q){if(!Q.objectName)throw new z9($);return await this.storage.read({name:Q.objectName})}async file($){let Q=await this.get($),V=(await this.readRecord($,Q)).body,G=V instanceof Blob?V:V?await new Response(V).blob():new Blob([]);return new File([G],Q.name,{type:Q.mimeType})}async put($,Q={}){let Z=K$(),V=Q.mimeType??$.type??"",G=Q.name??($ instanceof File?$.name:Z),J=await this.storage.put({name:H$(Z,G),body:$,contentType:V||void 0}),W={id:Z,scopeKey:this.scope.key,objectName:J,name:G,mimeType:V||"application/octet-stream",size:$.size,createdAt:new Date().toISOString(),destination:Q.fileId?"both":"storage",...Q.fileId?{fileId:Q.fileId}:{}};return await this.store.put(this.scope,W),W}}function H$($,Q){let Z=/\.([A-Za-z0-9]{1,8})$/.exec(Q);return`attachments/${$}${Z?`.${Z[1].toLowerCase()}`:""}`}class k9{rows=new Map;async put($,Q){X$($),this.rows.set(Q.id,{...Q,scopeKey:$.key})}async find($,Q){X$($);let Z=this.rows.get(Q);if(!Z||Z.scopeKey!==$.key)return null;return Z}get size(){return this.rows.size}}var t=new k9;class B9{jobs=new Map;async create($){if(this.jobs.has($.id))throw Error(`A background job with the id ${$.id} already exists.`);let Q=Date.now(),{deadlineMs:Z,...V}=$,G={...structuredClone(V),state:"running",createdAt:Q,updatedAt:Q,deadlineAt:Q+Z};return this.jobs.set(G.id,G),this.trim(G.threadId),structuredClone(G)}async get($){let Q=this.jobs.get($);return Q?structuredClone(Q):null}async listForThread($,Q={}){let Z=[];for(let V of this.jobs.values()){if(V.threadId!==$)continue;if(Q.states&&!Q.states.includes(V.state))continue;Z.push(V)}return Z.sort(NQ),(Q.limit===void 0?Z:Z.slice(0,Q.limit)).map((V)=>structuredClone(V))}async transition($,Q,Z){let V=this.jobs.get($);if(!V||!Q.includes(V.state))return!1;let G=structuredClone(Z),J=Date.now();if(Object.assign(V,G,{updatedAt:J}),G.state&&G.state!=="running"&&V.settledAt===void 0)V.settledAt=G.settledAt??J;return!0}async overdue($,Q){let Z=[];for(let V of this.jobs.values())if(V.state==="running"&&V.deadlineAt<=$)Z.push(V);return Z.sort((V,G)=>V.deadlineAt-G.deadlineAt),Z.slice(0,Math.max(0,Q)).map((V)=>structuredClone(V))}async now(){return Date.now()}trim($){let Q=[...this.jobs.values()].filter((Z)=>Z.threadId===$&&Z.state!=="running").sort(NQ);for(let Z of Q.slice(200))this.jobs.delete(Z.id)}}function NQ($,Q){return Q.createdAt-$.createdAt||($.id<Q.id?1:$.id>Q.id?-1:0)}var MQ=Symbol.for("gemi.ai.JobHandle");class b9{id;toolCallId;summary;deadlineAt;[MQ]=!0;constructor($,Q,Z,V){this.id=$;this.toolCallId=Q;this.summary=Z;this.deadlineAt=V}}function RQ($){return typeof $==="object"&&$!==null&&$[MQ]===!0}class D9 extends j{code="jobs_require_thread";constructor($){super($,{retryable:!1});this.name="JobsRequireThreadError"}}var a=new B9,b6=["running","ok","error"],y={get store(){return a},use($){a=$},get($){return a.get($)},async settle($,Q){return x9(a,$,Q)},async fail($,Q){return x9(a,$,{error:Q})},async sweep($={}){let Q=a,Z=$.limit??100,V=await z$(Q),G=0;for(let J of await Q.overdue(V,Z))if(await B$(Q,J))G++;return G}};async function z$($){return $.now?await $.now():Date.now()}function B$($,Q){return $.transition(Q.id,["running"],{state:"error",error:{code:"timeout",message:`The background job for "${Q.toolName}" did not finish before its deadline, so it was given up on. Its result, if it ever arrives, is ignored.`,toolCallId:Q.toolCallId,retryable:!0}})}async function x9($,Q,Z){let V=await $.get(Q);if(!V||V.state!=="running")return!1;let G=Z.usage?M(V.usage??R(),Z.usage):void 0;if("error"in Z)return $.transition(Q,["running"],{state:"error",error:f6(V,Z.error),...G?{usage:G}:{}});return $.transition(Q,["running"],{state:"ok",output:SQ(Z.output,V),...G?{usage:G}:{}})}function f6($,Q){if(typeof Q==="string")return{code:"tool_error",message:Q,toolCallId:$.toolCallId,retryable:!0};if(Q instanceof Error){let Z={code:"tool_error",message:Q.message,toolCallId:$.toolCallId,retryable:Q instanceof j?Q.retryable:!0};if(!(Q instanceof j))console.error(`The background job ${$.job??"(tracked)"} for "${$.toolName}" failed.`,Q);return F9(Z,{source:"tool",toolName:$.toolName,cause:Q})}return{code:Q.code??"tool_error",message:String(Q.message),toolCallId:$.toolCallId,retryable:Q.retryable??!0}}function SQ($,Q){if($===void 0)return null;try{return JSON.parse(JSON.stringify($))}catch(Z){throw Error(`The output of the background job for "${Q.toolName}" is not JSON: ${String(Z)}`)}}var D$=3600000;function jQ($){let Q=null,Z=(V,G,J={})=>{if($.async===void 0)throw new j(`"${$.toolName}" called ctx.jobs, but the tool does not declare \`async\`. Add \`async: { deadlineMs }\` to its definition.`,{retryable:!1});if(!$.jobs||!$.threadId)throw new D9(`"${$.toolName}" can only run in the background on a conversation the server keeps (a turn with a threadId), and this one has none.`);if($.depth>0)throw new D9(`"${$.toolName}" can only run in the background from the top-level agent, not from a sub-agent.`);if(Q)throw new j(`"${$.toolName}" started a background job already: a tool call has at most one.`,{retryable:!1});let W=J.deadlineMs??$.async.deadlineMs??D$;if(!Number.isFinite(W)||W<=0)throw new j(`A job's deadlineMs must be a positive number; got ${W}.`);let{jobs:X,threadId:K}=$;return Q=(async()=>{let Y=y.store,H=(await Y.listForThread(K,{limit:50})).find((D)=>D.toolCallId===$.toolCallId);if(H)return CQ(H);let B=async()=>{let D=await Y.create({id:`ajob_${crypto.randomUUID()}`,threadId:K,runId:$.runId,toolCallId:$.toolCallId,toolName:$.toolName,owner:X.owner,job:V?V.name:null,...J.summary!==void 0?{summary:SQ(J.summary,$)}:{},attachmentScope:$.attachments?.scopeKey??null,deadlineMs:W});if(V)try{await v6(V,{jobId:D.id,args:G})}catch(L){if(Y.transaction)throw L;throw await Y.transition(D.id,["running"],{state:"error",error:{code:"tool_error",message:`The background job for "${$.toolName}" could not be queued.`,toolCallId:$.toolCallId,retryable:!0}}).catch(()=>{}),L}return D},z=Y.transaction?await Y.transaction(B):await B();return CQ(z)})(),Q};return{start:(V,G,J)=>Z(V,G,J),track:(V)=>Z(null,void 0,V)}}function CQ($){return new b9($.id,$.toolCallId,$.summary,$.deadlineAt)}function v6($,Q){if($.name==="unset"||!$.name)throw Error("Cannot start an AgentJob with no `static name`.");return I9(qQ).push($,JSON.stringify([Q]))}class F$ extends _Q{attachments=t;attachmentStorage=w9;constructor(){super();let $=this.run;this.run=(Q)=>this.$runEnvelope(Q,$)}onDeadletter($,...Q){let Z=Q[0];if(!Z?.jobId)return;x9(y.store,Z.jobId,{error:$}).catch((V)=>{console.error(`Could not record the failure of background job ${Z.jobId}.`,V)})}async $runEnvelope($,Q){let Z=y.store,V=await Z.get($.jobId);if(!V||V.state!=="running")return;let G=new AQ(V,this),J;try{J=await Q.call(this,$.args,G)}catch(W){throw await OQ(Z,V.id,G.usage),W}if(this.$outcome)return await OQ(Z,V.id,G.usage),J;return await x9(Z,V.id,{output:J,usage:G.usage}),J}}async function OQ($,Q,Z){if(Z.totalTokens===0&&Z.inputTokens===0&&Z.outputTokens===0)return;let V=await $.get(Q);if(!V)return;await $.transition(Q,b6,{usage:M(V.usage??R(),Z)}).catch(()=>{})}class AQ{id;threadId;toolCallId;toolName;owner;summary;signal=new AbortController().signal;usage=R();attachments;constructor($,Q){this.id=$.id,this.threadId=$.threadId,this.toolCallId=$.toolCallId,this.toolName=$.toolName,this.owner=$.owner,this.summary=$.summary;let Z=$.attachmentScope?new p(Q.attachments,Q.attachmentStorage,{key:$.attachmentScope}):null,V=()=>{if(!Z)throw new g("The run that started this job had no attachment scope, so the job cannot store or read files. See `attachmentScope()` on the controller.");return Z};this.attachments={put:(G,J={})=>V().put(G,J),get:(G)=>V().get(G),read:(G)=>V().read(G),file:(G)=>V().file(G)}}generate($){return K9($,{origin:{threadId:this.threadId,toolCallId:this.toolCallId,jobId:this.id},settled:(Q)=>{this.usage=M(this.usage,Q.usage)}})}async generateImage($,Q){let{name:Z,...V}=Q,G=await $.generate({...V,signal:this.signal});return this.park($,G,Z)}async editImage($,Q){let{name:Z,images:V,mask:G,...J}=Q,W=async(K)=>typeof K==="string"?await this.attachments.file(K):K,X=await $.edit({...J,images:await Promise.all(V.map(W)),...G?{mask:await W(G)}:{},signal:this.signal});return this.park($,X,Z)}async park($,Q,Z){this.usage=M(this.usage,Q.usage);let V=Q.mimeType==="image/jpeg"?"jpg":"png";return{attachment:await this.attachments.put(Q.image,{name:Z??`${$.name}.${V}`,mimeType:Q.mimeType}),size:Q.size,mimeType:Q.mimeType,usage:Q.usage}}}function m($){let Q=new Set;for(let Z of $)for(let V of Z.content??[]){if(V.type!=="tool-call")continue;for(let G of V.attachments??[])if(G&&"shown"in G&&G.shown)Q.add(G.shown.messageId)}return Q}function L9($){if($.length===0)return[];let Q=m($),Z=[0];for(let V=1;V<$.length;V++){let G=$[V];if(G.role==="user"&&!Q.has(G.id))Z.push(V)}return Z}function y6($){let Q=L9($);return Q.map((Z,V)=>$.slice(Z,Q[V+1]??$.length))}function EQ($){try{return JSON.stringify($).length}catch{return 0}}var h6=4,kQ=10,xQ="[Earlier turns of this conversation are not shown.]";function r($,Q={}){let Z=[...$],V=L9(Z),G=g6(Q),J=f9(Q.maxTurns)??1/0,W=Math.max(1,Math.floor(f9(Q.step)??kQ));if(V.length<=1||J>=V.length&&G===1/0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let X=Array.from({length:Z.length+1},()=>0);if(G!==1/0)for(let U=Z.length-1;U>=0;U--)X[U]=X[U+1]+EQ(Z[U]);let K=(U)=>V.length-U<=J&&X[V[U]]<=G,Y=-1;for(let U=0;U<V.length;U+=W)if(K(U)){Y=U;break}if(Y<0){for(let U=0;U<V.length;U++)if(K(U)){Y=U;break}}if(Y<0)Y=V.length-1;if(Y===0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let H=V[Y],B=Z.slice(0,H),z=B.filter((U)=>U.role==="system"),D=u6(B,Z.slice(H)),L={turns:Y,messages:B.length-z.length},F=typeof Q.note==="function"?Q.note(L):Q.note===void 0?xQ:Q.note;if(F){let U=D[0];D[0]={...U,content:[{type:"text",text:F},...U.content]}}return{messages:[...z,...D],start:H,omittedTurns:L.turns,omittedMessages:L.messages}}function f9($){return typeof $==="number"&&$>0?$:void 0}function g6($){let Q=f9($.maxBytes)??1/0,Z=f9($.maxTokens);return Math.min(Q,Z===void 0?1/0:Z*h6)}function TQ($,Q){let Z=Array.isArray($?.namespaces)?$.namespaces:[],V=Array.isArray($?.loaded)?$.loaded:[];return Q.namespace?Z.includes(Q.namespace):V.includes(String(Q.name))}function L$($){return Array.isArray($.toolSearches)?$.toolSearches:[]}function u6($,Q){let Z=[];for(let Y of $)for(let H of Y.content??[])if(H.type==="tool-call")Z.push(...L$(H));if(Z.length===0)return Q;let V=[],G=new Set,J;if(Q.forEach((Y,H)=>{(Y.content??[]).forEach((B,z)=>{if(B.type!=="tool-call"||B.partial)return;if(V.push(...L$(B)),V.some((L)=>TQ(L,B)))return;let D=Z.filter((L)=>TQ(L,B));if(D.length===0)return;for(let L of D)G.add(L);J??={message:H,part:z}})}),!J)return Q;let W=Z.filter((Y)=>G.has(Y)),X=[...Q],K=X[J.message];return X[J.message]={...K,content:K.content.map((Y,H)=>H===J.part&&Y.type==="tool-call"?{...Y,toolSearches:[...W,...L$(Y)]}:Y)},X}var fQ=1000,c6=24000,p6=20000,vQ=1e5,m6=120000,yQ=["You keep a running summary of a conversation between a user and an AI assistant.","The assistant will continue the conversation with only your summary and the latest turns, so the summary has to carry everything from the earlier turns it may still need.","You are given the summary so far (possibly empty) and the turns that came after it. Answer the updated summary, which replaces the old one.","Keep: the user's goals, preferences and constraints; decisions made and why; facts, names, ids, numbers, dates, file names and URLs that may matter later; what tools were used and their important results; open questions and unfinished work.","Drop greetings, repetition and anything later turns superseded. Do not invent anything, and do not answer the user.","Write terse prose or bullet points, in the language of the conversation."].join(" "),hQ="[Summary of the earlier turns of this conversation, which are not shown:]",l6=8;class N${ttlMs;threads=new Map;lastSweep=0;constructor($=86400000){this.ttlMs=$}async loadSummaries($){this.sweep();let Q=this.threads.get($);if(!Q)return[];return Q.touchedAt=Date.now(),Q.summaries.slice()}async saveSummary($,Q){this.sweep();let Z=this.threads.get($)??{summaries:[],touchedAt:Date.now()};Z.summaries=h9(Z.summaries,Q),Z.touchedAt=Date.now(),this.threads.set($,Z)}delete($){this.threads.delete($)}sweep($=Date.now()){if($-this.lastSweep<60000)return;this.lastSweep=$;for(let[Q,Z]of this.threads)if($-Z.touchedAt>this.ttlMs)this.threads.delete(Q)}}function h9($,Q){return[Q,...$.filter((Z)=>Z.cutMessageId!==Q.cutMessageId)].slice(0,l6)}var C$=new N$;function gQ($){let Q=$;return typeof Q?.loadSummaries==="function"&&typeof Q?.saveSummary==="function"}function uQ($,Q,Z){let V=u(Z.maxSummaryTokens)??fQ,G=(K)=>Math.max(1,K-V),J={...Q,...u(Q.maxTokens)?{maxTokens:G(Q.maxTokens)}:{},...u(Q.maxBytes)?{maxBytes:Math.max(1,Q.maxBytes-V*P$)}:{}},W=d6(Q,Z),X={...J,note:!1,...W?{maxTokens:Math.min(J.maxTokens??1/0,G(W))}:{}};return{plain:J,cut:r($,X),maxSummaryTokens:V}}function d6($,Q){if(Q.triggerTokens===!1)return;let Z=u(Q.triggerTokens||void 0);if(Z)return Z;if(u($.maxTokens)||u($.maxBytes))return;return vQ}async function cQ($){let{history:Q,window:Z,compact:V}=$,{plain:G,cut:J,maxSummaryTokens:W}=uQ(Q,Z,V);if(J.omittedTurns===0)return J.messages;let X=`${Q[J.start].id}:${J.start}`,K=$.memo?.get(X);if(K===void 0){try{K=await t6($,J.start,W)}catch(D){if($.signal.aborted)throw D;K=null}if(!$.signal.aborted)$.memo?.set(X,K)}if(!K)return r(Q,G).messages;let Y=Q.length-J.start,H=J.messages.slice(0,J.messages.length-Y),B=J.messages.slice(J.messages.length-Y),z=Q[J.start];return[...H,{id:`summary_${z.id}`,role:"user",content:[{type:"text",text:`${hQ}
3
3
  ${K.text}`}],createdAt:z.createdAt},...B]}var IQ="\x00next-turn";function pQ($){let Q=i6($).finally(()=>y9.delete(Q));return y9.add(Q),Q}var y9=new Set;async function i6($){try{let Q={id:IQ,role:"user",content:[{type:"text",text:""}],createdAt:new Date().toISOString()},Z=[...$.history,Q],V=[...$.stored,Q],{cut:G,maxSummaryTokens:J}=uQ(Z,$.window,$.compact);if(G.omittedTurns===0||Z[G.start].id===IQ)return;let W=mQ({...$,history:Z,stored:V},G.start);if((await g9($.store,$.threadId)).some(W.matches))return;await lQ(W,{...$,history:Z,stored:V},G.start,J).promise}catch{}}async function n6(){while(P9.size>0||y9.size>0)await Promise.allSettled([...y9,...[...P9.values()].map(($)=>$.promise)])}var P9=new Map,l=new Map,o6=1000;function s6($,Q){l.set($,M(l.get($)??R(),Q));while(l.size>o6)l.delete(l.keys().next().value)}function wQ($,Q){let Z=l.get($);if(!Z)return;l.delete($),Q(Z)}function mQ($,Q){let Z=$.history[Q].id,V=G8($.stored,Q),G=V[Q];return{key:`${$.threadId}\x00${Z}\x00${G}`,fingerprints:V,matches:(J)=>J?.cutMessageId===Z&&J.fingerprint===G}}async function t6($,Q,Z){let V=mQ($,Q),G=(await g9($.store,$.threadId)).find(V.matches);if(G)return wQ(V.key,$.onUsage),G;let J=lQ(V,$,Q,Z);if(J.owed)$.onUsage(J.owed),J.owed=void 0;J.payers.push($.onUsage);try{return await a6(J.promise,$.signal)}finally{J.payers.splice(J.payers.indexOf($.onUsage),1),wQ(V.key,$.onUsage)}}function lQ($,Q,Z,V){let G=P9.get($.key);if(G)return G;let J={promise:void 0,payers:[],owed:void 0},W=(X)=>{let K=J.payers[0];if(K)K(X);else J.owed=M(J.owed??R(),X)};return J.promise=(async()=>{let{store:X,threadId:K}=Q,Y=u(Q.compact.lockWaitMs)??p6,H=null;if(X.lockSummary){try{H=await X.lockSummary(K,Q.history[Z].id,Y+60000)}catch{H=null}if(!H)return e6(Q,$.matches,Y)}try{let B=await g9(X,K),z=B.find($.matches);if(z)return z;return await $8(Q,B,$.fingerprints,Z,V,W)}finally{if(H)await H().catch(()=>{})}})().catch(()=>null).finally(()=>{if(P9.delete($.key),J.owed)s6($.key,J.owed);J.owed=void 0}),P9.set($.key,J),J}function a6($,Q){if(Q.aborted)return Promise.reject(Q.reason);return new Promise((Z,V)=>{let G=()=>V(Q.reason);Q.addEventListener("abort",G,{once:!0}),$.then((J)=>{Q.removeEventListener("abort",G),Z(J)},(J)=>{Q.removeEventListener("abort",G),V(J)})})}async function g9($,Q){try{let Z=await $.loadSummaries(Q);return Array.isArray(Z)?Z.filter(r6):[]}catch{return[]}}function r6($){let Q=$;return!!Q&&typeof Q.cutMessageId==="string"&&typeof Q.text==="string"&&typeof Q.fingerprint==="string"}async function e6($,Q,Z){let V=Date.now()+Z;while(Date.now()<V){await new Promise((J)=>setTimeout(J,250));let G=(await g9($.store,$.threadId)).find(Q);if(G)return G}return null}async function $8($,Q,Z,V,G,J){let{history:W,compact:X}=$,K=L9(W),Y=K.indexOf(V),H=new Map(K.map((O)=>[W[O].id,O])),B,z=0;for(let O of Q){let A=H.get(O.cutMessageId);if(A===void 0||A>=V||A<=z)continue;if(O.fingerprint!==Z[A])continue;B=O,z=A}let D=(u(X.chunkTokens)??c6)*P$,L=Q8(W,K,z,V,D),F=G*P$,U=`${X.instructions??yQ} Keep the summary under about ${Math.round(G*0.75)} words.`,P=B?.text??"",q=R();for(let O of L){let A=await Y$({provider:X.provider??$.provider,instructions:U,prompt:`Summary so far:
4
4
  ${P||"(none yet: these are the first turns of the conversation)"}
5
5
 
@@ -102,4 +102,4 @@ return 0`;class YQ{injectedClient;prefix;constructor($={}){this.injectedClient=$
102
102
 
103
103
  `)||void 0,q=await this.context($,{body:K}),_=await this.attachmentsFor($,V,{body:K});if(H?.cancelled)return H6();let O=V?new HQ(this.store,V,F,(E)=>this.reportHookFailure(E)):null,A=`run_${crypto.randomUUID()}`,k={req:$,runId:A,threadId:V},x={id:null,notified:Promise.resolve()},C=this.agent.stream({runId:A,messages:F,turn:J,threadId:V,...O?{onMessage:(E)=>O.finish(E)}:{},onTurn:(E)=>{if(x.id!==null)return;x.id=E.id;let s=O?O.settled():Promise.resolve();x.notified=s.then(()=>this.safely(()=>this.onMessage(E,k)))},instructions:P,context:q,attachments:_,body:K,redactError:(E,s)=>this.redactError(E,s,k),nonces:this.nonces,receipts:this.receipts,subject:Y,...V?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...V&&gQ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==UQ.prototype.prepareStep?{prepareStep:(E)=>this.prepareStep(E,k)}:{}}),N=this.liveRuns.register(C,{threadId:V,owner:Y,clientRunId:X,onEvent:(E)=>this.dispatchEvent(E,k),onInternalError:(E)=>this.reportHookFailure(E),maxRunDurationMs:this.agent.maxRunDurationMs});if(B=C,O)this.follow(C,O);let{stored:T,hooks:S}=this.persistRun(C,k,N,O,x);return V6.set(C,T),$.ctx?.()?.waitUntil(S),C.toResponse()};try{await this.authorizeRequest($,{route:"stream",threadId:V,body:K});let F=await this.foreignFile([...J?.files??[],...V?[]:y0(Z.messages)],Y);if(F)return F;if(H?.cancelled)return H6();let U=await this.runLimitKey($,{owner:Y,threadId:V}),P=U===null?C6:M0(this.liveRuns).take(U,V?`thread:${V}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return FQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return V?await this.withThread(V,Y,D):await D()}finally{let q=B;if(q)q.result().then(P,P);else P()}}finally{if(H&&Z$.get(X)===H)Z$.delete(X)}}async withThread($,Q,Z){let V=Q$.get($)??Promise.resolve(),G,J=new Promise((X)=>{G=X}),W=V.then(()=>J);Q$.set($,W),await V;try{let X=await this.liveRuns.find({threadId:$});if(X&&this.liveRuns.isRunning(X.runId)&&!this.liveRuns.mayAccess(X.runId,Q))return G$();let K=X?this.liveRuns.get(X.runId):null;if(K)K.stop({reason:"superseded by a later turn on this thread"}),await V6.get(K);return await Z()}finally{if(G(),Q$.get($)===W)Q$.delete($)}}async attach($=new M9){let Q=await zQ($,G6);if(Q.error)return V$(Q);let Z=Q.body,V=typeof Z.threadId==="string"?Z.threadId:b0($,"threadId");if(!V)return f(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest($,{route:"attach",threadId:V});let G=await this.liveRuns.find({threadId:V});if(G&&!this.liveRuns.mayAccess(G.runId,await this.runOwner($)))return G$();if(!G)return f(404,{code:"no_live_run",message:`No run in progress for thread ${V} in this process.`});let J=typeof Z.runId==="string"?Z.runId:void 0,W=J&&J!==G.runId?void 0:w0($,Z);try{return U6(this.liveRuns.replay(G.runId,W))}catch(X){if(X instanceof G9)return f(410,{code:X.code,message:X.message,oldestSeq:X.oldest});if(X instanceof q9)return f(404,{code:X.code,message:X.message});throw X}}async stop($=new M9){let Q=await zQ($,G6);if(Q.error)return V$(Q);let Z=Q.body;await this.authorizeRequest($,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let V=await this.runOwner($),G=typeof Z.runId==="string"?Z.runId:void 0;if(!G&&typeof Z.clientRunId==="string"){if(G=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!G){let W=Z$.get(Z.clientRunId);if(W){if(W.owner!==null&&W.owner!==V)return G$();return W.cancelled=!0,{stopped:!0}}}}if(!G&&typeof Z.threadId==="string")G=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let J=G?this.liveRuns.get(G):null;if(!J)return{stopped:!1};if(!this.liveRuns.mayAccess(J.runId,V))return G$();return J.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope($,Q,Z){let V=$.ctx()?.user,G=V?.id??V?.publicId;if(G!==void 0&&G!==null&&String(G)!=="")return{key:`user:${String(G)}`};if(Q)return{key:`thread:${Q}`};return null}attachmentLimits($){return null}attachmentDestination($,Q){return"both"}async attachmentsFor($,Q,Z={body:{}}){let V=await this.attachmentScope($,Q,Z);if(!V)return null;return new p(this.attachments,this.attachmentStorage,V)}async upload($=new M9){let Q=await $.rawRequest.formData(),Z=Q.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let V=Z instanceof File&&Z.name?Z.name:"upload",G=Z.type||"application/octet-stream",J=S0(Q.get("body")),W=Q.get("threadId");await this.authorizeRequest($,{route:"upload",threadId:typeof W==="string"&&W.length>0?W:void 0,body:J});let X=A0(await this.attachmentLimits($),Z,V,G);if(X)throw new q6(X.code,X.message);let K=typeof W==="string"&&W.length>0&&await this.store.loadThread(W)!==null?W:void 0,Y=await this.runOwner($),H=(_)=>this.fileOwners.record(_,{owner:Y,name:V,mimeType:G,size:Z.size,createdAt:new Date().toISOString()}),B=await this.attachmentDestination(Z,$),z=h0(B,Q.get("destination")),D=await this.attachmentScope($,K,{body:J}),L=z!=="provider"&&!D;if(L){if(z==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');g0()}if(z==="provider"||!D){let _=await W6(this.agent.provider,Z);await H(_);let O={fileId:_,name:V,mimeType:G,size:Z.size,destination:"provider"};if(L)O.downgraded="no_scope";return O}let F=K$(),U=await this.attachmentStorage.put({name:H$(F,V),body:Z,contentType:G}),P=z==="both"?await W6(this.agent.provider,Z):void 0;if(P)await H(P);let q={id:F,scopeKey:D.key,fileId:P,objectName:U,name:V,mimeType:G,size:Z.size,createdAt:new Date().toISOString(),destination:z};return await this.attachments.put(D,q),{fileId:P,attachmentId:F,name:V,mimeType:G,size:Z.size,destination:z}}async foreignFile($,Q){let Z=new Set($.map((V)=>V.fileId).filter((V)=>typeof V==="string"));for(let V of Z){let G=await this.fileOwners.get(V);if(G?G.owner!==null&&G.owner!==Q:this.requireKnownFiles)return v0()}return null}onMessage($,Q){}onToolCall($,Q){}onAwaitingInput($,Q){}redactError($,Q,Z){return F9($,Q)}onError($,Q){}onStreamComplete($,Q){}reportHookFailure($){console.error("[gemi/ai] agent controller hook failed",$)}async dispatchEvent($,Q){switch($.type){case"tool-call":if(!$.part.partial&&!$.resent)await this.onToolCall({toolCallId:$.part.toolCallId,name:String($.part.name),input:$.part.input},Q);return;case"awaiting-input":await this.onAwaitingInput($.pending,Q);return;case"error":await this.onError(N6($.error),Q);return;default:return}}async readThread($){let Q=await this.store.loadThread($);return Q?(await this.settleThread($,Q,{write:!1})).messages:null}isRunLive($,Q){return this.liveRuns.get($)!==null}async settleThread($,Q,{write:Z}){let V=(K)=>this.isRunLive(K,$),G=await eZ(Q,V),J=G.messages,W=[],X=new Map(G.settled.map((K)=>[K.id,K]));if(m0(J)||Z)try{let K=await Q6(J,{threadId:$,store:y.store,isRunLive:V,outputSchemaFor:(Y)=>this.toolOutputSchema(Y),scan:this.jobsBlockMax()});J=K.messages,W=K.jobs;for(let Y of K.settled)X.set(Y.id,Y);if(Z&&K.orphans.length>0){await Z6(y.store,K.orphans,(H)=>this.reportHookFailure(H));let Y=new Set(K.orphans.map((H)=>H.id));W=W.map((H)=>Y.has(H.id)?{...H,orphaned:!0}:H)}}catch(K){this.reportHookFailure(K)}if(Z&&X.size>0)try{await this.store.appendMessages($,[...X.values()])}catch(K){this.reportHookFailure(K)}return{messages:J,jobs:W}}jobsBlockMax(){let $=this.agent.jobs?.contextBlock;if($===!1)return 0;return $?.max??m9}jobsBlock($){return LZ($,this.jobsBlockMax())}toolOutputSchema($){let Q=(Z)=>{for(let V of Z){let G=V;if(Array.isArray(G.tools)){let J=Q(G.tools);if(J)return J}else if(G.name===$)return G.outputSchema}return};return Q(this.agent.tools??[])}follow($,Q){(async()=>{try{for await(let Z of $.frames())Q.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun($,Q,Z,V=null,G={id:null,notified:Promise.resolve()}){let J=Promise.resolve(),W=(async()=>{let K;try{K=await $.result()}catch(H){V?.close(),await V?.settled(),J=G.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},Q)));return}let Y=K.messages;if(V?.close(Y),await V?.settled(),Q.threadId&&Y.length>0)try{await this.store.appendMessages(Q.threadId,Y)}catch(H){this.reportHookFailure(H)}J=this.notifyRun(K,Y,Q,G)})(),X=W.then(()=>c0(Promise.all([J,Z]).then(()=>{}),this.hookHoldMs));return{stored:W,hooks:X}}async notifyRun($,Q,Z,V){await V.notified;for(let G of Q){if(G.id===V.id)continue;await this.safely(()=>this.onMessage(G,Z))}await this.safely(()=>this.onStreamComplete($,Z))}async safely($){try{await $()}catch(Q){this.reportHookFailure(Q)}}}var BQ=["turn","clientRunId","threadId","messages","regenerate"],R0=["text","files","toolResults"];function _6($,Q=R6($)?BQ:[...BQ,...R0]){let Z={};for(let[V,G]of Object.entries($)){if(Q.includes(V))continue;Object.defineProperty(Z,V,{value:G,writable:!0,enumerable:!0,configurable:!0})}return Z}function S0($){if($===null)return{};let Q;if(typeof $==="string")try{Q=JSON.parse($)}catch{throw new DQ("The upload's `body` field is not valid JSON.")}if(Q===null||typeof Q!=="object"||Array.isArray(Q))throw new DQ("The upload's `body` field must be a JSON object.");return _6(Q,BQ)}class DQ extends J${constructor($){super($);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:$}}},view:{}}}}async function W6($,Q){try{return await $.upload(Q)}catch(Z){if(Z instanceof h&&j0.has(Z.status))throw new M6(I(Z).message);throw Z}}var j0=new Set([400,413,415,422]);class q6 extends J${constructor($,Q){super(Q);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}function A0($,Q,Z,V){if(!$)return null;let{maxBytes:G,accept:J}=$;if(typeof G==="number"&&Q.size>G)return{code:"file_too_large",message:`${JSON.stringify(Z)} is ${Y6(Q.size)}; the limit is ${Y6(G)}.`};if(J&&J.length>0&&!J.some((W)=>T0(W,Z,V)))return{code:"unsupported_file_type",message:`${JSON.stringify(Z)} is not a type this chat accepts. Accepted: ${J.join(", ")}.`};return null}function T0($,Q,Z){let V=$.trim().toLowerCase();if(!V)return!1;if(V.startsWith("."))return Q.toLowerCase().endsWith(V);let G=Z.toLowerCase().split(";")[0].trim();if(V.endsWith("/*"))return G.startsWith(V.slice(0,-1));return G===V}function Y6($){if($<1024)return`${$} B`;let Q=["KB","MB","GB"],Z=$/1024,V=0;while(Z>=1024&&V<Q.length-1)Z/=1024,V++;return`${Math.round(Z*10)/10} ${Q[V]}`}class M6 extends J${constructor($){super($);this.name="RejectedUploadError";let Q=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test($)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}async function zQ($,Q){let Z=$?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!E0(Z.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let V=Number(Z.headers.get("Content-Length"));if(Number.isFinite(V)&&V>Q)return X6(Q);let G;try{let W=await k0(Z,Q);if(W===null)return X6(Q);G=W}catch{return{body:{},error:"The request body could not be read."}}if(!G.trim())return{body:{}};let J;try{J=JSON.parse(G)}catch{return{body:{},error:"The request body is not valid JSON."}}if(J===null||typeof J!=="object"||Array.isArray(J))return{body:{},error:"The request body must be a JSON object."};return{body:J}}function E0($){return L6($)==="application/json"}async function k0($,Q){if(!Number.isFinite(Q)||!$.body)return await $.text();let Z=$.body.getReader(),V=[],G=0;for(;;){let{done:X,value:K}=await Z.read();if(X)break;if(G+=K.byteLength,G>Q)return await Z.cancel().catch(C6),null;V.push(K)}let J=new Uint8Array(G),W=0;for(let X of V)J.set(X,W),W+=X.byteLength;return new TextDecoder().decode(J)}function X6($){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${$} bytes).`}}function FQ($,Q,Z){return f($,{...W$(F6($),Z,$),code:Q})}function V$($){if($.status===413)return FQ(413,$.code??"body_too_large",$.error??"");return f($.status??400,{code:$.code??"invalid_request",message:$.error})}function R6($){return Boolean($.turn)&&typeof $.turn==="object"}function x0($){let Q=R6($)?$.turn:$,Z={};if(typeof Q.text==="string")Z.text=Q.text;if(Array.isArray(Q.files)){let V=I0(Q.files);if(typeof V==="string")return{error:V};Z.files=V}if(Array.isArray(Q.toolResults))Z.toolResults=Q.toolResults;if(Object.keys(Z).length===0)return{};if(Q===$.turn&&Q.localId!==void 0&&Q.localId!==null&&Q.localId!==""){let{localId:V}=Q;if(typeof V!=="string")return{error:"turn.localId must be a string."};if(V.length>K6)return{error:`turn.localId is longer than ${K6} characters.`};Z.localId=V}return{turn:Z}}var K6=200;function I0($){let Q=[];for(let[Z,V]of $.entries()){let G=`turn.files[${Z}]`;if(!V||typeof V!=="object"||Array.isArray(V))return`${G} must be an object.`;let J={};for(let H of["fileId","attachmentId","name","mimeType"]){let B=V[H];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${G}.${H} must be a string.`;J[H]=B}let{fileId:W,attachmentId:X,name:K,mimeType:Y}=J;if(W?.startsWith(v))return`${G}.fileId holds a gemi attachment id (${W}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(X!==void 0&&!X.startsWith(v))return`${G}.attachmentId is not a gemi attachment id: it must start with "${v}".`;if(!W&&!X)return`${G} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;Q.push({...W?{fileId:W}:{},...X?{attachmentId:X}:{},...K!==void 0?{name:K}:{},...Y!==void 0?{mimeType:Y}:{}})}return Q}function w0($,Q){if(typeof Q.from==="number"&&Number.isFinite(Q.from))return Math.max(0,Math.floor(Q.from));if(typeof Q.cursor==="number"&&Number.isFinite(Q.cursor)){let V=Math.floor(Q.cursor);if(V>=0)return V+1;return}let Z=$?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let V=Number.parseInt(Z,10);if(Number.isFinite(V))return Math.max(0,V+1)}return}function b0($,Q){let Z=$?.search?.get(Q);return typeof Z==="string"?Z:void 0}function f0($){let Q=m($);for(let Z=$.length-1;Z>=0;Z--){let V=$[Z];if(V.role!=="user"||Q.has(V.id))continue;let G="",J=[];for(let W of V.content){if(W.type==="text")G+=W.text;if(W.type==="file")J.push({...W.fileId?{fileId:W.fileId}:{},...W.attachmentId?{attachmentId:W.attachmentId}:{},...W.name?{name:W.name}:{},...W.mimeType?{mimeType:W.mimeType}:{}})}if(!G&&J.length===0)continue;return{index:Z,turn:{...G?{text:G}:{},...J.length>0?{files:J}:{}}}}return null}function H6(){return f(409,{code:"stopped",message:"The turn was stopped before it started."})}function G$(){return f(403,W$("permission","This run belongs to someone else.",403))}function v0(){return f(403,W$("permission","A file in this turn was uploaded by someone else.",403))}function y0($){if(!Array.isArray($))return[];let Q=[];for(let Z of $){let V=Z?.content;if(!Array.isArray(V))continue;for(let G of V)if(G&&typeof G==="object"&&typeof G.fileId==="string")Q.push({fileId:G.fileId})}return Q}function f($,Q){return new Response(JSON.stringify({error:Q}),{status:$,headers:{"Content-Type":"application/json"}})}function h0($,Q){if(typeof Q!=="string"||Q.length===0)return $;if(Q!=="both"&&Q!=="provider"&&Q!=="storage")throw Error(`Unknown attachment destination "${Q}". Expected "both", "provider" or "storage".`);if(Q===$||$==="both"&&Q==="storage")return Q;if($==="both"&&Q==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${Q}" destination, but the server's policy for it is "${$}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var z6=!1;function g0(){if(z6)return;z6=!0,console.warn("[gemi/ai] An upload had no attachment scope, so its bytes were sent to the model provider only and no attachment id was minted \u2014 a tool cannot forward this file. Guard the route with auth, send a `threadId` with the upload, or override `attachmentScope()`.")}var u0=2147483647;function c0($,Q){let Z=$.then(()=>{},()=>{});if(!(Q<=u0))return Z;let V,G=new Promise((J)=>{V=setTimeout(J,Q)});return Promise.race([Z,G]).finally(()=>clearTimeout(V))}var B6=!1;function p0($){if(B6||Bun.env.NODE_ENV!=="production")return;if(!($ instanceof LQ))return;B6=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}function m0($){return $.some((Q)=>Q.content.some((Z)=>Z.type==="tool-result"&&Z.status==="running"))}export{r as windowMessages,L9 as turnStarts,N8 as toAgentTools,W9 as supportsStrict,y6 as splitTurns,n6 as settleSummaries,v9 as s,F9 as redactError,EQ as messageSize,ZQ as liveRuns,h9 as keepSummary,m as injectedMessageIds,Y$ as generate,V0 as evalChain,C$ as defaultSummaryStore,C9 as defaultNonceStore,VQ as defaultFileOwners,t as defaultAttachmentStore,XQ as defaultAgentStore,e as ToolNamespace,j as ToolError,S$ as Skill,p as ScopedAttachments,N9 as SKILLS_NAMESPACE,YQ as RedisReceiptStore,P6 as RedisNonceStore,d as PendingEscalation,a$ as OpenAIProvider,h$ as OpenAIImageProvider,N$ as MemorySummaryStore,WQ as MemoryReceiptStore,LQ as MemoryNonceStore,r9 as MemoryLiveRuns,e9 as MemoryFileOwners,a9 as MemoryCircuitStore,k9 as MemoryAttachmentStore,$$ as MemoryAgentStore,B9 as MemoryAgentJobStore,q9 as LiveRunNotFoundError,D9 as JobsRequireThreadError,b9 as JobHandle,l0 as JSONSchemaError,g as InvalidAttachmentScopeError,o9 as ImageRequestError,s9 as ImageProvider,f$ as ImageModel,G9 as FrameCursorEvictedError,_9 as FallbackProvider,w$ as DatabaseAgentJobStore,fQ as DEFAULT_MAX_SUMMARY_TOKENS,T$ as DEFAULT_MAX_RUN_DURATION_MS,D$ as DEFAULT_JOB_DEADLINE_MS,m9 as DEFAULT_JOBS_CONTEXT_MAX,kQ as DEFAULT_CONTEXT_WINDOW_STEP,xQ as DEFAULT_CONTEXT_WINDOW_NOTE,vQ as DEFAULT_COMPACT_TRIGGER_TOKENS,yQ as DEFAULT_COMPACT_INSTRUCTIONS,hQ as COMPACT_SUMMARY_HEADER,r$ as AzureOpenAIProvider,g$ as AzureOpenAIImageProvider,z9 as AttachmentNotFoundError,i as AgentTool,H9 as AgentRunError,V9 as AgentProvider,y as AgentJobs,k$ as AgentJobDeadlineSweep,F$ as AgentJob,UQ as AgentController,E$ as Agent};
104
104
 
105
- //# debugId=3518169BAF28C24564756E2164756E21
105
+ //# debugId=AEC487946E98859964756E2164756E21