gemi 0.112.1 → 0.113.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 (189) 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/auth/AuthController.d.ts +19 -2
  5. package/dist/auth/AuthController.d.ts.map +1 -1
  6. package/dist/auth/config.d.ts +9 -0
  7. package/dist/auth/config.d.ts.map +1 -1
  8. package/dist/auth/oauth/GoogleOAuthProvider.d.ts +16 -17
  9. package/dist/auth/oauth/GoogleOAuthProvider.d.ts.map +1 -1
  10. package/dist/auth/oauth/OAuthProvider.d.ts +56 -7
  11. package/dist/auth/oauth/OAuthProvider.d.ts.map +1 -1
  12. package/dist/auth/oauth/XOAuthProvider.d.ts +10 -9
  13. package/dist/auth/oauth/XOAuthProvider.d.ts.map +1 -1
  14. package/dist/auth/oauth/oauthState.d.ts +70 -0
  15. package/dist/auth/oauth/oauthState.d.ts.map +1 -0
  16. package/dist/auth/routes.d.ts +3 -2
  17. package/dist/auth/routes.d.ts.map +1 -1
  18. package/dist/bun/plugin.js +1 -1
  19. package/dist/bun/preload.js +1 -1
  20. package/dist/{chunk-jdtn0zk2.js → chunk-01qd6xx3.js} +3 -3
  21. package/dist/{chunk-jdtn0zk2.js.map → chunk-01qd6xx3.js.map} +1 -1
  22. package/dist/{chunk-15a1mrdv.js → chunk-1p85fdrk.js} +2 -2
  23. package/dist/{chunk-15a1mrdv.js.map → chunk-1p85fdrk.js.map} +1 -1
  24. package/dist/{chunk-qyp652jz.js → chunk-1se4t9rg.js} +3 -3
  25. package/dist/{chunk-qyp652jz.js.map → chunk-1se4t9rg.js.map} +1 -1
  26. package/dist/{chunk-b7cqwcbm.js → chunk-3f1kq32g.js} +2 -2
  27. package/dist/{chunk-b7cqwcbm.js.map → chunk-3f1kq32g.js.map} +1 -1
  28. package/dist/{chunk-57edag57.js → chunk-4t1pbt9p.js} +3 -3
  29. package/dist/{chunk-57edag57.js.map → chunk-4t1pbt9p.js.map} +1 -1
  30. package/dist/{chunk-851k0b26.js → chunk-4tp2cr02.js} +2 -2
  31. package/dist/{chunk-851k0b26.js.map → chunk-4tp2cr02.js.map} +1 -1
  32. package/dist/{chunk-a9q2cr4w.js → chunk-571rvxe6.js} +2 -2
  33. package/dist/{chunk-a9q2cr4w.js.map → chunk-571rvxe6.js.map} +1 -1
  34. package/dist/{chunk-mx9y9mtx.js → chunk-5nqkwa2w.js} +1 -1
  35. package/dist/{chunk-d0trs736.js → chunk-5q4a7yqf.js} +2 -2
  36. package/dist/{chunk-d0trs736.js.map → chunk-5q4a7yqf.js.map} +1 -1
  37. package/dist/{chunk-dan79jab.js → chunk-5x0aacrn.js} +2 -2
  38. package/dist/{chunk-dan79jab.js.map → chunk-5x0aacrn.js.map} +1 -1
  39. package/dist/{chunk-bf1ets45.js → chunk-5zzhypmt.js} +2 -2
  40. package/dist/{chunk-bf1ets45.js.map → chunk-5zzhypmt.js.map} +1 -1
  41. package/dist/{chunk-18c3y8m3.js → chunk-68s1f5d5.js} +2 -2
  42. package/dist/{chunk-18c3y8m3.js.map → chunk-68s1f5d5.js.map} +1 -1
  43. package/dist/chunk-6g20zec2.js +46 -0
  44. package/dist/{chunk-4sb1484x.js.map → chunk-6g20zec2.js.map} +7 -5
  45. package/dist/{chunk-csbc1fxa.js → chunk-6wymbbes.js} +3 -3
  46. package/dist/{chunk-csbc1fxa.js.map → chunk-6wymbbes.js.map} +1 -1
  47. package/dist/{chunk-b7qjp7r1.js → chunk-7jnpnjth.js} +2 -2
  48. package/dist/{chunk-b7qjp7r1.js.map → chunk-7jnpnjth.js.map} +1 -1
  49. package/dist/{chunk-ddad3902.js → chunk-8mbyyh8j.js} +2 -2
  50. package/dist/{chunk-ddad3902.js.map → chunk-8mbyyh8j.js.map} +1 -1
  51. package/dist/{chunk-dx7wpz5b.js → chunk-9tpx9ag3.js} +2 -2
  52. package/dist/{chunk-dx7wpz5b.js.map → chunk-9tpx9ag3.js.map} +1 -1
  53. package/dist/{chunk-beks65me.js → chunk-9vsj0ksk.js} +2 -2
  54. package/dist/{chunk-beks65me.js.map → chunk-9vsj0ksk.js.map} +1 -1
  55. package/dist/{chunk-rx2shb3t.js → chunk-agw3anaf.js} +1 -1
  56. package/dist/{chunk-jn8hh25v.js → chunk-atmzm0z3.js} +2 -2
  57. package/dist/{chunk-jn8hh25v.js.map → chunk-atmzm0z3.js.map} +1 -1
  58. package/dist/{chunk-es487acc.js → chunk-bq5nqqeq.js} +1 -1
  59. package/dist/{chunk-b1mk12xg.js → chunk-c7mp2kyp.js} +2 -2
  60. package/dist/{chunk-b1mk12xg.js.map → chunk-c7mp2kyp.js.map} +1 -1
  61. package/dist/{chunk-j0sncgxc.js → chunk-cqnfp0n9.js} +3 -3
  62. package/dist/{chunk-j0sncgxc.js.map → chunk-cqnfp0n9.js.map} +1 -1
  63. package/dist/{chunk-kk502yk2.js → chunk-d04r0hdf.js} +2 -2
  64. package/dist/{chunk-kk502yk2.js.map → chunk-d04r0hdf.js.map} +1 -1
  65. package/dist/{chunk-2taa0brj.js → chunk-dbwhgyg3.js} +2 -2
  66. package/dist/{chunk-2taa0brj.js.map → chunk-dbwhgyg3.js.map} +1 -1
  67. package/dist/{chunk-k7rbkhhw.js → chunk-de03dewf.js} +2 -2
  68. package/dist/{chunk-k7rbkhhw.js.map → chunk-de03dewf.js.map} +1 -1
  69. package/dist/{chunk-qtbf3w6w.js → chunk-essqp1ek.js} +2 -2
  70. package/dist/{chunk-qtbf3w6w.js.map → chunk-essqp1ek.js.map} +1 -1
  71. package/dist/{chunk-5waxjsvv.js → chunk-fnkjmq94.js} +2 -2
  72. package/dist/{chunk-5waxjsvv.js.map → chunk-fnkjmq94.js.map} +1 -1
  73. package/dist/{chunk-8reepafh.js → chunk-fr0arqdj.js} +2 -2
  74. package/dist/{chunk-8reepafh.js.map → chunk-fr0arqdj.js.map} +1 -1
  75. package/dist/chunk-fsfbyg5e.js +5 -0
  76. package/dist/{chunk-d9an2nra.js.map → chunk-fsfbyg5e.js.map} +1 -1
  77. package/dist/{chunk-ga7c7tq0.js → chunk-g8kx549d.js} +2 -2
  78. package/dist/{chunk-ga7c7tq0.js.map → chunk-g8kx549d.js.map} +1 -1
  79. package/dist/{chunk-xs4c2nvz.js → chunk-g8sc6scv.js} +2 -2
  80. package/dist/{chunk-xs4c2nvz.js.map → chunk-g8sc6scv.js.map} +1 -1
  81. package/dist/{chunk-75ptmewf.js → chunk-k2fh4r0p.js} +2 -2
  82. package/dist/{chunk-75ptmewf.js.map → chunk-k2fh4r0p.js.map} +1 -1
  83. package/dist/{chunk-wexs11yy.js → chunk-kexsfyjj.js} +2 -2
  84. package/dist/{chunk-wexs11yy.js.map → chunk-kexsfyjj.js.map} +1 -1
  85. package/dist/{chunk-ryzcfxq7.js → chunk-kp7k4s5c.js} +2 -2
  86. package/dist/{chunk-ryzcfxq7.js.map → chunk-kp7k4s5c.js.map} +1 -1
  87. package/dist/{chunk-tmrmwthr.js → chunk-kz4yp5n7.js} +2 -2
  88. package/dist/{chunk-tmrmwthr.js.map → chunk-kz4yp5n7.js.map} +1 -1
  89. package/dist/{chunk-j9jqxv1d.js → chunk-mepaedy5.js} +2 -2
  90. package/dist/{chunk-j9jqxv1d.js.map → chunk-mepaedy5.js.map} +1 -1
  91. package/dist/{chunk-scbvv2e4.js → chunk-mk0rtgd1.js} +2 -2
  92. package/dist/{chunk-scbvv2e4.js.map → chunk-mk0rtgd1.js.map} +1 -1
  93. package/dist/{chunk-mvtgx1mr.js → chunk-nksn6xcd.js} +2 -2
  94. package/dist/{chunk-mvtgx1mr.js.map → chunk-nksn6xcd.js.map} +1 -1
  95. package/dist/{chunk-s9rfgxj5.js → chunk-nysqgzp1.js} +2 -2
  96. package/dist/{chunk-s9rfgxj5.js.map → chunk-nysqgzp1.js.map} +1 -1
  97. package/dist/{chunk-5az0mq4p.js → chunk-p3zmc8k8.js} +2 -2
  98. package/dist/{chunk-5az0mq4p.js.map → chunk-p3zmc8k8.js.map} +1 -1
  99. package/dist/{chunk-9hr0bcfy.js → chunk-qpttgn4k.js} +3 -3
  100. package/dist/{chunk-9hr0bcfy.js.map → chunk-qpttgn4k.js.map} +1 -1
  101. package/dist/{chunk-bhw7k8vp.js → chunk-qt8nvpqp.js} +2 -2
  102. package/dist/{chunk-bhw7k8vp.js.map → chunk-qt8nvpqp.js.map} +1 -1
  103. package/dist/{chunk-teny6xkw.js → chunk-r7b12dmm.js} +2 -2
  104. package/dist/{chunk-teny6xkw.js.map → chunk-r7b12dmm.js.map} +1 -1
  105. package/dist/{chunk-amvy4r59.js → chunk-rg4hhxj3.js} +2 -2
  106. package/dist/{chunk-amvy4r59.js.map → chunk-rg4hhxj3.js.map} +1 -1
  107. package/dist/{chunk-53bek7sp.js → chunk-rh2fad7n.js} +1 -1
  108. package/dist/{chunk-xv74rhay.js → chunk-sr18y2ck.js} +2 -2
  109. package/dist/{chunk-xv74rhay.js.map → chunk-sr18y2ck.js.map} +1 -1
  110. package/dist/{chunk-vgdcz7tk.js → chunk-szr1k584.js} +2 -2
  111. package/dist/{chunk-vgdcz7tk.js.map → chunk-szr1k584.js.map} +1 -1
  112. package/dist/{chunk-dm59ze55.js → chunk-v4gwmhtf.js} +2 -2
  113. package/dist/{chunk-dm59ze55.js.map → chunk-v4gwmhtf.js.map} +1 -1
  114. package/dist/{chunk-et3vhkbf.js → chunk-vc9phr57.js} +2 -2
  115. package/dist/{chunk-et3vhkbf.js.map → chunk-vc9phr57.js.map} +1 -1
  116. package/dist/{chunk-30yg31sz.js → chunk-vdwagp7y.js} +2 -2
  117. package/dist/{chunk-30yg31sz.js.map → chunk-vdwagp7y.js.map} +1 -1
  118. package/dist/{chunk-6w79zajj.js → chunk-vqa3agzw.js} +3 -3
  119. package/dist/{chunk-6w79zajj.js.map → chunk-vqa3agzw.js.map} +1 -1
  120. package/dist/{chunk-jn59bsww.js → chunk-vwprq300.js} +2 -2
  121. package/dist/{chunk-jn59bsww.js.map → chunk-vwprq300.js.map} +1 -1
  122. package/dist/{chunk-0z2h35d7.js → chunk-vzf5pbx3.js} +2 -2
  123. package/dist/{chunk-0z2h35d7.js.map → chunk-vzf5pbx3.js.map} +1 -1
  124. package/dist/{chunk-1pvkw2pq.js → chunk-w45agtch.js} +2 -2
  125. package/dist/{chunk-1pvkw2pq.js.map → chunk-w45agtch.js.map} +1 -1
  126. package/dist/{chunk-ck0v2kzw.js → chunk-wr3e4sez.js} +2 -2
  127. package/dist/{chunk-ck0v2kzw.js.map → chunk-wr3e4sez.js.map} +1 -1
  128. package/dist/{chunk-mrdarm2q.js → chunk-x5sert1k.js} +2 -2
  129. package/dist/{chunk-mrdarm2q.js.map → chunk-x5sert1k.js.map} +1 -1
  130. package/dist/{chunk-d8ekyng4.js → chunk-x5yq097b.js} +2 -2
  131. package/dist/{chunk-d8ekyng4.js.map → chunk-x5yq097b.js.map} +1 -1
  132. package/dist/{chunk-p2fhtf5r.js → chunk-xqwdn9kb.js} +3 -3
  133. package/dist/{chunk-p2fhtf5r.js.map → chunk-xqwdn9kb.js.map} +1 -1
  134. package/dist/{chunk-yv1psptb.js → chunk-y596ghpz.js} +2 -2
  135. package/dist/{chunk-yv1psptb.js.map → chunk-y596ghpz.js.map} +1 -1
  136. package/dist/{chunk-rend2sbk.js → chunk-y6frz1vm.js} +1 -1
  137. package/dist/{chunk-hfyxvdjj.js → chunk-y6v0x869.js} +2 -2
  138. package/dist/{chunk-hfyxvdjj.js.map → chunk-y6v0x869.js.map} +1 -1
  139. package/dist/{chunk-gcs9ydjv.js → chunk-yyzexrnb.js} +2 -2
  140. package/dist/{chunk-gcs9ydjv.js.map → chunk-yyzexrnb.js.map} +1 -1
  141. package/dist/{chunk-eazqda9z.js → chunk-z5hrymvn.js} +3 -3
  142. package/dist/{chunk-eazqda9z.js.map → chunk-z5hrymvn.js.map} +1 -1
  143. package/dist/{chunk-tb126j80.js → chunk-zng3qexn.js} +2 -2
  144. package/dist/{chunk-tb126j80.js.map → chunk-zng3qexn.js.map} +1 -1
  145. package/dist/{chunk-zfter1x0.js → chunk-zyer1g7k.js} +4 -4
  146. package/dist/{chunk-zfter1x0.js.map → chunk-zyer1g7k.js.map} +1 -1
  147. package/dist/config/index.js +1 -1
  148. package/dist/console/run.js +2 -2
  149. package/dist/console/run.js.map +1 -1
  150. package/dist/container/index.js +2 -2
  151. package/dist/container/index.js.map +1 -1
  152. package/dist/database/index.js +2 -2
  153. package/dist/database/index.js.map +1 -1
  154. package/dist/email/index.js +2 -2
  155. package/dist/email/index.js.map +1 -1
  156. package/dist/facades/index.js +2 -2
  157. package/dist/facades/index.js.map +1 -1
  158. package/dist/foundation/index.js +2 -2
  159. package/dist/foundation/index.js.map +1 -1
  160. package/dist/http/index.js +2 -2
  161. package/dist/http/index.js.map +1 -1
  162. package/dist/i18n/dictionaryRuntime.js +2 -2
  163. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  164. package/dist/i18n/index.js +2 -2
  165. package/dist/i18n/index.js.map +1 -1
  166. package/dist/kernel/index.js +2 -2
  167. package/dist/kernel/index.js.map +1 -1
  168. package/dist/orm/index.js +2 -2
  169. package/dist/orm/index.js.map +1 -1
  170. package/dist/server/index.js +2 -2
  171. package/dist/server/index.js.map +1 -1
  172. package/dist/services/index.d.ts +2 -1
  173. package/dist/services/index.d.ts.map +1 -1
  174. package/dist/services/index.js +8 -8
  175. package/dist/services/index.js.map +5 -6
  176. package/dist/services/queue/work.js +2 -2
  177. package/dist/services/queue/work.js.map +1 -1
  178. package/dist/stats/route-table.js +1 -1
  179. package/dist/support/index.js +2 -2
  180. package/dist/support/index.js.map +1 -1
  181. package/dist/vitest/index.js +1 -1
  182. package/package.json +1 -1
  183. package/dist/chunk-4sb1484x.js +0 -46
  184. package/dist/chunk-d9an2nra.js +0 -5
  185. /package/dist/{chunk-mx9y9mtx.js.map → chunk-5nqkwa2w.js.map} +0 -0
  186. /package/dist/{chunk-rx2shb3t.js.map → chunk-agw3anaf.js.map} +0 -0
  187. /package/dist/{chunk-es487acc.js.map → chunk-bq5nqqeq.js.map} +0 -0
  188. /package/dist/{chunk-53bek7sp.js.map → chunk-rh2fad7n.js.map} +0 -0
  189. /package/dist/{chunk-rend2sbk.js.map → chunk-y6frz1vm.js.map} +0 -0
package/dist/ai/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Kb as S,Lb as O9,Mb as bZ,Nb as fZ,Ob as m6}from"../chunk-3z9vhjd7.js";import{bc as yZ}from"../chunk-qx87cdfg.js";import{fc as fQ,jc as vQ}from"../chunk-ga7c7tq0.js";import{Cf as u6,Rf as M1,Sf as d9,Tf as z9,Uf as k9,hg as y9,jg as D9,kg as Q9,mg as wZ,og as c6,zf as y6}from"../chunk-j0sncgxc.js";import{pg as g6,rg as F$,sg as L$}from"../chunk-teny6xkw.js";import{wg as a9}from"../chunk-yv1psptb.js";import"../chunk-b1mk12xg.js";import"../chunk-hfyxvdjj.js";import{Cg as pZ,Dg as lZ,Rg as dZ}from"../chunk-57edag57.js";import"../chunk-jn59bsww.js";import{Dh as $9}from"../chunk-eazqda9z.js";import"../chunk-dm59ze55.js";import"../chunk-et3vhkbf.js";import"../chunk-8reepafh.js";import"../chunk-ddad3902.js";class g extends Error{status;body;requestId;constructor($,Q,Z){super(`Provider request failed with status ${$}: ${t6(Q)}`);this.name="ProviderHttpError",this.status=$,this.body=Q,this.requestId=Z}}class E9 extends Error{timeoutMs;constructor($){super(`Provider request timed out after ${$}ms`);this.name="ProviderTimeoutError",this.timeoutMs=$}}function t6($){let Q=xQ($);if(Q?.message)return Q.message;if(typeof $==="string")return $.slice(0,500);return"no error body"}function xQ($){if(!$||typeof $!=="object")return null;let Q=$,J=Q.error&&typeof Q.error==="object"?Q.error:$;if(typeof J.message!=="string"&&typeof J.code!=="string"&&typeof J.type!=="string")return null;let G=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:G,param:J.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 E9)return{code:"provider_error",message:$.message,retryable:!0};if($8($))return{code:"aborted",message:"The request was aborted.",retryable:!1};if($ instanceof g)return a6($.status,xQ($.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 J=Q?.message??Z,G=(Q?.code??"").toLowerCase(),W=(Q?.type??"").toLowerCase(),V=`${G} ${W} ${J}`.toLowerCase();if($===429){let Y=G==="insufficient_quota"||V.includes("quota");return{code:"rate_limited",message:J,retryable:!Y}}if($>=500||$===408||$===409)return{code:"provider_error",message:J,retryable:!0};if(r6(V))return{code:"context_length_exceeded",message:J,retryable:!1};if(e6(V))return{code:"content_filtered",message:J,retryable:!1};if(Q?.param?.startsWith("tools")||V.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function r6($){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 $8($){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 m($,Q){if(Q.aborted)return Promise.reject(new w);return new Promise((Z,J)=>{let G=()=>J(new w);Q.addEventListener("abort",G,{once:!0}),$.then(Z,J).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 x9($){if(!$.trim())return{};try{return JSON.parse($)}catch{}let Q=[],Z=!1,J=!1;for(let V of $){if(Z){if(J)J=!1;else if(V==="\\")J=!0;else if(V==='"')Z=!1;continue}if(V==='"')Z=!0;else if(V==="{")Q.push("}");else if(V==="[")Q.push("]");else if(V==="}"||V==="]")Q.pop()}let G=$;if(Z)G+='"';G=G.replace(/[,:]\s*$/,"");let W=Q.reverse().join("");try{return JSON.parse(G+W)}catch{try{return JSON.parse(G.replace(/,?\s*"[^"]*"\s*$/,"")+W)}catch{return{}}}}function I9($){return{name:"output",schema:$.toJSONSchema(),strict:z9($)}}function w9($,Q){let Z=$.safeParse(x9(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 b9($){if($.length>0)$[0];return $}function B9($,Q,Z){let J=$.content[$.content.length-1];if(J&&J.type===Q){J.text=(J.text??"")+Z;return}$.content.push(Q==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function f9($,Q,Z){let J=$.content[$.content.length-1];if(J&&J.type==="reasoning"&&J.id===Q){J.text=(J.text??"")+Z;return}$.content.push(Q?{type:"reasoning",id:Q,text:Z}:{type:"reasoning",text:Z})}function U$($){return F9($)}async function F9($,Q={}){let Z=`gen_${crypto.randomUUID()}`,J=await Z8($);if(Q.settled?.(J),!J.ok){if($.logErrors!==!1&&J.error.code!=="aborted")Q8(Z,J.error,Q.origin);if($.throwOnError)throw new L9({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function Q8($,Q,Z){let J=`[gemi/ai] generate() failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`,G={...Z,generateId:$,error:Q},W=!1;try{D9.error(J,G),W=!0}catch{}if(!W||Bun.env.NODE_ENV==="development")console.error(J,G)}async function Z8($){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 J={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},G=$.signal??new AbortController().signal,W=R(),V="stop",Y,H={},X="";try{let D=$.provider.stream({messages:[...Z],systemPrompt:$.instructions?.trim()?$.instructions:void 0,output:I9($.output),reasoning:$.reasoning,maxOutputTokens:$.maxOutputTokens,temperature:$.temperature,signal:$.signal})[Symbol.asyncIterator]();try{for(;;){let L=await m(Promise.resolve(D.next()),G);if(L.done)break;let F=L.value;switch(F.type){case"output-delta":X+=F.delta;break;case"text-delta":B9(J,"text",F.delta);break;case"reasoning-delta":f9(J,F.id,F.delta);break;case"finish":if(W=M(W,F.usage),!Y)V=F.reason;break;case"error":V="error",Y=F.error,H=b(F);break}}}finally{if(G.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(z){if(z instanceof w||G.aborted)V="aborted",Y=J8(G);else V="error",Y=$.provider.normalizeError(z),H=b(z)}let K=!1,B;if(!Y)if(V==="length")Y={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())Y={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let z=w9($.output,X);if(z.ok===!0)K=!0,B=z.value;else Y=z.error}if(K)J.content.push({type:"output",value:B});else if(X)B9(J,"text",X);for(let z of J.content)if((z.type==="text"||z.type==="reasoning")&&typeof z.text==="string")z.text=b9(z.text);if(J.finishReason=V,J.usage=W,Z.push(J),K)return{ok:!0,output:B,messages:Z,usage:W,finishReason:V};return{ok:!1,error:{...Y,...H},messages:Z,usage:W,finishReason:V}}function J8($){return $.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}class U9 extends S{id;code="attachment_not_found";constructor($){super(`No attachment ${$}.`);this.id=$;this.name="AttachmentNotFoundError"}}class u extends S{code="invalid_attachment_scope";constructor($){super($);this.name="InvalidAttachmentScopeError"}}function P$($){if(!$||typeof $.key!=="string"||$.key.length===0)throw new u("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 h="gemi_att_";function C$(){return`${h}${crypto.randomUUID()}`}class p{store;storage;scope;constructor($,Q,Z){this.store=$;this.storage=Q;this.scope=Z;P$(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 U9($);return Q}async read($){return await this.readRecord($,await this.get($))}async readRecord($,Q){if(!Q.objectName)throw new U9($);return await this.storage.read({name:Q.objectName})}async file($){let Q=await this.get($),J=(await this.readRecord($,Q)).body,G=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([G],Q.name,{type:Q.mimeType})}async put($,Q={}){let Z=C$(),J=Q.mimeType??$.type??"",G=Q.name??($ instanceof File?$.name:Z),W=await this.storage.put({name:O$(Z,G),body:$,contentType:J||void 0}),V={id:Z,scopeKey:this.scope.key,objectName:W,name:G,mimeType:J||"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,V),V}}function O$($,Q){let Z=/\.([A-Za-z0-9]{1,8})$/.exec(Q);return`attachments/${$}${Z?`.${Z[1].toLowerCase()}`:""}`}class v9{rows=new Map;async put($,Q){P$($),this.rows.set(Q.id,{...Q,scopeKey:$.key})}async find($,Q){P$($);let Z=this.rows.get(Q);if(!Z||Z.scopeKey!==$.key)return null;return Z}get size(){return this.rows.size}}var r=new v9;class P9{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,...J}=$,G={...structuredClone(J),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 J of this.jobs.values()){if(J.threadId!==$)continue;if(Q.states&&!Q.states.includes(J.state))continue;Z.push(J)}return Z.sort(IQ),(Q.limit===void 0?Z:Z.slice(0,Q.limit)).map((J)=>structuredClone(J))}async transition($,Q,Z){let J=this.jobs.get($);if(!J||!Q.includes(J.state))return!1;let G=structuredClone(Z),W=Date.now();if(Object.assign(J,G,{updatedAt:W}),G.state&&G.state!=="running"&&J.settledAt===void 0)J.settledAt=G.settledAt??W;return!0}async overdue($,Q){let Z=[];for(let J of this.jobs.values())if(J.state==="running"&&J.deadlineAt<=$)Z.push(J);return Z.sort((J,G)=>J.deadlineAt-G.deadlineAt),Z.slice(0,Math.max(0,Q)).map((J)=>structuredClone(J))}async now(){return Date.now()}trim($){let Q=[...this.jobs.values()].filter((Z)=>Z.threadId===$&&Z.state!=="running").sort(IQ);for(let Z of Q.slice(200))this.jobs.delete(Z.id)}}function IQ($,Q){return Q.createdAt-$.createdAt||($.id<Q.id?1:$.id>Q.id?-1:0)}var hQ=Symbol.for("gemi.ai.JobHandle");class g9{id;toolCallId;summary;deadlineAt;[hQ]=!0;constructor($,Q,Z,J){this.id=$;this.toolCallId=Q;this.summary=Z;this.deadlineAt=J}}function yQ($){return typeof $==="object"&&$!==null&&$[hQ]===!0}class C9 extends S{code="jobs_require_thread";constructor($){super($,{retryable:!1});this.name="JobsRequireThreadError"}}var e=new P9,G8=["running","ok","error"],y={get store(){return e},use($){e=$},get($){return e.get($)},async settle($,Q){return h9(e,$,Q)},async fail($,Q){return h9(e,$,{error:Q})},async sweep($={}){let Q=e,Z=$.limit??100,J=await N$(Q),G=0;for(let W of await Q.overdue(J,Z))if(await _$(Q,W))G++;return G}};async function N$($){return $.now?await $.now():Date.now()}function _$($,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 h9($,Q,Z){let J=await $.get(Q);if(!J||J.state!=="running")return!1;let G=Z.usage?M(J.usage??R(),Z.usage):void 0;if("error"in Z)return $.transition(Q,["running"],{state:"error",error:W8(J,Z.error),...G?{usage:G}:{}});return $.transition(Q,["running"],{state:"ok",output:gQ(Z.output,J),...G?{usage:G}:{}})}function W8($,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 S?Q.retryable:!0};if(!(Q instanceof S))console.error(`The background job ${$.job??"(tracked)"} for "${$.toolName}" failed.`,Q);return O9(Z,{source:"tool",toolName:$.toolName,cause:Q})}return{code:Q.code??"tool_error",message:String(Q.message),toolCallId:$.toolCallId,retryable:Q.retryable??!0}}function gQ($,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 q$=3600000;function uQ($){let Q=null,Z=(J,G,W={})=>{if($.async===void 0)throw new S(`"${$.toolName}" called ctx.jobs, but the tool does not declare \`async\`. Add \`async: { deadlineMs }\` to its definition.`,{retryable:!1});if(!$.jobs||!$.threadId)throw new C9(`"${$.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 C9(`"${$.toolName}" can only run in the background from the top-level agent, not from a sub-agent.`);if(Q)throw new S(`"${$.toolName}" started a background job already: a tool call has at most one.`,{retryable:!1});let V=W.deadlineMs??$.async.deadlineMs??q$;if(!Number.isFinite(V)||V<=0)throw new S(`A job's deadlineMs must be a positive number; got ${V}.`);let{jobs:Y,threadId:H}=$;return Q=(async()=>{let X=y.store,K=(await X.listForThread(H,{limit:50})).find((D)=>D.toolCallId===$.toolCallId);if(K)return wQ(K);let B=async()=>{let D=await X.create({id:`ajob_${crypto.randomUUID()}`,threadId:H,runId:$.runId,toolCallId:$.toolCallId,toolName:$.toolName,owner:Y.owner,job:J?J.name:null,...W.summary!==void 0?{summary:gQ(W.summary,$)}:{},attachmentScope:$.attachments?.scopeKey??null,deadlineMs:V});if(J)try{await V8(J,{jobId:D.id,args:G})}catch(L){if(X.transaction)throw L;throw await X.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=X.transaction?await X.transaction(B):await B();return wQ(z)})(),Q};return{start:(J,G,W)=>Z(J,G,W),track:(J)=>Z(null,void 0,J)}}function wQ($){return new g9($.id,$.toolCallId,$.summary,$.deadlineAt)}function V8($,Q){if($.name==="unset"||!$.name)throw Error("Cannot start an AgentJob with no `static name`.");return $9(vQ).push($,JSON.stringify([Q]))}class M$ extends fQ{attachments=r;attachmentStorage=y9;constructor(){super();let $=this.run;this.run=(Q)=>this.$runEnvelope(Q,$)}onDeadletter($,...Q){let Z=Q[0];if(!Z?.jobId)return;h9(y.store,Z.jobId,{error:$}).catch((J)=>{console.error(`Could not record the failure of background job ${Z.jobId}.`,J)})}async $runEnvelope($,Q){let Z=y.store,J=await Z.get($.jobId);if(!J||J.state!=="running")return;let G=new cQ(J,this),W;try{W=await Q.call(this,$.args,G)}catch(V){throw await bQ(Z,J.id,G.usage),V}if(this.$outcome)return await bQ(Z,J.id,G.usage),W;return await h9(Z,J.id,{output:W,usage:G.usage}),W}}async function bQ($,Q,Z){if(Z.totalTokens===0&&Z.inputTokens===0&&Z.outputTokens===0)return;let J=await $.get(Q);if(!J)return;await $.transition(Q,G8,{usage:M(J.usage??R(),Z)}).catch(()=>{})}class cQ{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,J=()=>{if(!Z)throw new u("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,W={})=>J().put(G,W),get:(G)=>J().get(G),read:(G)=>J().read(G),file:(G)=>J().file(G)}}generate($){return F9($,{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,...J}=Q,G=await $.generate({...J,signal:this.signal});return this.park($,G,Z)}async editImage($,Q){let{name:Z,images:J,mask:G,...W}=Q,V=async(H)=>typeof H==="string"?await this.attachments.file(H):H,Y=await $.edit({...W,images:await Promise.all(J.map(V)),...G?{mask:await V(G)}:{},signal:this.signal});return this.park($,Y,Z)}async park($,Q,Z){this.usage=M(this.usage,Q.usage);let J=Q.mimeType==="image/jpeg"?"jpg":"png";return{attachment:await this.attachments.put(Q.image,{name:Z??`${$.name}.${J}`,mimeType:Q.mimeType}),size:Q.size,mimeType:Q.mimeType,usage:Q.usage}}}import{createHmac as X8,hkdfSync as Y8,randomBytes as mQ,timingSafeEqual as H8}from"crypto";class N9{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 J=this.spent.get($);if(J!==void 0&&J>Z)return!1;return this.spent.set($,Q),!0}get size(){return this.spent.size}sweep($){for(let[Q,Z]of this.spent)if(Z<=$)this.spent.delete(Q);this.sweepAt=Math.max(1024,this.spent.size*2)}}class R${injectedClient;prefix;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:ai:nonce"}async consume($,Q){let Z=Math.max(1,Math.ceil(Q-Date.now()));return await this.client.send("SET",[`${this.prefix}:${$}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let $=$9(),Q=$.bound(Q9)?$.make(Q9).client:void 0;if(!Q)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return Q}}var Z9=new N9;var j$="agt2",c9="agt1",pQ=[j$,c9],S$=86400000,K8=Date.now()+S$;function lQ($){return $<=K8}var dQ="gemi.ai.pending-call.v1",iQ="gemi.ai.nested-run.v1",z8="gemi.ai.execution-receipt.v1",B8="gemi.ai.signing",u9=new Map;function _9($,Q){let Z=A$(Q),J=`${$}\x00${Z}`,G=u9.get(J);if(!G){if(G=Buffer.from(Y8("sha256",Z,B8,$,32)),u9.size>64)u9.clear();u9.set(J,G)}return G}function A$($){let Q=$??process.env.SECRET;if(!Q)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return Q}function v($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return`[${$.map(v).join(",")}]`;let Q=$;return`{${Object.keys(Q).filter((J)=>Q[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${v(Q[J])}`).join(",")}}`}function D8($){return $.map((Q)=>`${Q.length}:${Q}`).join("")}function l($,Q){return X8("sha256",$).update(D8(Q)).digest()}function nQ($,Q){let Z=Buffer.from($.split(".")[4],"base64url");return Z.length===Q.length&&H8(Z,Q)}function T$($){return v($??null)}function oQ($,Q,Z){return[j$,$.runId,$.toolCallId,$.name,$.kind,Q,String(Z),v($.input),v($.path??[]),T$($.subject)]}function F8($,Q,Z){let J=[c9,$.runId,$.toolCallId,$.name,$.kind,Q,String(Z),v($.input)];if($.path&&$.path.length>0)J.push(v($.path));return J}var sQ=($)=>Buffer.from($,"utf8").toString("base64url"),L8=($)=>Buffer.from($,"base64url").toString("utf8");function tQ($,Q={}){let Z=_9(dQ,Q.secret),G=(Q.now??Date.now())+(Q.ttlMs??S$),W=mQ(12).toString("base64url"),V=l(Z,oQ($,W,G)).toString("base64url");return[j$,sQ($.runId),W,G.toString(36),V].join(".")}function k$($){return p9($,pQ)}function p9($,Q){let Z=$.split(".");if(Z.length!==5||!Q.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:L8(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function aQ($,Q,Z={}){let J=p9($,pQ);if(!J)return{ok:!1,reason:"malformed"};if(J.version===c9&&!lQ(J.expiresAt))return{ok:!1,reason:"forged"};let G=J.version===c9?l(A$(Z.secret),F8(Q,J.nonce,J.expiresAt)):l(_9(dQ,Z.secret),oQ(Q,J.nonce,J.expiresAt));if(!nQ($,G))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 E$="agn2",m9="agn1",rQ=[E$,m9];function eQ($,Q,Z){return[...$Z($,Q,Z,E$),T$($.subject)]}function $Z($,Q,Z,J=m9){return[J,$.runId,v($.path),$.nestedRunId,Q,String(Z),v([...$.open].sort()),v($.input)]}function QZ($,Q={}){let Z=_9(iQ,Q.secret),G=(Q.now??Date.now())+(Q.ttlMs??S$),W=mQ(12).toString("base64url"),V=l(Z,eQ($,W,G)).toString("base64url");return[E$,sQ($.runId),W,G.toString(36),V].join(".")}function ZZ($,Q,Z={}){let J=p9($,rQ);if(!J)return{ok:!1,reason:"malformed"};if(J.version===m9&&!lQ(J.expiresAt))return{ok:!1,reason:"forged"};let G={...Q,runId:J.runId},W=J.version===m9?l(A$(Z.secret),$Z(G,J.nonce,J.expiresAt)):l(_9(iQ,Z.secret),eQ(G,J.nonce,J.expiresAt));if(!nQ($,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}}function JZ($,Q,Z={}){let J=_9(z8,Z.secret);return l(J,[$,Q.runId,Q.toolCallId,Q.name,Q.kind,v(Q.input),v(Q.path??[]),T$(Q.subject)]).toString("base64url")}function GZ($,Q){return VZ(Q,k$($))}function WZ($,Q){return VZ(Q,p9($,rQ))}async function VZ($,Q){if(!Q)return!1;return $.consume(Q.nonce,Q.expiresAt)}function d($){let Q=new Set;for(let Z of $)for(let J of Z.content??[]){if(J.type!=="tool-call")continue;for(let G of J.attachments??[])if(G&&"shown"in G&&G.shown)Q.add(G.shown.messageId)}return Q}function q9($){if($.length===0)return[];let Q=d($),Z=[0];for(let J=1;J<$.length;J++){let G=$[J];if(G.role==="user"&&!Q.has(G.id))Z.push(J)}return Z}function U8($){let Q=q9($);return Q.map((Z,J)=>$.slice(Z,Q[J+1]??$.length))}function YZ($){try{return JSON.stringify($).length}catch{return 0}}var P8=4,HZ=10,KZ="[Earlier turns of this conversation are not shown.]";function J9($,Q={}){let Z=[...$],J=q9(Z),G=C8(Q),W=l9(Q.maxTurns)??1/0,V=Math.max(1,Math.floor(l9(Q.step)??HZ));if(J.length<=1||W>=J.length&&G===1/0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let Y=Array.from({length:Z.length+1},()=>0);if(G!==1/0)for(let U=Z.length-1;U>=0;U--)Y[U]=Y[U+1]+YZ(Z[U]);let H=(U)=>J.length-U<=W&&Y[J[U]]<=G,X=-1;for(let U=0;U<J.length;U+=V)if(H(U)){X=U;break}if(X<0){for(let U=0;U<J.length;U++)if(H(U)){X=U;break}}if(X<0)X=J.length-1;if(X===0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let K=J[X],B=Z.slice(0,K),z=B.filter((U)=>U.role==="system"),D=O8(B,Z.slice(K)),L={turns:X,messages:B.length-z.length},F=typeof Q.note==="function"?Q.note(L):Q.note===void 0?KZ:Q.note;if(F){let U=D[0];D[0]={...U,content:[{type:"text",text:F},...U.content]}}return{messages:[...z,...D],start:K,omittedTurns:L.turns,omittedMessages:L.messages}}function l9($){return typeof $==="number"&&$>0?$:void 0}function C8($){let Q=l9($.maxBytes)??1/0,Z=l9($.maxTokens);return Math.min(Q,Z===void 0?1/0:Z*P8)}function XZ($,Q){let Z=Array.isArray($?.namespaces)?$.namespaces:[],J=Array.isArray($?.loaded)?$.loaded:[];return Q.namespace?Z.includes(Q.namespace):J.includes(String(Q.name))}function x$($){return Array.isArray($.toolSearches)?$.toolSearches:[]}function O8($,Q){let Z=[];for(let X of $)for(let K of X.content??[])if(K.type==="tool-call")Z.push(...x$(K));if(Z.length===0)return Q;let J=[],G=new Set,W;if(Q.forEach((X,K)=>{(X.content??[]).forEach((B,z)=>{if(B.type!=="tool-call"||B.partial)return;if(J.push(...x$(B)),J.some((L)=>XZ(L,B)))return;let D=Z.filter((L)=>XZ(L,B));if(D.length===0)return;for(let L of D)G.add(L);W??={message:K,part:z}})}),!W)return Q;let V=Z.filter((X)=>G.has(X)),Y=[...Q],H=Y[W.message];return Y[W.message]={...H,content:H.content.map((X,K)=>K===W.part&&X.type==="tool-call"?{...X,toolSearches:[...V,...x$(X)]}:X)},Y}var FZ=1000,N8=24000,_8=20000,LZ=1e5,q8=120000,UZ=["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(" "),PZ="[Summary of the earlier turns of this conversation, which are not shown:]",M8=8;class b${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=n9(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 n9($,Q){return[Q,...$.filter((Z)=>Z.cutMessageId!==Q.cutMessageId)].slice(0,M8)}var f$=new b$;function CZ($){let Q=$;return typeof Q?.loadSummaries==="function"&&typeof Q?.saveSummary==="function"}function OZ($,Q,Z){let J=c(Z.maxSummaryTokens)??FZ,G=(H)=>Math.max(1,H-J),W={...Q,...c(Q.maxTokens)?{maxTokens:G(Q.maxTokens)}:{},...c(Q.maxBytes)?{maxBytes:Math.max(1,Q.maxBytes-J*w$)}:{}},V=R8(Q,Z),Y={...W,note:!1,...V?{maxTokens:Math.min(W.maxTokens??1/0,G(V))}:{}};return{plain:W,cut:J9($,Y),maxSummaryTokens:J}}function R8($,Q){if(Q.triggerTokens===!1)return;let Z=c(Q.triggerTokens||void 0);if(Z)return Z;if(c($.maxTokens)||c($.maxBytes))return;return LZ}async function NZ($){let{history:Q,window:Z,compact:J}=$,{plain:G,cut:W,maxSummaryTokens:V}=OZ(Q,Z,J);if(W.omittedTurns===0)return W.messages;let Y=`${Q[W.start].id}:${W.start}`,H=$.memo?.get(Y);if(H===void 0){try{H=await k8($,W.start,V)}catch(D){if($.signal.aborted)throw D;H=null}if(!$.signal.aborted)$.memo?.set(Y,H)}if(!H)return J9(Q,G).messages;let X=Q.length-W.start,K=W.messages.slice(0,W.messages.length-X),B=W.messages.slice(W.messages.length-X),z=Q[W.start];return[...K,{id:`summary_${z.id}`,role:"user",content:[{type:"text",text:`${PZ}
2
+ import{Kb as S,Lb as O9,Mb as bZ,Nb as fZ,Ob as m6}from"../chunk-3z9vhjd7.js";import{bc as yZ}from"../chunk-qx87cdfg.js";import{fc as fQ,jc as vQ}from"../chunk-g8kx549d.js";import{Bf as y6,Ef as u6,Tf as M1,Uf as d9,Vf as z9,Wf as k9,jg as y9,lg as D9,mg as Q9,og as wZ,qg as c6}from"../chunk-cqnfp0n9.js";import{rg as g6,tg as F$,ug as L$}from"../chunk-r7b12dmm.js";import{yg as a9}from"../chunk-y596ghpz.js";import"../chunk-c7mp2kyp.js";import"../chunk-y6v0x869.js";import{Eg as pZ,Fg as lZ,Tg as dZ}from"../chunk-4t1pbt9p.js";import"../chunk-vwprq300.js";import{Fh as $9}from"../chunk-z5hrymvn.js";import"../chunk-v4gwmhtf.js";import"../chunk-vc9phr57.js";import"../chunk-fr0arqdj.js";import"../chunk-8mbyyh8j.js";class g extends Error{status;body;requestId;constructor($,Q,Z){super(`Provider request failed with status ${$}: ${t6(Q)}`);this.name="ProviderHttpError",this.status=$,this.body=Q,this.requestId=Z}}class E9 extends Error{timeoutMs;constructor($){super(`Provider request timed out after ${$}ms`);this.name="ProviderTimeoutError",this.timeoutMs=$}}function t6($){let Q=xQ($);if(Q?.message)return Q.message;if(typeof $==="string")return $.slice(0,500);return"no error body"}function xQ($){if(!$||typeof $!=="object")return null;let Q=$,J=Q.error&&typeof Q.error==="object"?Q.error:$;if(typeof J.message!=="string"&&typeof J.code!=="string"&&typeof J.type!=="string")return null;let G=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:G,param:J.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 E9)return{code:"provider_error",message:$.message,retryable:!0};if($8($))return{code:"aborted",message:"The request was aborted.",retryable:!1};if($ instanceof g)return a6($.status,xQ($.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 J=Q?.message??Z,G=(Q?.code??"").toLowerCase(),W=(Q?.type??"").toLowerCase(),V=`${G} ${W} ${J}`.toLowerCase();if($===429){let Y=G==="insufficient_quota"||V.includes("quota");return{code:"rate_limited",message:J,retryable:!Y}}if($>=500||$===408||$===409)return{code:"provider_error",message:J,retryable:!0};if(r6(V))return{code:"context_length_exceeded",message:J,retryable:!1};if(e6(V))return{code:"content_filtered",message:J,retryable:!1};if(Q?.param?.startsWith("tools")||V.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function r6($){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 $8($){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 m($,Q){if(Q.aborted)return Promise.reject(new w);return new Promise((Z,J)=>{let G=()=>J(new w);Q.addEventListener("abort",G,{once:!0}),$.then(Z,J).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 x9($){if(!$.trim())return{};try{return JSON.parse($)}catch{}let Q=[],Z=!1,J=!1;for(let V of $){if(Z){if(J)J=!1;else if(V==="\\")J=!0;else if(V==='"')Z=!1;continue}if(V==='"')Z=!0;else if(V==="{")Q.push("}");else if(V==="[")Q.push("]");else if(V==="}"||V==="]")Q.pop()}let G=$;if(Z)G+='"';G=G.replace(/[,:]\s*$/,"");let W=Q.reverse().join("");try{return JSON.parse(G+W)}catch{try{return JSON.parse(G.replace(/,?\s*"[^"]*"\s*$/,"")+W)}catch{return{}}}}function I9($){return{name:"output",schema:$.toJSONSchema(),strict:z9($)}}function w9($,Q){let Z=$.safeParse(x9(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 b9($){if($.length>0)$[0];return $}function B9($,Q,Z){let J=$.content[$.content.length-1];if(J&&J.type===Q){J.text=(J.text??"")+Z;return}$.content.push(Q==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function f9($,Q,Z){let J=$.content[$.content.length-1];if(J&&J.type==="reasoning"&&J.id===Q){J.text=(J.text??"")+Z;return}$.content.push(Q?{type:"reasoning",id:Q,text:Z}:{type:"reasoning",text:Z})}function U$($){return F9($)}async function F9($,Q={}){let Z=`gen_${crypto.randomUUID()}`,J=await Z8($);if(Q.settled?.(J),!J.ok){if($.logErrors!==!1&&J.error.code!=="aborted")Q8(Z,J.error,Q.origin);if($.throwOnError)throw new L9({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function Q8($,Q,Z){let J=`[gemi/ai] generate() failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`,G={...Z,generateId:$,error:Q},W=!1;try{D9.error(J,G),W=!0}catch{}if(!W||Bun.env.NODE_ENV==="development")console.error(J,G)}async function Z8($){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 J={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},G=$.signal??new AbortController().signal,W=R(),V="stop",Y,H={},X="";try{let D=$.provider.stream({messages:[...Z],systemPrompt:$.instructions?.trim()?$.instructions:void 0,output:I9($.output),reasoning:$.reasoning,maxOutputTokens:$.maxOutputTokens,temperature:$.temperature,signal:$.signal})[Symbol.asyncIterator]();try{for(;;){let L=await m(Promise.resolve(D.next()),G);if(L.done)break;let F=L.value;switch(F.type){case"output-delta":X+=F.delta;break;case"text-delta":B9(J,"text",F.delta);break;case"reasoning-delta":f9(J,F.id,F.delta);break;case"finish":if(W=M(W,F.usage),!Y)V=F.reason;break;case"error":V="error",Y=F.error,H=b(F);break}}}finally{if(G.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(z){if(z instanceof w||G.aborted)V="aborted",Y=J8(G);else V="error",Y=$.provider.normalizeError(z),H=b(z)}let K=!1,B;if(!Y)if(V==="length")Y={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())Y={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let z=w9($.output,X);if(z.ok===!0)K=!0,B=z.value;else Y=z.error}if(K)J.content.push({type:"output",value:B});else if(X)B9(J,"text",X);for(let z of J.content)if((z.type==="text"||z.type==="reasoning")&&typeof z.text==="string")z.text=b9(z.text);if(J.finishReason=V,J.usage=W,Z.push(J),K)return{ok:!0,output:B,messages:Z,usage:W,finishReason:V};return{ok:!1,error:{...Y,...H},messages:Z,usage:W,finishReason:V}}function J8($){return $.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}class U9 extends S{id;code="attachment_not_found";constructor($){super(`No attachment ${$}.`);this.id=$;this.name="AttachmentNotFoundError"}}class u extends S{code="invalid_attachment_scope";constructor($){super($);this.name="InvalidAttachmentScopeError"}}function P$($){if(!$||typeof $.key!=="string"||$.key.length===0)throw new u("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 h="gemi_att_";function C$(){return`${h}${crypto.randomUUID()}`}class p{store;storage;scope;constructor($,Q,Z){this.store=$;this.storage=Q;this.scope=Z;P$(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 U9($);return Q}async read($){return await this.readRecord($,await this.get($))}async readRecord($,Q){if(!Q.objectName)throw new U9($);return await this.storage.read({name:Q.objectName})}async file($){let Q=await this.get($),J=(await this.readRecord($,Q)).body,G=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([G],Q.name,{type:Q.mimeType})}async put($,Q={}){let Z=C$(),J=Q.mimeType??$.type??"",G=Q.name??($ instanceof File?$.name:Z),W=await this.storage.put({name:O$(Z,G),body:$,contentType:J||void 0}),V={id:Z,scopeKey:this.scope.key,objectName:W,name:G,mimeType:J||"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,V),V}}function O$($,Q){let Z=/\.([A-Za-z0-9]{1,8})$/.exec(Q);return`attachments/${$}${Z?`.${Z[1].toLowerCase()}`:""}`}class v9{rows=new Map;async put($,Q){P$($),this.rows.set(Q.id,{...Q,scopeKey:$.key})}async find($,Q){P$($);let Z=this.rows.get(Q);if(!Z||Z.scopeKey!==$.key)return null;return Z}get size(){return this.rows.size}}var r=new v9;class P9{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,...J}=$,G={...structuredClone(J),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 J of this.jobs.values()){if(J.threadId!==$)continue;if(Q.states&&!Q.states.includes(J.state))continue;Z.push(J)}return Z.sort(IQ),(Q.limit===void 0?Z:Z.slice(0,Q.limit)).map((J)=>structuredClone(J))}async transition($,Q,Z){let J=this.jobs.get($);if(!J||!Q.includes(J.state))return!1;let G=structuredClone(Z),W=Date.now();if(Object.assign(J,G,{updatedAt:W}),G.state&&G.state!=="running"&&J.settledAt===void 0)J.settledAt=G.settledAt??W;return!0}async overdue($,Q){let Z=[];for(let J of this.jobs.values())if(J.state==="running"&&J.deadlineAt<=$)Z.push(J);return Z.sort((J,G)=>J.deadlineAt-G.deadlineAt),Z.slice(0,Math.max(0,Q)).map((J)=>structuredClone(J))}async now(){return Date.now()}trim($){let Q=[...this.jobs.values()].filter((Z)=>Z.threadId===$&&Z.state!=="running").sort(IQ);for(let Z of Q.slice(200))this.jobs.delete(Z.id)}}function IQ($,Q){return Q.createdAt-$.createdAt||($.id<Q.id?1:$.id>Q.id?-1:0)}var hQ=Symbol.for("gemi.ai.JobHandle");class g9{id;toolCallId;summary;deadlineAt;[hQ]=!0;constructor($,Q,Z,J){this.id=$;this.toolCallId=Q;this.summary=Z;this.deadlineAt=J}}function yQ($){return typeof $==="object"&&$!==null&&$[hQ]===!0}class C9 extends S{code="jobs_require_thread";constructor($){super($,{retryable:!1});this.name="JobsRequireThreadError"}}var e=new P9,G8=["running","ok","error"],y={get store(){return e},use($){e=$},get($){return e.get($)},async settle($,Q){return h9(e,$,Q)},async fail($,Q){return h9(e,$,{error:Q})},async sweep($={}){let Q=e,Z=$.limit??100,J=await N$(Q),G=0;for(let W of await Q.overdue(J,Z))if(await _$(Q,W))G++;return G}};async function N$($){return $.now?await $.now():Date.now()}function _$($,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 h9($,Q,Z){let J=await $.get(Q);if(!J||J.state!=="running")return!1;let G=Z.usage?M(J.usage??R(),Z.usage):void 0;if("error"in Z)return $.transition(Q,["running"],{state:"error",error:W8(J,Z.error),...G?{usage:G}:{}});return $.transition(Q,["running"],{state:"ok",output:gQ(Z.output,J),...G?{usage:G}:{}})}function W8($,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 S?Q.retryable:!0};if(!(Q instanceof S))console.error(`The background job ${$.job??"(tracked)"} for "${$.toolName}" failed.`,Q);return O9(Z,{source:"tool",toolName:$.toolName,cause:Q})}return{code:Q.code??"tool_error",message:String(Q.message),toolCallId:$.toolCallId,retryable:Q.retryable??!0}}function gQ($,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 q$=3600000;function uQ($){let Q=null,Z=(J,G,W={})=>{if($.async===void 0)throw new S(`"${$.toolName}" called ctx.jobs, but the tool does not declare \`async\`. Add \`async: { deadlineMs }\` to its definition.`,{retryable:!1});if(!$.jobs||!$.threadId)throw new C9(`"${$.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 C9(`"${$.toolName}" can only run in the background from the top-level agent, not from a sub-agent.`);if(Q)throw new S(`"${$.toolName}" started a background job already: a tool call has at most one.`,{retryable:!1});let V=W.deadlineMs??$.async.deadlineMs??q$;if(!Number.isFinite(V)||V<=0)throw new S(`A job's deadlineMs must be a positive number; got ${V}.`);let{jobs:Y,threadId:H}=$;return Q=(async()=>{let X=y.store,K=(await X.listForThread(H,{limit:50})).find((D)=>D.toolCallId===$.toolCallId);if(K)return wQ(K);let B=async()=>{let D=await X.create({id:`ajob_${crypto.randomUUID()}`,threadId:H,runId:$.runId,toolCallId:$.toolCallId,toolName:$.toolName,owner:Y.owner,job:J?J.name:null,...W.summary!==void 0?{summary:gQ(W.summary,$)}:{},attachmentScope:$.attachments?.scopeKey??null,deadlineMs:V});if(J)try{await V8(J,{jobId:D.id,args:G})}catch(L){if(X.transaction)throw L;throw await X.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=X.transaction?await X.transaction(B):await B();return wQ(z)})(),Q};return{start:(J,G,W)=>Z(J,G,W),track:(J)=>Z(null,void 0,J)}}function wQ($){return new g9($.id,$.toolCallId,$.summary,$.deadlineAt)}function V8($,Q){if($.name==="unset"||!$.name)throw Error("Cannot start an AgentJob with no `static name`.");return $9(vQ).push($,JSON.stringify([Q]))}class M$ extends fQ{attachments=r;attachmentStorage=y9;constructor(){super();let $=this.run;this.run=(Q)=>this.$runEnvelope(Q,$)}onDeadletter($,...Q){let Z=Q[0];if(!Z?.jobId)return;h9(y.store,Z.jobId,{error:$}).catch((J)=>{console.error(`Could not record the failure of background job ${Z.jobId}.`,J)})}async $runEnvelope($,Q){let Z=y.store,J=await Z.get($.jobId);if(!J||J.state!=="running")return;let G=new cQ(J,this),W;try{W=await Q.call(this,$.args,G)}catch(V){throw await bQ(Z,J.id,G.usage),V}if(this.$outcome)return await bQ(Z,J.id,G.usage),W;return await h9(Z,J.id,{output:W,usage:G.usage}),W}}async function bQ($,Q,Z){if(Z.totalTokens===0&&Z.inputTokens===0&&Z.outputTokens===0)return;let J=await $.get(Q);if(!J)return;await $.transition(Q,G8,{usage:M(J.usage??R(),Z)}).catch(()=>{})}class cQ{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,J=()=>{if(!Z)throw new u("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,W={})=>J().put(G,W),get:(G)=>J().get(G),read:(G)=>J().read(G),file:(G)=>J().file(G)}}generate($){return F9($,{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,...J}=Q,G=await $.generate({...J,signal:this.signal});return this.park($,G,Z)}async editImage($,Q){let{name:Z,images:J,mask:G,...W}=Q,V=async(H)=>typeof H==="string"?await this.attachments.file(H):H,Y=await $.edit({...W,images:await Promise.all(J.map(V)),...G?{mask:await V(G)}:{},signal:this.signal});return this.park($,Y,Z)}async park($,Q,Z){this.usage=M(this.usage,Q.usage);let J=Q.mimeType==="image/jpeg"?"jpg":"png";return{attachment:await this.attachments.put(Q.image,{name:Z??`${$.name}.${J}`,mimeType:Q.mimeType}),size:Q.size,mimeType:Q.mimeType,usage:Q.usage}}}import{createHmac as X8,hkdfSync as Y8,randomBytes as mQ,timingSafeEqual as H8}from"crypto";class N9{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 J=this.spent.get($);if(J!==void 0&&J>Z)return!1;return this.spent.set($,Q),!0}get size(){return this.spent.size}sweep($){for(let[Q,Z]of this.spent)if(Z<=$)this.spent.delete(Q);this.sweepAt=Math.max(1024,this.spent.size*2)}}class R${injectedClient;prefix;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:ai:nonce"}async consume($,Q){let Z=Math.max(1,Math.ceil(Q-Date.now()));return await this.client.send("SET",[`${this.prefix}:${$}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let $=$9(),Q=$.bound(Q9)?$.make(Q9).client:void 0;if(!Q)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return Q}}var Z9=new N9;var j$="agt2",c9="agt1",pQ=[j$,c9],S$=86400000,K8=Date.now()+S$;function lQ($){return $<=K8}var dQ="gemi.ai.pending-call.v1",iQ="gemi.ai.nested-run.v1",z8="gemi.ai.execution-receipt.v1",B8="gemi.ai.signing",u9=new Map;function _9($,Q){let Z=A$(Q),J=`${$}\x00${Z}`,G=u9.get(J);if(!G){if(G=Buffer.from(Y8("sha256",Z,B8,$,32)),u9.size>64)u9.clear();u9.set(J,G)}return G}function A$($){let Q=$??process.env.SECRET;if(!Q)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return Q}function v($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return`[${$.map(v).join(",")}]`;let Q=$;return`{${Object.keys(Q).filter((J)=>Q[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${v(Q[J])}`).join(",")}}`}function D8($){return $.map((Q)=>`${Q.length}:${Q}`).join("")}function l($,Q){return X8("sha256",$).update(D8(Q)).digest()}function nQ($,Q){let Z=Buffer.from($.split(".")[4],"base64url");return Z.length===Q.length&&H8(Z,Q)}function T$($){return v($??null)}function oQ($,Q,Z){return[j$,$.runId,$.toolCallId,$.name,$.kind,Q,String(Z),v($.input),v($.path??[]),T$($.subject)]}function F8($,Q,Z){let J=[c9,$.runId,$.toolCallId,$.name,$.kind,Q,String(Z),v($.input)];if($.path&&$.path.length>0)J.push(v($.path));return J}var sQ=($)=>Buffer.from($,"utf8").toString("base64url"),L8=($)=>Buffer.from($,"base64url").toString("utf8");function tQ($,Q={}){let Z=_9(dQ,Q.secret),G=(Q.now??Date.now())+(Q.ttlMs??S$),W=mQ(12).toString("base64url"),V=l(Z,oQ($,W,G)).toString("base64url");return[j$,sQ($.runId),W,G.toString(36),V].join(".")}function k$($){return p9($,pQ)}function p9($,Q){let Z=$.split(".");if(Z.length!==5||!Q.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:L8(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function aQ($,Q,Z={}){let J=p9($,pQ);if(!J)return{ok:!1,reason:"malformed"};if(J.version===c9&&!lQ(J.expiresAt))return{ok:!1,reason:"forged"};let G=J.version===c9?l(A$(Z.secret),F8(Q,J.nonce,J.expiresAt)):l(_9(dQ,Z.secret),oQ(Q,J.nonce,J.expiresAt));if(!nQ($,G))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 E$="agn2",m9="agn1",rQ=[E$,m9];function eQ($,Q,Z){return[...$Z($,Q,Z,E$),T$($.subject)]}function $Z($,Q,Z,J=m9){return[J,$.runId,v($.path),$.nestedRunId,Q,String(Z),v([...$.open].sort()),v($.input)]}function QZ($,Q={}){let Z=_9(iQ,Q.secret),G=(Q.now??Date.now())+(Q.ttlMs??S$),W=mQ(12).toString("base64url"),V=l(Z,eQ($,W,G)).toString("base64url");return[E$,sQ($.runId),W,G.toString(36),V].join(".")}function ZZ($,Q,Z={}){let J=p9($,rQ);if(!J)return{ok:!1,reason:"malformed"};if(J.version===m9&&!lQ(J.expiresAt))return{ok:!1,reason:"forged"};let G={...Q,runId:J.runId},W=J.version===m9?l(A$(Z.secret),$Z(G,J.nonce,J.expiresAt)):l(_9(iQ,Z.secret),eQ(G,J.nonce,J.expiresAt));if(!nQ($,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}}function JZ($,Q,Z={}){let J=_9(z8,Z.secret);return l(J,[$,Q.runId,Q.toolCallId,Q.name,Q.kind,v(Q.input),v(Q.path??[]),T$(Q.subject)]).toString("base64url")}function GZ($,Q){return VZ(Q,k$($))}function WZ($,Q){return VZ(Q,p9($,rQ))}async function VZ($,Q){if(!Q)return!1;return $.consume(Q.nonce,Q.expiresAt)}function d($){let Q=new Set;for(let Z of $)for(let J of Z.content??[]){if(J.type!=="tool-call")continue;for(let G of J.attachments??[])if(G&&"shown"in G&&G.shown)Q.add(G.shown.messageId)}return Q}function q9($){if($.length===0)return[];let Q=d($),Z=[0];for(let J=1;J<$.length;J++){let G=$[J];if(G.role==="user"&&!Q.has(G.id))Z.push(J)}return Z}function U8($){let Q=q9($);return Q.map((Z,J)=>$.slice(Z,Q[J+1]??$.length))}function YZ($){try{return JSON.stringify($).length}catch{return 0}}var P8=4,HZ=10,KZ="[Earlier turns of this conversation are not shown.]";function J9($,Q={}){let Z=[...$],J=q9(Z),G=C8(Q),W=l9(Q.maxTurns)??1/0,V=Math.max(1,Math.floor(l9(Q.step)??HZ));if(J.length<=1||W>=J.length&&G===1/0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let Y=Array.from({length:Z.length+1},()=>0);if(G!==1/0)for(let U=Z.length-1;U>=0;U--)Y[U]=Y[U+1]+YZ(Z[U]);let H=(U)=>J.length-U<=W&&Y[J[U]]<=G,X=-1;for(let U=0;U<J.length;U+=V)if(H(U)){X=U;break}if(X<0){for(let U=0;U<J.length;U++)if(H(U)){X=U;break}}if(X<0)X=J.length-1;if(X===0)return{messages:Z,start:0,omittedTurns:0,omittedMessages:0};let K=J[X],B=Z.slice(0,K),z=B.filter((U)=>U.role==="system"),D=O8(B,Z.slice(K)),L={turns:X,messages:B.length-z.length},F=typeof Q.note==="function"?Q.note(L):Q.note===void 0?KZ:Q.note;if(F){let U=D[0];D[0]={...U,content:[{type:"text",text:F},...U.content]}}return{messages:[...z,...D],start:K,omittedTurns:L.turns,omittedMessages:L.messages}}function l9($){return typeof $==="number"&&$>0?$:void 0}function C8($){let Q=l9($.maxBytes)??1/0,Z=l9($.maxTokens);return Math.min(Q,Z===void 0?1/0:Z*P8)}function XZ($,Q){let Z=Array.isArray($?.namespaces)?$.namespaces:[],J=Array.isArray($?.loaded)?$.loaded:[];return Q.namespace?Z.includes(Q.namespace):J.includes(String(Q.name))}function x$($){return Array.isArray($.toolSearches)?$.toolSearches:[]}function O8($,Q){let Z=[];for(let X of $)for(let K of X.content??[])if(K.type==="tool-call")Z.push(...x$(K));if(Z.length===0)return Q;let J=[],G=new Set,W;if(Q.forEach((X,K)=>{(X.content??[]).forEach((B,z)=>{if(B.type!=="tool-call"||B.partial)return;if(J.push(...x$(B)),J.some((L)=>XZ(L,B)))return;let D=Z.filter((L)=>XZ(L,B));if(D.length===0)return;for(let L of D)G.add(L);W??={message:K,part:z}})}),!W)return Q;let V=Z.filter((X)=>G.has(X)),Y=[...Q],H=Y[W.message];return Y[W.message]={...H,content:H.content.map((X,K)=>K===W.part&&X.type==="tool-call"?{...X,toolSearches:[...V,...x$(X)]}:X)},Y}var FZ=1000,N8=24000,_8=20000,LZ=1e5,q8=120000,UZ=["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(" "),PZ="[Summary of the earlier turns of this conversation, which are not shown:]",M8=8;class b${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=n9(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 n9($,Q){return[Q,...$.filter((Z)=>Z.cutMessageId!==Q.cutMessageId)].slice(0,M8)}var f$=new b$;function CZ($){let Q=$;return typeof Q?.loadSummaries==="function"&&typeof Q?.saveSummary==="function"}function OZ($,Q,Z){let J=c(Z.maxSummaryTokens)??FZ,G=(H)=>Math.max(1,H-J),W={...Q,...c(Q.maxTokens)?{maxTokens:G(Q.maxTokens)}:{},...c(Q.maxBytes)?{maxBytes:Math.max(1,Q.maxBytes-J*w$)}:{}},V=R8(Q,Z),Y={...W,note:!1,...V?{maxTokens:Math.min(W.maxTokens??1/0,G(V))}:{}};return{plain:W,cut:J9($,Y),maxSummaryTokens:J}}function R8($,Q){if(Q.triggerTokens===!1)return;let Z=c(Q.triggerTokens||void 0);if(Z)return Z;if(c($.maxTokens)||c($.maxBytes))return;return LZ}async function NZ($){let{history:Q,window:Z,compact:J}=$,{plain:G,cut:W,maxSummaryTokens:V}=OZ(Q,Z,J);if(W.omittedTurns===0)return W.messages;let Y=`${Q[W.start].id}:${W.start}`,H=$.memo?.get(Y);if(H===void 0){try{H=await k8($,W.start,V)}catch(D){if($.signal.aborted)throw D;H=null}if(!$.signal.aborted)$.memo?.set(Y,H)}if(!H)return J9(Q,G).messages;let X=Q.length-W.start,K=W.messages.slice(0,W.messages.length-X),B=W.messages.slice(W.messages.length-X),z=Q[W.start];return[...K,{id:`summary_${z.id}`,role:"user",content:[{type:"text",text:`${PZ}
3
3
  ${H.text}`}],createdAt:z.createdAt},...B]}var zZ="\x00next-turn";function _Z($){let Q=j8($).finally(()=>i9.delete(Q));return i9.add(Q),Q}var i9=new Set;async function j8($){try{let Q={id:zZ,role:"user",content:[{type:"text",text:""}],createdAt:new Date().toISOString()},Z=[...$.history,Q],J=[...$.stored,Q],{cut:G,maxSummaryTokens:W}=OZ(Z,$.window,$.compact);if(G.omittedTurns===0||Z[G.start].id===zZ)return;let V=qZ({...$,history:Z,stored:J},G.start);if((await o9($.store,$.threadId)).some(V.matches))return;await MZ(V,{...$,history:Z,stored:J},G.start,W).promise}catch{}}async function S8(){while(R9.size>0||i9.size>0)await Promise.allSettled([...i9,...[...R9.values()].map(($)=>$.promise)])}var R9=new Map,i=new Map,A8=1000;function T8($,Q){i.set($,M(i.get($)??R(),Q));while(i.size>A8)i.delete(i.keys().next().value)}function BZ($,Q){let Z=i.get($);if(!Z)return;i.delete($),Q(Z)}function qZ($,Q){let Z=$.history[Q].id,J=h8($.stored,Q),G=J[Q];return{key:`${$.threadId}\x00${Z}\x00${G}`,fingerprints:J,matches:(W)=>W?.cutMessageId===Z&&W.fingerprint===G}}async function k8($,Q,Z){let J=qZ($,Q),G=(await o9($.store,$.threadId)).find(J.matches);if(G)return BZ(J.key,$.onUsage),G;let W=MZ(J,$,Q,Z);if(W.owed)$.onUsage(W.owed),W.owed=void 0;W.payers.push($.onUsage);try{return await E8(W.promise,$.signal)}finally{W.payers.splice(W.payers.indexOf($.onUsage),1),BZ(J.key,$.onUsage)}}function MZ($,Q,Z,J){let G=R9.get($.key);if(G)return G;let W={promise:void 0,payers:[],owed:void 0},V=(Y)=>{let H=W.payers[0];if(H)H(Y);else W.owed=M(W.owed??R(),Y)};return W.promise=(async()=>{let{store:Y,threadId:H}=Q,X=c(Q.compact.lockWaitMs)??_8,K=null;if(Y.lockSummary){try{K=await Y.lockSummary(H,Q.history[Z].id,X+60000)}catch{K=null}if(!K)return I8(Q,$.matches,X)}try{let B=await o9(Y,H),z=B.find($.matches);if(z)return z;return await w8(Q,B,$.fingerprints,Z,J,V)}finally{if(K)await K().catch(()=>{})}})().catch(()=>null).finally(()=>{if(R9.delete($.key),W.owed)T8($.key,W.owed);W.owed=void 0}),R9.set($.key,W),W}function E8($,Q){if(Q.aborted)return Promise.reject(Q.reason);return new Promise((Z,J)=>{let G=()=>J(Q.reason);Q.addEventListener("abort",G,{once:!0}),$.then((W)=>{Q.removeEventListener("abort",G),Z(W)},(W)=>{Q.removeEventListener("abort",G),J(W)})})}async function o9($,Q){try{let Z=await $.loadSummaries(Q);return Array.isArray(Z)?Z.filter(x8):[]}catch{return[]}}function x8($){let Q=$;return!!Q&&typeof Q.cutMessageId==="string"&&typeof Q.text==="string"&&typeof Q.fingerprint==="string"}async function I8($,Q,Z){let J=Date.now()+Z;while(Date.now()<J){await new Promise((W)=>setTimeout(W,250));let G=(await o9($.store,$.threadId)).find(Q);if(G)return G}return null}async function w8($,Q,Z,J,G,W){let{history:V,compact:Y}=$,H=q9(V),X=H.indexOf(J),K=new Map(H.map((N)=>[V[N].id,N])),B,z=0;for(let N of Q){let A=K.get(N.cutMessageId);if(A===void 0||A>=J||A<=z)continue;if(N.fingerprint!==Z[A])continue;B=N,z=A}let D=(c(Y.chunkTokens)??N8)*w$,L=b8(V,H,z,J,D),F=G*w$,U=`${Y.instructions??UZ} Keep the summary under about ${Math.round(G*0.75)} words.`,P=B?.text??"",q=R();for(let N of L){let A=await U$({provider:Y.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 qQ{injectedClient;prefix;constructor($={}){this.injectedClient=$
102
102
 
103
103
  `)||void 0,q=await this.context($,{body:H}),_=await this.attachmentsFor($,J,{body:H});if(K?.cancelled)return f6();let N=J?new jQ(this.store,J,F,(k)=>this.reportHookFailure(k)):null,A=`run_${crypto.randomUUID()}`,E={req:$,runId:A,threadId:J},x={id:null,notified:Promise.resolve()},O=this.agent.stream({runId:A,messages:F,turn:W,threadId:J,...N?{onMessage:(k)=>N.finish(k)}:{},onTurn:(k)=>{if(x.id!==null)return;x.id=k.id;let a=N?N.settled():Promise.resolve();x.notified=a.then(()=>this.safely(()=>this.onMessage(k,E)))},instructions:P,context:q,attachments:_,body:H,redactError:(k,a)=>this.redactError(k,a,E),nonces:this.nonces,receipts:this.receipts,subject:X,...J?{jobs:{owner:X}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...J&&CZ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==EQ.prototype.prepareStep?{prepareStep:(k)=>this.prepareStep(k,E)}:{}}),C=this.liveRuns.register(O,{threadId:J,owner:X,clientRunId:Y,onEvent:(k)=>this.dispatchEvent(k,E),onInternalError:(k)=>this.reportHookFailure(k),maxRunDurationMs:this.agent.maxRunDurationMs});if(B=O,N)this.follow(O,N);let{stored:T,hooks:j}=this.persistRun(O,E,C,N,x);return T6.set(O,T),$.ctx?.()?.waitUntil(j),O.toResponse()};try{await this.authorizeRequest($,{route:"stream",threadId:J,body:H});let F=await this.foreignFile([...W?.files??[],...J?[]:U1(Z.messages)],X);if(F)return F;if(K?.cancelled)return f6();let U=await this.runLimitKey($,{owner:X,threadId:J}),P=U===null?p6:Z1(this.liveRuns).take(U,J?`thread:${J}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return kQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return J?await this.withThread(J,X,D):await D()}finally{let q=B;if(q)q.result().then(P,P);else P()}}finally{if(K&&z$.get(Y)===K)z$.delete(Y)}}async withThread($,Q,Z){let J=K$.get($)??Promise.resolve(),G,W=new Promise((Y)=>{G=Y}),V=J.then(()=>W);K$.set($,V),await J;try{let Y=await this.liveRuns.find({threadId:$});if(Y&&this.liveRuns.isRunning(Y.runId)&&!this.liveRuns.mayAccess(Y.runId,Q))return D$();let H=Y?this.liveRuns.get(Y.runId):null;if(H)H.stop({reason:"superseded by a later turn on this thread"}),await T6.get(H);return await Z()}finally{if(G(),K$.get($)===V)K$.delete($)}}async attach($=new k9){let Q=await SQ($,k6);if(Q.error)return B$(Q);let Z=Q.body,J=typeof Z.threadId==="string"?Z.threadId:D1($,"threadId");if(!J)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:J});let G=await this.liveRuns.find({threadId:J});if(G&&!this.liveRuns.mayAccess(G.runId,await this.runOwner($)))return D$();if(!G)return f(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`});let W=typeof Z.runId==="string"?Z.runId:void 0,V=W&&W!==G.runId?void 0:B1($,Z);try{return c6(this.liveRuns.replay(G.runId,V))}catch(Y){if(Y instanceof H9)return f(410,{code:Y.code,message:Y.message,oldestSeq:Y.oldest});if(Y instanceof T9)return f(404,{code:Y.code,message:Y.message});throw Y}}async stop($=new k9){let Q=await SQ($,k6);if(Q.error)return B$(Q);let Z=Q.body;await this.authorizeRequest($,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let J=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 V=z$.get(Z.clientRunId);if(V){if(V.owner!==null&&V.owner!==J)return D$();return V.cancelled=!0,{stopped:!0}}}}if(!G&&typeof Z.threadId==="string")G=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let W=G?this.liveRuns.get(G):null;if(!W)return{stopped:!1};if(!this.liveRuns.mayAccess(W.runId,J))return D$();return W.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope($,Q,Z){let J=$.ctx()?.user,G=J?.id??J?.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 J=await this.attachmentScope($,Q,Z);if(!J)return null;return new p(this.attachments,this.attachmentStorage,J)}async upload($=new k9){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 J=Z instanceof File&&Z.name?Z.name:"upload",G=Z.type||"application/octet-stream",W=G1(Q.get("body")),V=Q.get("threadId");await this.authorizeRequest($,{route:"upload",threadId:typeof V==="string"&&V.length>0?V:void 0,body:W});let Y=V1(await this.attachmentLimits($),Z,J,G);if(Y)throw new i6(Y.code,Y.message);let H=typeof V==="string"&&V.length>0&&await this.store.loadThread(V)!==null?V:void 0,X=await this.runOwner($),K=(_)=>this.fileOwners.record(_,{owner:X,name:J,mimeType:G,size:Z.size,createdAt:new Date().toISOString()}),B=await this.attachmentDestination(Z,$),z=P1(B,Q.get("destination")),D=await this.attachmentScope($,H,{body:W}),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()`.');C1()}if(z==="provider"||!D){let _=await x6(this.agent.provider,Z);await K(_);let N={fileId:_,name:J,mimeType:G,size:Z.size,destination:"provider"};if(L)N.downgraded="no_scope";return N}let F=C$(),U=await this.attachmentStorage.put({name:O$(F,J),body:Z,contentType:G}),P=z==="both"?await x6(this.agent.provider,Z):void 0;if(P)await K(P);let q={id:F,scopeKey:D.key,fileId:P,objectName:U,name:J,mimeType:G,size:Z.size,createdAt:new Date().toISOString(),destination:z};return await this.attachments.put(D,q),{fileId:P,attachmentId:F,name:J,mimeType:G,size:Z.size,destination:z}}async foreignFile($,Q){let Z=new Set($.map((J)=>J.fileId).filter((J)=>typeof J==="string"));for(let J of Z){let G=await this.fileOwners.get(J);if(G?G.owner!==null&&G.owner!==Q:this.requireKnownFiles)return L1()}return null}onMessage($,Q){}onToolCall($,Q){}onAwaitingInput($,Q){}redactError($,Q,Z){return O9($,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(m6($.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 J=(H)=>this.isRunLive(H,$),G=await R6(Q,J),W=G.messages,V=[],Y=new Map(G.settled.map((H)=>[H.id,H]));if(q1(W)||Z)try{let H=await S6(W,{threadId:$,store:y.store,isRunLive:J,outputSchemaFor:(X)=>this.toolOutputSchema(X),scan:this.jobsBlockMax()});W=H.messages,V=H.jobs;for(let X of H.settled)Y.set(X.id,X);if(Z&&H.orphans.length>0){await A6(y.store,H.orphans,(K)=>this.reportHookFailure(K));let X=new Set(H.orphans.map((K)=>K.id));V=V.map((K)=>X.has(K.id)?{...K,orphaned:!0}:K)}}catch(H){this.reportHookFailure(H)}if(Z&&Y.size>0)try{await this.store.appendMessages($,[...Y.values()])}catch(H){this.reportHookFailure(H)}return{messages:W,jobs:V}}jobsBlockMax(){let $=this.agent.jobs?.contextBlock;if($===!1)return 0;return $?.max??r9}jobsBlock($){return uZ($,this.jobsBlockMax())}toolOutputSchema($){let Q=(Z)=>{for(let J of Z){let G=J;if(Array.isArray(G.tools)){let W=Q(G.tools);if(W)return W}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,J=null,G={id:null,notified:Promise.resolve()}){let W=Promise.resolve(),V=(async()=>{let H;try{H=await $.result()}catch(K){J?.close(),await J?.settled(),W=G.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:K instanceof Error?K.message:String(K),retryable:!1},Q)));return}let X=H.messages;if(J?.close(X),await J?.settled(),Q.threadId&&X.length>0)try{await this.store.appendMessages(Q.threadId,X)}catch(K){this.reportHookFailure(K)}W=this.notifyRun(H,X,Q,G)})(),Y=V.then(()=>N1(Promise.all([W,Z]).then(()=>{}),this.hookHoldMs));return{stored:V,hooks:Y}}async notifyRun($,Q,Z,J){await J.notified;for(let G of Q){if(G.id===J.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 AQ=["turn","clientRunId","threadId","messages","regenerate"],J1=["text","files","toolResults"];function d6($,Q=o6($)?AQ:[...AQ,...J1]){let Z={};for(let[J,G]of Object.entries($)){if(Q.includes(J))continue;Object.defineProperty(Z,J,{value:G,writable:!0,enumerable:!0,configurable:!0})}return Z}function G1($){if($===null)return{};let Q;if(typeof $==="string")try{Q=JSON.parse($)}catch{throw new TQ("The upload's `body` field is not valid JSON.")}if(Q===null||typeof Q!=="object"||Array.isArray(Q))throw new TQ("The upload's `body` field must be a JSON object.");return d6(Q,AQ)}class TQ extends F${constructor($){super($);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:$}}},view:{}}}}async function x6($,Q){try{return await $.upload(Q)}catch(Z){if(Z instanceof g&&W1.has(Z.status))throw new n6(I(Z).message);throw Z}}var W1=new Set([400,413,415,422]);class i6 extends F${constructor($,Q){super(Q);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}function V1($,Q,Z,J){if(!$)return null;let{maxBytes:G,accept:W}=$;if(typeof G==="number"&&Q.size>G)return{code:"file_too_large",message:`${JSON.stringify(Z)} is ${I6(Q.size)}; the limit is ${I6(G)}.`};if(W&&W.length>0&&!W.some((V)=>X1(V,Z,J)))return{code:"unsupported_file_type",message:`${JSON.stringify(Z)} is not a type this chat accepts. Accepted: ${W.join(", ")}.`};return null}function X1($,Q,Z){let J=$.trim().toLowerCase();if(!J)return!1;if(J.startsWith("."))return Q.toLowerCase().endsWith(J);let G=Z.toLowerCase().split(";")[0].trim();if(J.endsWith("/*"))return G.startsWith(J.slice(0,-1));return G===J}function I6($){if($<1024)return`${$} B`;let Q=["KB","MB","GB"],Z=$/1024,J=0;while(Z>=1024&&J<Q.length-1)Z/=1024,J++;return`${Math.round(Z*10)/10} ${Q[J]}`}class n6 extends F${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 SQ($,Q){let Z=$?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!Y1(Z.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let J=Number(Z.headers.get("Content-Length"));if(Number.isFinite(J)&&J>Q)return w6(Q);let G;try{let V=await H1(Z,Q);if(V===null)return w6(Q);G=V}catch{return{body:{},error:"The request body could not be read."}}if(!G.trim())return{body:{}};let W;try{W=JSON.parse(G)}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 Y1($){return u6($)==="application/json"}async function H1($,Q){if(!Number.isFinite(Q)||!$.body)return await $.text();let Z=$.body.getReader(),J=[],G=0;for(;;){let{done:Y,value:H}=await Z.read();if(Y)break;if(G+=H.byteLength,G>Q)return await Z.cancel().catch(p6),null;J.push(H)}let W=new Uint8Array(G),V=0;for(let Y of J)W.set(Y,V),V+=Y.byteLength;return new TextDecoder().decode(W)}function w6($){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${$} bytes).`}}function kQ($,Q,Z){return f($,{...L$(g6($),Z,$),code:Q})}function B$($){if($.status===413)return kQ(413,$.code??"body_too_large",$.error??"");return f($.status??400,{code:$.code??"invalid_request",message:$.error})}function o6($){return Boolean($.turn)&&typeof $.turn==="object"}function K1($){let Q=o6($)?$.turn:$,Z={};if(typeof Q.text==="string")Z.text=Q.text;if(Array.isArray(Q.files)){let J=z1(Q.files);if(typeof J==="string")return{error:J};Z.files=J}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:J}=Q;if(typeof J!=="string")return{error:"turn.localId must be a string."};if(J.length>b6)return{error:`turn.localId is longer than ${b6} characters.`};Z.localId=J}return{turn:Z}}var b6=200;function z1($){let Q=[];for(let[Z,J]of $.entries()){let G=`turn.files[${Z}]`;if(!J||typeof J!=="object"||Array.isArray(J))return`${G} must be an object.`;let W={};for(let K of["fileId","attachmentId","name","mimeType"]){let B=J[K];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${G}.${K} must be a string.`;W[K]=B}let{fileId:V,attachmentId:Y,name:H,mimeType:X}=W;if(V?.startsWith(h))return`${G}.fileId holds a gemi attachment id (${V}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(Y!==void 0&&!Y.startsWith(h))return`${G}.attachmentId is not a gemi attachment id: it must start with "${h}".`;if(!V&&!Y)return`${G} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;Q.push({...V?{fileId:V}:{},...Y?{attachmentId:Y}:{},...H!==void 0?{name:H}:{},...X!==void 0?{mimeType:X}:{}})}return Q}function B1($,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 J=Math.floor(Q.cursor);if(J>=0)return J+1;return}let Z=$?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let J=Number.parseInt(Z,10);if(Number.isFinite(J))return Math.max(0,J+1)}return}function D1($,Q){let Z=$?.search?.get(Q);return typeof Z==="string"?Z:void 0}function F1($){let Q=d($);for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.role!=="user"||Q.has(J.id))continue;let G="",W=[];for(let V of J.content){if(V.type==="text")G+=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(!G&&W.length===0)continue;return{index:Z,turn:{...G?{text:G}:{},...W.length>0?{files:W}:{}}}}return null}function f6(){return f(409,{code:"stopped",message:"The turn was stopped before it started."})}function D$(){return f(403,L$("permission","This run belongs to someone else.",403))}function L1(){return f(403,L$("permission","A file in this turn was uploaded by someone else.",403))}function U1($){if(!Array.isArray($))return[];let Q=[];for(let Z of $){let J=Z?.content;if(!Array.isArray(J))continue;for(let G of J)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 P1($,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 v6=!1;function C1(){if(v6)return;v6=!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 O1=2147483647;function N1($,Q){let Z=$.then(()=>{},()=>{});if(!(Q<=O1))return Z;let J,G=new Promise((W)=>{J=setTimeout(W,Q)});return Promise.race([Z,G]).finally(()=>clearTimeout(J))}var h6=!1;function _1($){if(h6||Bun.env.NODE_ENV!=="production")return;if(!($ instanceof N9))return;h6=!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 q1($){return $.some((Q)=>Q.content.some((Z)=>Z.type==="tool-result"&&Z.status==="running"))}export{J9 as windowMessages,q9 as turnStarts,a8 as toAgentTools,z9 as supportsStrict,U8 as splitTurns,S8 as settleSummaries,d9 as s,O9 as redactError,YZ as messageSize,CQ as liveRuns,n9 as keepSummary,d as injectedMessageIds,U$ as generate,v0 as evalChain,f$ as defaultSummaryStore,Z9 as defaultNonceStore,OQ as defaultFileOwners,r as defaultAttachmentStore,MQ as defaultAgentStore,G9 as ToolNamespace,S as ToolError,c$ as Skill,p as ScopedAttachments,j9 as SKILLS_NAMESPACE,qQ as RedisReceiptStore,R$ as RedisNonceStore,n as PendingEscalation,DQ as OpenAIProvider,$Q as OpenAIImageProvider,b$ as MemorySummaryStore,_Q as MemoryReceiptStore,N9 as MemoryNonceStore,X$ as MemoryLiveRuns,Y$ as MemoryFileOwners,V$ as MemoryCircuitStore,v9 as MemoryAttachmentStore,H$ as MemoryAgentStore,P9 as MemoryAgentJobStore,T9 as LiveRunNotFoundError,C9 as JobsRequireThreadError,g9 as JobHandle,M1 as JSONSchemaError,u as InvalidAttachmentScopeError,J$ as ImageRequestError,G$ as ImageProvider,a$ as ImageModel,H9 as FrameCursorEvictedError,A9 as FallbackProvider,s$ as DatabaseAgentJobStore,FZ as DEFAULT_MAX_SUMMARY_TOKENS,l$ as DEFAULT_MAX_RUN_DURATION_MS,q$ as DEFAULT_JOB_DEADLINE_MS,r9 as DEFAULT_JOBS_CONTEXT_MAX,HZ as DEFAULT_CONTEXT_WINDOW_STEP,KZ as DEFAULT_CONTEXT_WINDOW_NOTE,LZ as DEFAULT_COMPACT_TRIGGER_TOKENS,UZ as DEFAULT_COMPACT_INSTRUCTIONS,PZ as COMPACT_SUMMARY_HEADER,FQ as AzureOpenAIProvider,QQ as AzureOpenAIImageProvider,U9 as AttachmentNotFoundError,o as AgentTool,L9 as AgentRunError,Y9 as AgentProvider,y as AgentJobs,i$ as AgentJobDeadlineSweep,M$ as AgentJob,EQ as AgentController,d$ as Agent};
104
104
 
105
- //# debugId=4886125D4947C82664756E2164756E21
105
+ //# debugId=6DA41F2D207E442864756E2164756E21