gemi 0.91.1 → 0.92.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.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/chunk-00cwycyq.js +5 -0
- package/dist/{chunk-ddbbxg9m.js.map → chunk-00cwycyq.js.map} +1 -1
- package/dist/{chunk-k5j65f2c.js → chunk-165mrqab.js} +2 -2
- package/dist/{chunk-k5j65f2c.js.map → chunk-165mrqab.js.map} +1 -1
- package/dist/{chunk-gzfat1x1.js → chunk-2caeg5jf.js} +2 -2
- package/dist/{chunk-gzfat1x1.js.map → chunk-2caeg5jf.js.map} +1 -1
- package/dist/{chunk-6y62ccam.js → chunk-30k7198s.js} +3 -3
- package/dist/{chunk-6y62ccam.js.map → chunk-30k7198s.js.map} +1 -1
- package/dist/{chunk-kmebynhc.js → chunk-4cjfngfk.js} +2 -2
- package/dist/{chunk-kmebynhc.js.map → chunk-4cjfngfk.js.map} +1 -1
- package/dist/{chunk-j2402q2z.js → chunk-4cqt4y7f.js} +2 -2
- package/dist/{chunk-j2402q2z.js.map → chunk-4cqt4y7f.js.map} +1 -1
- package/dist/{chunk-9kfnd4bf.js → chunk-52bk916h.js} +1 -1
- package/dist/{chunk-49v5xq8q.js → chunk-677yj1rx.js} +2 -2
- package/dist/{chunk-49v5xq8q.js.map → chunk-677yj1rx.js.map} +1 -1
- package/dist/{chunk-6tt3ynm7.js → chunk-6jw956j2.js} +2 -2
- package/dist/{chunk-6tt3ynm7.js.map → chunk-6jw956j2.js.map} +1 -1
- package/dist/{chunk-3z8fkczm.js → chunk-73drae3k.js} +2 -2
- package/dist/{chunk-3z8fkczm.js.map → chunk-73drae3k.js.map} +1 -1
- package/dist/{chunk-b1wjymn0.js → chunk-7dp5fv1e.js} +2 -2
- package/dist/{chunk-b1wjymn0.js.map → chunk-7dp5fv1e.js.map} +1 -1
- package/dist/{chunk-fj7yk6a7.js → chunk-7hvnms5x.js} +3 -3
- package/dist/{chunk-fj7yk6a7.js.map → chunk-7hvnms5x.js.map} +1 -1
- package/dist/{chunk-01n76z2m.js → chunk-7v9919g5.js} +2 -2
- package/dist/{chunk-01n76z2m.js.map → chunk-7v9919g5.js.map} +1 -1
- package/dist/{chunk-7k7dfy74.js → chunk-93c5cx5a.js} +2 -2
- package/dist/{chunk-7k7dfy74.js.map → chunk-93c5cx5a.js.map} +1 -1
- package/dist/{chunk-a9a3tbyr.js → chunk-98jbvwpf.js} +2 -2
- package/dist/{chunk-a9a3tbyr.js.map → chunk-98jbvwpf.js.map} +1 -1
- package/dist/{chunk-7ct4y1zh.js → chunk-9de5kyz3.js} +3 -3
- package/dist/{chunk-7ct4y1zh.js.map → chunk-9de5kyz3.js.map} +1 -1
- package/dist/{chunk-ngrr6wvw.js → chunk-9k9znvhp.js} +2 -2
- package/dist/{chunk-ngrr6wvw.js.map → chunk-9k9znvhp.js.map} +1 -1
- package/dist/{chunk-kdpc26j2.js → chunk-bsgjnb30.js} +1 -1
- package/dist/{chunk-dedazpms.js → chunk-cm9am4b8.js} +1 -1
- package/dist/{chunk-66g9yytx.js → chunk-cnd7s0vv.js} +3 -3
- package/dist/{chunk-66g9yytx.js.map → chunk-cnd7s0vv.js.map} +1 -1
- package/dist/{chunk-vqhcztw0.js → chunk-d5nx54s0.js} +2 -2
- package/dist/{chunk-vqhcztw0.js.map → chunk-d5nx54s0.js.map} +1 -1
- package/dist/{chunk-kk5x6grc.js → chunk-df0105td.js} +2 -2
- package/dist/{chunk-kk5x6grc.js.map → chunk-df0105td.js.map} +1 -1
- package/dist/{chunk-3470jpmr.js → chunk-dpak844f.js} +2 -2
- package/dist/{chunk-3470jpmr.js.map → chunk-dpak844f.js.map} +1 -1
- package/dist/{chunk-8acf5bf3.js → chunk-dt38t11e.js} +2 -2
- package/dist/{chunk-8acf5bf3.js.map → chunk-dt38t11e.js.map} +1 -1
- package/dist/{chunk-dyq9gcwa.js → chunk-dxcg3vg7.js} +2 -2
- package/dist/{chunk-dyq9gcwa.js.map → chunk-dxcg3vg7.js.map} +1 -1
- package/dist/{chunk-mn5xnk02.js → chunk-ejebep30.js} +2 -2
- package/dist/{chunk-mn5xnk02.js.map → chunk-ejebep30.js.map} +1 -1
- package/dist/{chunk-n4mfv24c.js → chunk-ev5nyhp4.js} +2 -2
- package/dist/{chunk-n4mfv24c.js.map → chunk-ev5nyhp4.js.map} +1 -1
- package/dist/{chunk-f2vjbxh6.js → chunk-ev6j9291.js} +2 -2
- package/dist/{chunk-f2vjbxh6.js.map → chunk-ev6j9291.js.map} +1 -1
- package/dist/{chunk-d476f9f6.js → chunk-f3fb0x49.js} +2 -2
- package/dist/{chunk-d476f9f6.js.map → chunk-f3fb0x49.js.map} +1 -1
- package/dist/{chunk-bj6gsxkv.js → chunk-fwrefjt0.js} +2 -2
- package/dist/{chunk-bj6gsxkv.js.map → chunk-fwrefjt0.js.map} +1 -1
- package/dist/{chunk-3nh3h2df.js → chunk-g582bb47.js} +2 -2
- package/dist/{chunk-3nh3h2df.js.map → chunk-g582bb47.js.map} +1 -1
- package/dist/{chunk-ez0c0mpt.js → chunk-geg85jwj.js} +2 -2
- package/dist/{chunk-ez0c0mpt.js.map → chunk-geg85jwj.js.map} +1 -1
- package/dist/chunk-hg51829v.js +17 -0
- package/dist/{chunk-087r45fw.js.map → chunk-hg51829v.js.map} +4 -4
- package/dist/{chunk-e70ggm2m.js → chunk-hj4wjv7v.js} +2 -2
- package/dist/{chunk-e70ggm2m.js.map → chunk-hj4wjv7v.js.map} +1 -1
- package/dist/{chunk-5rpeez39.js → chunk-hzd58xtv.js} +3 -3
- package/dist/{chunk-5rpeez39.js.map → chunk-hzd58xtv.js.map} +1 -1
- package/dist/{chunk-w9j1kxmc.js → chunk-jrpn4k18.js} +2 -2
- package/dist/{chunk-fc28h7g2.js.map → chunk-jrpn4k18.js.map} +1 -1
- package/dist/{chunk-r6jytsz3.js → chunk-jth8zxxk.js} +2 -2
- package/dist/{chunk-r6jytsz3.js.map → chunk-jth8zxxk.js.map} +1 -1
- package/dist/{chunk-t6hma13w.js → chunk-k13q1tvj.js} +3 -3
- package/dist/{chunk-t6hma13w.js.map → chunk-k13q1tvj.js.map} +1 -1
- package/dist/{chunk-sh1cfx9j.js → chunk-mfncnxva.js} +3 -3
- package/dist/{chunk-sh1cfx9j.js.map → chunk-mfncnxva.js.map} +1 -1
- package/dist/{chunk-ttckhvew.js → chunk-mqa6b0sx.js} +2 -2
- package/dist/{chunk-ttckhvew.js.map → chunk-mqa6b0sx.js.map} +1 -1
- package/dist/{chunk-6ffpdkjw.js → chunk-nhnv4nrs.js} +3 -3
- package/dist/{chunk-6ffpdkjw.js.map → chunk-nhnv4nrs.js.map} +1 -1
- package/dist/{chunk-d33qcg5b.js → chunk-nxwfjn97.js} +2 -2
- package/dist/{chunk-d33qcg5b.js.map → chunk-nxwfjn97.js.map} +1 -1
- package/dist/{chunk-2mrgrjy6.js → chunk-pd6qazcx.js} +2 -2
- package/dist/{chunk-2mrgrjy6.js.map → chunk-pd6qazcx.js.map} +1 -1
- package/dist/{chunk-q7gkfkbz.js → chunk-pnf2vn6y.js} +2 -2
- package/dist/{chunk-q7gkfkbz.js.map → chunk-pnf2vn6y.js.map} +1 -1
- package/dist/{chunk-17nh5gfm.js → chunk-pwchwgkc.js} +2 -2
- package/dist/{chunk-17nh5gfm.js.map → chunk-pwchwgkc.js.map} +1 -1
- package/dist/{chunk-ed346kf4.js → chunk-ra0ct4ad.js} +2 -2
- package/dist/{chunk-ed346kf4.js.map → chunk-ra0ct4ad.js.map} +1 -1
- package/dist/{chunk-p3n8jjjf.js → chunk-rzh6nq2x.js} +3 -3
- package/dist/{chunk-p3n8jjjf.js.map → chunk-rzh6nq2x.js.map} +1 -1
- package/dist/{chunk-cv2sargd.js → chunk-s74kx019.js} +2 -2
- package/dist/{chunk-cv2sargd.js.map → chunk-s74kx019.js.map} +1 -1
- package/dist/{chunk-araqww9d.js → chunk-sa79bwd3.js} +2 -2
- package/dist/{chunk-araqww9d.js.map → chunk-sa79bwd3.js.map} +1 -1
- package/dist/{chunk-n2rq7wp8.js → chunk-t8xxsah1.js} +2 -2
- package/dist/{chunk-n2rq7wp8.js.map → chunk-t8xxsah1.js.map} +1 -1
- package/dist/{chunk-6p62z1h3.js → chunk-t91h0yek.js} +2 -2
- package/dist/{chunk-6p62z1h3.js.map → chunk-t91h0yek.js.map} +1 -1
- package/dist/{chunk-4czqjqs7.js → chunk-tj684a37.js} +2 -2
- package/dist/{chunk-4czqjqs7.js.map → chunk-tj684a37.js.map} +1 -1
- package/dist/{chunk-2dfar4d1.js → chunk-tx7hd2ec.js} +2 -2
- package/dist/{chunk-2dfar4d1.js.map → chunk-tx7hd2ec.js.map} +1 -1
- package/dist/{chunk-j0qwgrp6.js → chunk-v6kef2b8.js} +4 -4
- package/dist/{chunk-j0qwgrp6.js.map → chunk-v6kef2b8.js.map} +1 -1
- package/dist/{chunk-xqyx8kzr.js → chunk-v6vsjdp7.js} +2 -2
- package/dist/{chunk-xqyx8kzr.js.map → chunk-v6vsjdp7.js.map} +1 -1
- package/dist/{chunk-q18fb0cr.js → chunk-w46dtkdh.js} +2 -2
- package/dist/{chunk-q18fb0cr.js.map → chunk-w46dtkdh.js.map} +1 -1
- package/dist/{chunk-6mdw41s5.js → chunk-x6vkmjb8.js} +2 -2
- package/dist/{chunk-6mdw41s5.js.map → chunk-x6vkmjb8.js.map} +1 -1
- package/dist/{chunk-5c7nyk5k.js → chunk-y1z1bq77.js} +2 -2
- package/dist/{chunk-5c7nyk5k.js.map → chunk-y1z1bq77.js.map} +1 -1
- package/dist/{chunk-hc1mcgs9.js → chunk-ykxvpzzr.js} +2 -2
- package/dist/{chunk-hc1mcgs9.js.map → chunk-ykxvpzzr.js.map} +1 -1
- package/dist/{chunk-x97zectc.js → chunk-ynjtm50m.js} +2 -2
- package/dist/{chunk-x97zectc.js.map → chunk-ynjtm50m.js.map} +1 -1
- package/dist/{chunk-w4qek53d.js → chunk-z3y1pa0y.js} +2 -2
- package/dist/{chunk-w4qek53d.js.map → chunk-z3y1pa0y.js.map} +1 -1
- package/dist/{chunk-fc28h7g2.js → chunk-z77p625q.js} +2 -2
- package/dist/{chunk-w9j1kxmc.js.map → chunk-z77p625q.js.map} +1 -1
- package/dist/{chunk-hx1jg944.js → chunk-z89v7fm0.js} +2 -2
- package/dist/{chunk-hx1jg944.js.map → chunk-z89v7fm0.js.map} +1 -1
- package/dist/client/Mutation.d.ts +12 -3
- package/dist/client/Mutation.d.ts.map +1 -1
- package/dist/client/MutationError.d.ts +32 -2
- package/dist/client/MutationError.d.ts.map +1 -1
- package/dist/client/auth/useForgotPassword.d.ts +1 -1
- package/dist/client/auth/useResetPassword.d.ts +1 -1
- package/dist/client/auth/useSignIn.d.ts +1 -1
- package/dist/client/auth/useSignOut.d.ts +1 -1
- package/dist/client/auth/useSignUp.d.ts +1 -1
- package/dist/client/index.d.ts +2 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +19 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/useMutation.d.ts +38 -26
- package/dist/client/useMutation.d.ts.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/ApiRouter.d.ts +10 -4
- package/dist/http/ApiRouter.d.ts.map +1 -1
- package/dist/http/HttpResponse.d.ts +85 -10
- package/dist/http/HttpResponse.d.ts.map +1 -1
- package/dist/http/index.d.ts +1 -1
- package/dist/http/index.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/package.json +1 -1
- package/skills/gemi-react-best-practices/rules/controller-throw-framework-errors.md +9 -0
- package/dist/chunk-087r45fw.js +0 -17
- package/dist/chunk-ddbbxg9m.js +0 -5
- /package/dist/{chunk-9kfnd4bf.js.map → chunk-52bk916h.js.map} +0 -0
- /package/dist/{chunk-kdpc26j2.js.map → chunk-bsgjnb30.js.map} +0 -0
- /package/dist/{chunk-dedazpms.js.map → chunk-cm9am4b8.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ab as f9,Bb as F$,Cb as C$,Db as Y3,zb as O}from"../chunk-wc46df4w.js";import{$e as Y6,Ie as X3,Le as V3,_e as H6,af as n,bf as WQ,pf as H3,rf as t,sf as gQ}from"../chunk-7ct4y1zh.js";import{tf as G3,vf as fQ,wf as hQ}from"../chunk-xqyx8kzr.js";import{Af as NQ}from"../chunk-17nh5gfm.js";import{xg as y9}from"../chunk-sh1cfx9j.js";import"../chunk-dyq9gcwa.js";import"../chunk-ed346kf4.js";import"../chunk-kmebynhc.js";import"../chunk-fc28h7g2.js";class I extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${P3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class GQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function P3(Q){let $=h9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function h9(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;if(typeof J.message!=="string"&&typeof J.code!=="string"&&typeof J.type!=="string")return null;let W=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:W,param:J.param}}function T(Q){if(!Q||typeof Q!=="object")return{};let{status:$,requestId:Z}=Q;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function _(Q){if(Q instanceof GQ)return{code:"provider_error",message:Q.message,retryable:!0};if(_3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof I)return j3(Q.status,h9(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function j3(Q,$,Z){let J=$?.message??Z,W=($?.code??"").toLowerCase(),X=($?.type??"").toLowerCase(),G=`${W} ${X} ${J}`.toLowerCase();if(Q===429){let Y=W==="insufficient_quota"||G.includes("quota");return{code:"rate_limited",message:J,retryable:!Y}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(O3(G))return{code:"context_length_exceeded",message:J,retryable:!1};if(N3(G))return{code:"content_filtered",message:J,retryable:!1};if($?.param?.startsWith("tools")||G.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function O3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function N3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function _3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class q extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function f(Q,$){if($.aborted)return Promise.reject(new q);return new Promise((Z,J)=>{let W=()=>J(new q);$.addEventListener("abort",W,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",W))})}function v(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function E(Q,$){if(!$)return Q;let Z={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)Z.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)Z.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);if($.imageInputTokens!==void 0||Q.imageInputTokens!==void 0)Z.imageInputTokens=(Q.imageInputTokens??0)+($.imageInputTokens??0);if($.imageOutputTokens!==void 0||Q.imageOutputTokens!==void 0)Z.imageOutputTokens=(Q.imageOutputTokens??0)+($.imageOutputTokens??0);return Z}function VQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,J=!1;for(let G of Q){if(Z){if(J)J=!1;else if(G==="\\")J=!0;else if(G==='"')Z=!1;continue}if(G==='"')Z=!0;else if(G==="{")$.push("}");else if(G==="[")$.push("]");else if(G==="}"||G==="]")$.pop()}let W=Q;if(Z)W+='"';W=W.replace(/[,:]\s*$/,"");let X=$.reverse().join("");try{return JSON.parse(W+X)}catch{try{return JSON.parse(W.replace(/,?\s*"[^"]*"\s*$/,"")+X)}catch{return{}}}}function HQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:n(Q)}}function YQ(Q,$){let Z=Q.safeParse(VQ($));if(Z.ok===!0)return{ok:!0,value:Z.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Z.errors.join(", ")}`,retryable:!0}}}function KQ(Q){if(Q.length>0)Q[0];return Q}function s(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type===$){J.text=(J.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function zQ(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type==="reasoning"&&J.id===$){J.text=(J.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function q3(Q){return yQ(Q)}async function yQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await S3(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")M3(Z,J.error,$.origin);if(Q.throwOnError)throw new a({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function M3(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,W={...Z,generateId:Q,error:$},X=!1;try{t.error(J,W),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.error(J,W)}async function S3(Q){let $=Q.messages??[];if($.length===0&&!Q.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...$];if(Q.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q.prompt}],createdAt:new Date().toISOString()});let J={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},W=Q.signal??new AbortController().signal,X=v(),G="stop",Y,V={},H="";try{let D=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:HQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let F=await f(Promise.resolve(D.next()),W);if(F.done)break;let U=F.value;switch(U.type){case"output-delta":H+=U.delta;break;case"text-delta":s(J,"text",U.delta);break;case"reasoning-delta":zQ(J,U.id,U.delta);break;case"finish":if(X=E(X,U.usage),!Y)G=U.reason;break;case"error":G="error",Y=U.error,V=T(U);break}}}finally{if(W.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(B){if(B instanceof q||W.aborted)G="aborted",Y=R3(W);else G="error",Y=Q.provider.normalizeError(B),V=T(B)}let K=!1,z;if(!Y)if(G==="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(!H.trim())Y={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let B=YQ(Q.output,H);if(B.ok===!0)K=!0,z=B.value;else Y=B.error}if(K)J.content.push({type:"output",value:z});else if(H)s(J,"text",H);for(let B of J.content)if((B.type==="text"||B.type==="reasoning")&&typeof B.text==="string")B.text=KQ(B.text);if(J.finishReason=G,J.usage=X,Z.push(J),K)return{ok:!0,output:z,messages:Z,usage:X,finishReason:G};return{ok:!1,error:{...Y,...V},messages:Z,usage:X,finishReason:G}}function R3(Q){return Q.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}import{createHmac as k3,hkdfSync as T3,randomBytes as g9,timingSafeEqual as A3}from"crypto";class r{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(Q);if(J!==void 0&&J>Z)return!1;return this.spent.set(Q,$),!0}get size(){return this.spent.size}sweep(Q){for(let[$,Z]of this.spent)if(Z<=Q)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class uQ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:nonce"}async consume(Q,$){let Z=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Q}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Q=y9(),$=Q.bound(gQ)?Q.make(gQ).client:void 0;if(!$)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return $}}var m=new r;var cQ="agt2",UQ="agt1",u9=[cQ,UQ],mQ=86400000,x3=Date.now()+mQ;function c9(Q){return Q<=x3}var m9="gemi.ai.pending-call.v1",p9="gemi.ai.nested-run.v1",E3="gemi.ai.signing",BQ=new Map;function FQ(Q,$){let Z=pQ($),J=`${Q}\x00${Z}`,W=BQ.get(J);if(!W){if(W=Buffer.from(T3("sha256",Z,E3,Q,32)),BQ.size>64)BQ.clear();BQ.set(J,W)}return W}function pQ(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function A(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(A).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${A($[J])}`).join(",")}}`}function b3(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function p(Q,$){return k3("sha256",Q).update(b3($)).digest()}function d9(Q,$){let Z=Buffer.from(Q.split(".")[4],"base64url");return Z.length===$.length&&A3(Z,$)}function l9(Q){return A(Q??null)}function i9(Q,$,Z){return[cQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),A(Q.input),A(Q.path??[]),l9(Q.subject)]}function w3(Q,$,Z){let J=[UQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),A(Q.input)];if(Q.path&&Q.path.length>0)J.push(A(Q.path));return J}var o9=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),I3=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function n9(Q,$={}){let Z=FQ(m9,$.secret),W=($.now??Date.now())+($.ttlMs??mQ),X=g9(12).toString("base64url"),G=p(Z,i9(Q,X,W)).toString("base64url");return[cQ,o9(Q.runId),X,W.toString(36),G].join(".")}function dQ(Q){return CQ(Q,u9)}function CQ(Q,$){let Z=Q.split(".");if(Z.length!==5||!$.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:I3(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function s9(Q,$,Z={}){let J=CQ(Q,u9);if(!J)return{ok:!1,reason:"malformed"};if(J.version===UQ&&!c9(J.expiresAt))return{ok:!1,reason:"forged"};let W=J.version===UQ?p(pQ(Z.secret),w3($,J.nonce,J.expiresAt)):p(FQ(m9,Z.secret),i9($,J.nonce,J.expiresAt));if(!d9(Q,W))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var lQ="agn2",DQ="agn1",t9=[lQ,DQ];function a9(Q,$,Z){return[...r9(Q,$,Z,lQ),l9(Q.subject)]}function r9(Q,$,Z,J=DQ){return[J,Q.runId,A(Q.path),Q.nestedRunId,$,String(Z),A([...Q.open].sort()),A(Q.input)]}function e9(Q,$={}){let Z=FQ(p9,$.secret),W=($.now??Date.now())+($.ttlMs??mQ),X=g9(12).toString("base64url"),G=p(Z,a9(Q,X,W)).toString("base64url");return[lQ,o9(Q.runId),X,W.toString(36),G].join(".")}function Q$(Q,$,Z={}){let J=CQ(Q,t9);if(!J)return{ok:!1,reason:"malformed"};if(J.version===DQ&&!c9(J.expiresAt))return{ok:!1,reason:"forged"};let W={...$,runId:J.runId},X=J.version===DQ?p(pQ(Z.secret),r9(W,J.nonce,J.expiresAt)):p(FQ(p9,Z.secret),a9(W,J.nonce,J.expiresAt));if(!d9(Q,X))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 $$(Q,$){return J$($,dQ(Q))}function Z$(Q,$){return J$($,CQ(Q,t9))}async function J$(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class e extends O{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class d extends O{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function iQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new d("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var x="gemi_att_";function oQ(){return`${x}${crypto.randomUUID()}`}class QQ{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;iQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new e(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new e(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,W=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([W],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=oQ(),J=$.mimeType??Q.type??"",W=$.name??(Q instanceof File?Q.name:Z),X=await this.storage.put({name:nQ(Z,W),body:Q,contentType:J||void 0}),G={id:Z,scopeKey:this.scope.key,objectName:X,name:W,mimeType:J||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,G),G}}function nQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class LQ{rows=new Map;async put(Q,$){iQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){iQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var PQ=new LQ;var sQ=new TextEncoder;function W$(Q){return`id: ${Q.seq}
|
|
2
|
+
import{Ab as f9,Bb as F$,Cb as C$,Db as Y3,zb as O}from"../chunk-wc46df4w.js";import{$e as H6,Je as X3,Me as V3,af as Y6,bf as n,cf as WQ,qf as H3,sf as t,tf as gQ}from"../chunk-9de5kyz3.js";import{uf as G3,wf as fQ,xf as hQ}from"../chunk-v6vsjdp7.js";import{Bf as NQ}from"../chunk-pwchwgkc.js";import{yg as y9}from"../chunk-mfncnxva.js";import"../chunk-dxcg3vg7.js";import"../chunk-ra0ct4ad.js";import"../chunk-4cjfngfk.js";import"../chunk-z77p625q.js";class I extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${P3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class GQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function P3(Q){let $=h9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function h9(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;if(typeof J.message!=="string"&&typeof J.code!=="string"&&typeof J.type!=="string")return null;let W=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:W,param:J.param}}function T(Q){if(!Q||typeof Q!=="object")return{};let{status:$,requestId:Z}=Q;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function _(Q){if(Q instanceof GQ)return{code:"provider_error",message:Q.message,retryable:!0};if(_3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof I)return j3(Q.status,h9(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function j3(Q,$,Z){let J=$?.message??Z,W=($?.code??"").toLowerCase(),X=($?.type??"").toLowerCase(),G=`${W} ${X} ${J}`.toLowerCase();if(Q===429){let Y=W==="insufficient_quota"||G.includes("quota");return{code:"rate_limited",message:J,retryable:!Y}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(O3(G))return{code:"context_length_exceeded",message:J,retryable:!1};if(N3(G))return{code:"content_filtered",message:J,retryable:!1};if($?.param?.startsWith("tools")||G.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function O3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function N3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function _3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class q extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function f(Q,$){if($.aborted)return Promise.reject(new q);return new Promise((Z,J)=>{let W=()=>J(new q);$.addEventListener("abort",W,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",W))})}function v(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function E(Q,$){if(!$)return Q;let Z={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)Z.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)Z.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);if($.imageInputTokens!==void 0||Q.imageInputTokens!==void 0)Z.imageInputTokens=(Q.imageInputTokens??0)+($.imageInputTokens??0);if($.imageOutputTokens!==void 0||Q.imageOutputTokens!==void 0)Z.imageOutputTokens=(Q.imageOutputTokens??0)+($.imageOutputTokens??0);return Z}function VQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,J=!1;for(let G of Q){if(Z){if(J)J=!1;else if(G==="\\")J=!0;else if(G==='"')Z=!1;continue}if(G==='"')Z=!0;else if(G==="{")$.push("}");else if(G==="[")$.push("]");else if(G==="}"||G==="]")$.pop()}let W=Q;if(Z)W+='"';W=W.replace(/[,:]\s*$/,"");let X=$.reverse().join("");try{return JSON.parse(W+X)}catch{try{return JSON.parse(W.replace(/,?\s*"[^"]*"\s*$/,"")+X)}catch{return{}}}}function HQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:n(Q)}}function YQ(Q,$){let Z=Q.safeParse(VQ($));if(Z.ok===!0)return{ok:!0,value:Z.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Z.errors.join(", ")}`,retryable:!0}}}function KQ(Q){if(Q.length>0)Q[0];return Q}function s(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type===$){J.text=(J.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function zQ(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type==="reasoning"&&J.id===$){J.text=(J.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function q3(Q){return yQ(Q)}async function yQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await S3(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")M3(Z,J.error,$.origin);if(Q.throwOnError)throw new a({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function M3(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,W={...Z,generateId:Q,error:$},X=!1;try{t.error(J,W),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.error(J,W)}async function S3(Q){let $=Q.messages??[];if($.length===0&&!Q.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...$];if(Q.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q.prompt}],createdAt:new Date().toISOString()});let J={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},W=Q.signal??new AbortController().signal,X=v(),G="stop",Y,V={},H="";try{let D=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:HQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let F=await f(Promise.resolve(D.next()),W);if(F.done)break;let U=F.value;switch(U.type){case"output-delta":H+=U.delta;break;case"text-delta":s(J,"text",U.delta);break;case"reasoning-delta":zQ(J,U.id,U.delta);break;case"finish":if(X=E(X,U.usage),!Y)G=U.reason;break;case"error":G="error",Y=U.error,V=T(U);break}}}finally{if(W.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(B){if(B instanceof q||W.aborted)G="aborted",Y=R3(W);else G="error",Y=Q.provider.normalizeError(B),V=T(B)}let K=!1,z;if(!Y)if(G==="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(!H.trim())Y={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let B=YQ(Q.output,H);if(B.ok===!0)K=!0,z=B.value;else Y=B.error}if(K)J.content.push({type:"output",value:z});else if(H)s(J,"text",H);for(let B of J.content)if((B.type==="text"||B.type==="reasoning")&&typeof B.text==="string")B.text=KQ(B.text);if(J.finishReason=G,J.usage=X,Z.push(J),K)return{ok:!0,output:z,messages:Z,usage:X,finishReason:G};return{ok:!1,error:{...Y,...V},messages:Z,usage:X,finishReason:G}}function R3(Q){return Q.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}import{createHmac as k3,hkdfSync as T3,randomBytes as g9,timingSafeEqual as A3}from"crypto";class r{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(Q);if(J!==void 0&&J>Z)return!1;return this.spent.set(Q,$),!0}get size(){return this.spent.size}sweep(Q){for(let[$,Z]of this.spent)if(Z<=Q)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class uQ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:nonce"}async consume(Q,$){let Z=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Q}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Q=y9(),$=Q.bound(gQ)?Q.make(gQ).client:void 0;if(!$)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return $}}var m=new r;var cQ="agt2",UQ="agt1",u9=[cQ,UQ],mQ=86400000,x3=Date.now()+mQ;function c9(Q){return Q<=x3}var m9="gemi.ai.pending-call.v1",p9="gemi.ai.nested-run.v1",E3="gemi.ai.signing",BQ=new Map;function FQ(Q,$){let Z=pQ($),J=`${Q}\x00${Z}`,W=BQ.get(J);if(!W){if(W=Buffer.from(T3("sha256",Z,E3,Q,32)),BQ.size>64)BQ.clear();BQ.set(J,W)}return W}function pQ(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function A(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(A).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${A($[J])}`).join(",")}}`}function b3(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function p(Q,$){return k3("sha256",Q).update(b3($)).digest()}function d9(Q,$){let Z=Buffer.from(Q.split(".")[4],"base64url");return Z.length===$.length&&A3(Z,$)}function l9(Q){return A(Q??null)}function i9(Q,$,Z){return[cQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),A(Q.input),A(Q.path??[]),l9(Q.subject)]}function w3(Q,$,Z){let J=[UQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),A(Q.input)];if(Q.path&&Q.path.length>0)J.push(A(Q.path));return J}var o9=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),I3=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function n9(Q,$={}){let Z=FQ(m9,$.secret),W=($.now??Date.now())+($.ttlMs??mQ),X=g9(12).toString("base64url"),G=p(Z,i9(Q,X,W)).toString("base64url");return[cQ,o9(Q.runId),X,W.toString(36),G].join(".")}function dQ(Q){return CQ(Q,u9)}function CQ(Q,$){let Z=Q.split(".");if(Z.length!==5||!$.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:I3(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function s9(Q,$,Z={}){let J=CQ(Q,u9);if(!J)return{ok:!1,reason:"malformed"};if(J.version===UQ&&!c9(J.expiresAt))return{ok:!1,reason:"forged"};let W=J.version===UQ?p(pQ(Z.secret),w3($,J.nonce,J.expiresAt)):p(FQ(m9,Z.secret),i9($,J.nonce,J.expiresAt));if(!d9(Q,W))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var lQ="agn2",DQ="agn1",t9=[lQ,DQ];function a9(Q,$,Z){return[...r9(Q,$,Z,lQ),l9(Q.subject)]}function r9(Q,$,Z,J=DQ){return[J,Q.runId,A(Q.path),Q.nestedRunId,$,String(Z),A([...Q.open].sort()),A(Q.input)]}function e9(Q,$={}){let Z=FQ(p9,$.secret),W=($.now??Date.now())+($.ttlMs??mQ),X=g9(12).toString("base64url"),G=p(Z,a9(Q,X,W)).toString("base64url");return[lQ,o9(Q.runId),X,W.toString(36),G].join(".")}function Q$(Q,$,Z={}){let J=CQ(Q,t9);if(!J)return{ok:!1,reason:"malformed"};if(J.version===DQ&&!c9(J.expiresAt))return{ok:!1,reason:"forged"};let W={...$,runId:J.runId},X=J.version===DQ?p(pQ(Z.secret),r9(W,J.nonce,J.expiresAt)):p(FQ(p9,Z.secret),a9(W,J.nonce,J.expiresAt));if(!d9(Q,X))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 $$(Q,$){return J$($,dQ(Q))}function Z$(Q,$){return J$($,CQ(Q,t9))}async function J$(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class e extends O{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class d extends O{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function iQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new d("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var x="gemi_att_";function oQ(){return`${x}${crypto.randomUUID()}`}class QQ{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;iQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new e(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new e(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,W=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([W],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=oQ(),J=$.mimeType??Q.type??"",W=$.name??(Q instanceof File?Q.name:Z),X=await this.storage.put({name:nQ(Z,W),body:Q,contentType:J||void 0}),G={id:Z,scopeKey:this.scope.key,objectName:X,name:W,mimeType:J||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,G),G}}function nQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class LQ{rows=new Map;async put(Q,$){iQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){iQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var PQ=new LQ;var sQ=new TextEncoder;function W$(Q){return`id: ${Q.seq}
|
|
3
3
|
data: ${JSON.stringify(Q.event)}
|
|
4
4
|
|
|
5
5
|
`}var v3=5000,f3=`: keepalive
|
|
@@ -17,4 +17,4 @@ data: ${JSON.stringify(Y.event)}
|
|
|
17
17
|
`);while(H!==-1){let K=$.slice(0,H);$=$.slice(H+1);let z=G(K);if(z)yield z;H=$.indexOf(`
|
|
18
18
|
`)}}if($.length>0){let V=G($);if(V)yield V}let Y=X();if(Y)yield Y}async function*v$(Q,$={}){let Z=new Map,J=new Set,W=!1;for await(let X of FZ(Q)){if(X.data==="[DONE]")break;let G;try{G=JSON.parse(X.data)}catch{continue}switch(typeof G.type==="string"?G.type:X.event){case"response.output_text.delta":{let V=String(G.delta??"");if(!V)break;yield $.structuredOutput?{type:"output-delta",delta:V}:{type:"text-delta",delta:V};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let V=String(G.delta??"");if(!V)break;yield{type:"reasoning-delta",delta:V,id:G.item_id};break}case"response.output_item.added":{let V=G.item;if(!V)break;if(V.type==="function_call"){let H=String(V.id??G.item_id??V.call_id??"");Z.set(H,{callId:String(V.call_id??H),name:String(V.name??""),namespace:typeof V.namespace==="string"&&V.namespace?V.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let V=Z.get(String(G.item_id??""));if(!V)break;let H=String(G.delta??"");if(!H)break;yield{type:"tool-call-delta",toolCallId:V.callId,name:V.name,argsDelta:H,...V.namespace?{namespace:V.namespace}:{}};break}case"response.function_call_arguments.done":{let V=String(G.item_id??""),H=Z.get(V);if(!H)break;H.done=!0,yield{type:"tool-call",toolCallId:H.callId,name:H.name,args:String(G.arguments??""),...H.namespace?{namespace:H.namespace}:{}};break}case"response.output_item.done":{let V=G.item;if(!V)break;if(V.type==="function_call"){let H=String(V.id??G.item_id??V.call_id??""),K=Z.get(H);if(K?.done)break;let z=(typeof V.namespace==="string"?V.namespace:"")||K?.namespace;if(yield{type:"tool-call",toolCallId:String(V.call_id??H),name:String(V.name??K?.name??""),args:String(V.arguments??""),...z?{namespace:z}:{}},K)K.done=!0;break}if(V.type==="tool_search_call"||V.type==="tool_search_output"){let H=CZ(V);if(H.loaded.length===0&&H.namespaces.length===0)break;let K=String(V.tool_search_call_id??V.id??"");if(J.has(K))break;J.add(K),yield{type:"tool-search",...H}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(G.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{W=!0,yield{type:"finish",reason:"stop",usage:C9(G.response?.usage)};break}case"response.incomplete":{W=!0;let V=C9(G.response?.usage),H=G.response?.incomplete_details?.reason;if(H==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:LZ(G.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:V};break}yield{type:"finish",reason:H==="max_output_tokens"?"length":"stop",usage:V};break}case"response.failed":case"error":{W=!0;let V=G.response?.error??G.error??G;yield{type:"error",error:PZ(V)},yield{type:"finish",reason:"error",usage:C9(G.response?.usage)};break}}if(W)return}if(!W)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield{type:"finish",reason:"error",usage:l()}}function CZ(Q){let $=[],Z=[];return f$(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:L9($),namespaces:L9(Z)}}function f$(Q,$,Z,J){if(!Array.isArray(Q)||J>4)return;for(let W of Q){if(typeof W==="string"){$.push(W);continue}if(!W||typeof W!=="object")continue;let X=W,G=typeof X.name==="string"?X.name:typeof X.tool_name==="string"?X.tool_name:"",Y=X.tools??X.functions;if(Array.isArray(Y)){if(G)Z.push(G);f$(Y,$,Z,J+1);continue}if(G)$.push(G)}}function L9(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function LZ(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let J of Q){if(!J||typeof J!=="object")continue;let W=J,X=W.content_filter_results;if(!X||typeof X!=="object")continue;for(let[G,Y]of Object.entries(X))if(Y&&typeof Y==="object"&&Y.filtered===!0)Z.push(`${G} (${String(W.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${L9(Z).join(", ")}.`}function PZ(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",Z=String(Q?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function l(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function C9(Q){if(!Q)return l();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},W=Q.output_tokens_details?.reasoning_tokens;if(typeof W==="number")J.reasoningTokens=W;let X=Q.input_tokens_details?.cached_tokens;if(typeof X==="number")J.cachedInputTokens=X;return J}async function*h$(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:W,value:X}=await $.read();if(W)break;if(X)yield Z.decode(X,{stream:!0})}let J=Z.decode();if(J)yield J}finally{$.releaseLock()}}function P9(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}async function*j9(Q,$,Z){let J,W=$,X=new Set;for(let G=0;J===void 0;G++)try{J=await ZQ(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(W)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(Y){let V=G<b$?w$(W,Y,Z.files).filter((K)=>!X.has(K)):[];if(V.length>0){let K=_(Y).message;for(let z of V)X.add(z),yield{type:"file-rejected",fileId:z,message:K,...T(Y)};W=I$(W,new Set(V),Z.files);continue}let H=_(Y);if(H.code!=="aborted")yield{type:"error",error:H,...T(Y)};yield{type:"finish",reason:H.code==="aborted"?"aborted":"error",usage:l()};return}try{yield*v$(h$(J.body),{structuredOutput:Z.structuredOutput})}catch(G){let Y=_(G);if(Y.code==="aborted"){yield{type:"finish",reason:"aborted",usage:l()};return}yield{type:"error",error:Y},yield{type:"finish",reason:"error",usage:l()}}}async function O9(Q,$,Z="user_data"){let J=new FormData;J.set("purpose",Z),J.set("file",$);let X=await(await ZQ(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:J},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!X?.id)throw Error("The provider accepted the upload but returned no file id.");return X.id}function N9(Q){let $=jZ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=OZ($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:y$(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:y$(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function y$(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function jZ(Q){return Q.trim().toLowerCase()}function OZ(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec(Q);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function q9(Q,$){let{capabilities:Z}=$,J={model:$.model,input:NZ(Q.messages,Z),stream:!0};if(Q.systemPrompt)J.instructions=Q.systemPrompt;let W=xZ(Q.tools,Z);if(W.length>0){if(J.tools=W,!Z.parallelToolCalls)J.parallel_tool_calls=!1}if(Q.output)J.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&Z.reasoning)J.reasoning=Q.reasoning==="none"?{effort:"none"}:{effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")J.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")J.max_output_tokens=Q.maxOutputTokens;return J}function NZ(Q,$){let Z=[];for(let J of Q){let W=J.role,X=[],G=()=>{if(X.length===0)return;Z.push({type:"message",role:W,content:X}),X=[]};for(let Y of J.content??[])switch(Y.type){case"text":{if(!Y.text)break;X.push(i(W,Y.text));break}case"output":{if(Y.partial)break;X.push(i(W,JSON.stringify(Y.value)));break}case"file":{if(W==="assistant")break;let V=MZ(Y);if(!$.fileInput){if(V)X.push(i(W,_9(Y,!1)));break}if(Y.fileId?.startsWith(x))throw Error(`FilePart.fileId holds a gemi attachment id (${Y.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!Y.fileId&&!V)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(Y.providerRejected){if(V)X.push(i(W,_9(Y,!1)));X.push(i(W,D9(Y.name)));break}if(V)X.push(i(W,_9(Y,!!Y.fileId)));if(Y.fileId)X.push(SZ(Y));break}case"reasoning":{G();let V=TZ(Y);if(V)Z.push(V);break}case"tool-call":{if(Y.partial)break;G(),Z.push({type:"function_call",call_id:Y.toolCallId,name:String(Y.name),arguments:JSON.stringify(Y.input??{})});break}case"tool-result":{G(),Z.push({type:"function_call_output",call_id:Y.toolCallId,output:AZ(Y)});break}}G()}return qZ(Z)}var _Z="No result was recorded for this tool call. Assume it did not complete.";function qZ(Q){let $=new Set,Z=new Set,J=[];for(let X of Q){if(X.type==="function_call"){let G=String(X.call_id);if($.has(G))continue;$.add(G)}else if(X.type==="function_call_output"){let G=String(X.call_id);if(!$.has(G)||Z.has(G))continue;Z.add(G)}J.push(X)}if(Z.size===$.size)return J;let W=[];for(let X of J){if(W.push(X),X.type!=="function_call")continue;let G=String(X.call_id);if(Z.has(G))continue;Z.add(G),W.push({type:"function_call_output",call_id:G,output:_Z})}return W}function i(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function MZ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(x)?$:void 0}function _9(Q,$){let Z=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)Z.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)Z.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let J=`attachment ${Z.join(" ")}`;return $?`[${J}]`:`[${J} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function SZ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":RZ(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function RZ(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&kZ.has($[1])}var kZ=new Set(["jpeg","jpg","png","gif","webp"]);function TZ(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function AZ(Q){if(Q.status==="ok")return typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??null);if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function g$(Q){return Array.isArray(Q.tools)}function xZ(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let W=[];for(let X of Q)if(g$(X))for(let G of X.tools)W.push(kQ(G,!1));else W.push(kQ(X,!1));return W}let Z=[],J=!1;for(let W of Q)if(g$(W)){let X=W.tools.map((G)=>{if(G.deferred)J=!0;return kQ(G,!0)});Z.push({type:"namespace",name:W.name,description:W.description,tools:X})}else{if(W.deferred)J=!0;Z.push(kQ(W,!0))}if(J)Z.push({type:"tool_search"});return Z}function kQ(Q,$){let Z={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)Z.defer_loading=!0;return Z}class TQ{static models(){return[]}normalizeError(Q){return _(Q)}}var u$=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class M9 extends TQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=N9(Q),this.config=$}static model(Q,$){return new M9(Q,$)}static models(){return u$}stream(Q){let $=q9(Q,{model:this.model,capabilities:this.capabilities});return j9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:U9(Q.messages)})}upload(Q){return O9(this.endpoint(),Q)}endpoint(){return P9(qQ(this.config))}}class S9 extends TQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=N9(Q),this.config=$}static model(Q,$){return new S9(Q,$)}static models(){return u$}stream(Q){let $=q9(Q,{model:this.deployment(),capabilities:this.capabilities});return j9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:U9(Q.messages)})}upload(Q){return O9(this.endpoint(),Q,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return P9(MQ(this.config))}}class o extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,Z){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=Z}}class JQ extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class AQ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096,this.maxAgeMs=Q.maxAgeMs===void 0?3600000:Q.maxAgeMs}register(Q,$={}){let Z={run:Q,threadId:$.threadId,owner:$.owner??null,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(Q.runId,Z),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);return this.scheduleExpiry(Z,$.maxRunDurationMs),this.pump(Z,$)}findByClientRunId(Q){let $=this.byClientRun.get(Q);return $&&this.runs.has($)?$:null}async find(Q){let $=this.byThread.get(Q.threadId);if(!$)return null;let Z=this.runs.get($);if(!Z)return null;return{runId:$,seq:Z.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}ownerOf(Q){return this.runs.get(Q)?.owner??null}mayAccess(Q,$){let Z=this.ownerOf(Q);return Z===null||Z===$}isRunning(Q){let $=this.runs.get(Q);return!!$&&!$.ended&&!$.evicted}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new JQ(Q);if($!==void 0&&$<Z.lostBefore)throw new o(Q,$,Z.lostBefore);let J=Z.frames[0]?.seq;return this.drain(Z,Q,$??J??Z.lastSeq+1)}clear(){for(let Q of this.runs.values()){if(Q.evictAt)clearTimeout(Q.evictAt);if(Q.expireAt)clearTimeout(Q.expireAt);Q.ended=!0,this.notify(Q)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(Q,$){let Z=Promise.resolve();try{for await(let J of Q.run.frames()){if(Q.evicted){let X=$.onEvent;if(X)Z=Z.then(()=>X(J.event)).catch((G)=>R9($,G));continue}if(Q.frames.push(J),Q.lastSeq=J.seq,Q.frames.length>this.maxFrames){let X=Q.frames.shift();if(X)Q.lostBefore=X.seq+1}this.notify(Q);let W=$.onEvent;if(W)Z=Z.then(()=>W(J.event)).catch((X)=>R9($,X))}}catch(J){R9($,J)}finally{if(Q.ended=!0,Q.expireAt)clearTimeout(Q.expireAt),Q.expireAt=null;this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let J=Z;while(!0){let W=Q.version;for(;;){if(J<Q.lostBefore)throw new o($,J,Q.lostBefore);let X=Q.frames,G=X[0]?.seq;if(G===void 0)break;let Y=Math.max(0,J-G);if(Y>=X.length)break;let V=X[Y];yield V,J=V.seq+1}if(Q.ended&&J>Q.lastSeq||Q.evicted)return;await this.wait(Q,W)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((Z)=>Q.wake.add(Z))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let Z of $)Z()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let Z=Q.run.runId;if(!Q.ended)Q.evicted=!0,Q.frames=[];if(this.runs.get(Z)===Q)this.runs.delete(Z);if(Q.threadId&&this.byThread.get(Q.threadId)===Z)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===Z)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}scheduleExpiry(Q,$){if(this.maxAgeMs===null||$===null)return;let Z=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Z)||Z>2147483647)return;let J=setTimeout(()=>{if(Q.expireAt=null,Q.ended)return;try{Q.run.stop({reason:`The run was still going ${Math.round(Z/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(Q)},Z);J.unref?.(),Q.expireAt=J}}var k9=new AQ;function R9(Q,$){try{Q.onInternalError?.($)}catch{}}class xQ{maxEntries;records=new Map;constructor(Q=1e5){this.maxEntries=Q}async record(Q,$){if(this.records.has(Q))return;this.records.set(Q,{...$});while(this.records.size>this.maxEntries){let Z=this.records.keys().next().value;if(Z===void 0)break;this.records.delete(Z)}}async get(Q){let $=this.records.get(Q);return $?{...$}:null}}var T9=new xQ;class EQ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??86400000,this.clientOwnedIds=Q.clientOwnedIds??!1}async createThread(Q){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(Q){this.sweep();let $=this.threads.get(Q);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set(Q,Z)}for(let J of $){let W=Z.messages.findIndex((X)=>X.id===J.id);if(W===-1)Z.messages.push(J);else Z.messages[W]=J}Z.touchedAt=Date.now()}async removeMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z)return;let J=new Set($);Z.messages=Z.messages.filter((W)=>!J.has(W.id)),Z.touchedAt=Date.now()}delete(Q){this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<60000)return;this.lastSweep=Q;for(let[$,Z]of this.threads)if(Q-Z.touchedAt>this.ttlMs)this.threads.delete($)}}var A9=new EQ;function d$(Q={}){return{messages:Q.messages?[...Q.messages]:[],pending:Q.pending?[...Q.pending]:[],error:null,threadId:Q.threadId,seq:Q.seq??-1,cursorRunId:Q.cursorRunId,runMessageIds:[],loadedTools:[]}}function l$(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...i$(Q,$.event,Z),seq:$.seq}}function i$(Q,$,Z){switch($.type){case"run-start":return{...Q,runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return u(Q,$.messageId,Z,(J)=>({...J,role:$.role}));case"text-delta":if(m$(Q,$.messageId))return Q;return u(Q,$.messageId,Z,(J)=>({...J,content:vZ(J.content,$.delta)}));case"reasoning-delta":if(m$(Q,$.messageId))return Q;return u(Q,$.messageId,Z,(J)=>({...J,content:fZ(J.content,$.delta,$.id)}));case"output-delta":return u(Q,$.messageId,Z,(J)=>({...J,content:p$(J.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return u(Q,$.messageId,Z,(J)=>{let W=J.content.findIndex((z)=>z.type==="tool-call"&&z.toolCallId===$.part.toolCallId),X=W===-1?void 0:J.content[W],G=$.part.progress??X?.progress,Y=$.part.nested??X?.nested,V=$.part.attachments??X?.attachments,H={...$.part,...G?{progress:G}:{},...Y?{nested:Y}:{},...V?{attachments:V}:{}},K=J.content.slice();if(W===-1)K.push(H);else K[W]=H;return{...J,content:K}});case"tool-search":{let J=$.loaded.filter((W)=>!Q.loadedTools.includes(W));if(J.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...J]}}case"tool-progress":return c$(Q,$.toolCallId,(J)=>({...J,progress:[...J.progress??[],$.data]}));case"nested-event":{let J=$;return c$(Q,$.toolCallId,(W)=>{let X=W.nested??[],G=X.findIndex((K)=>K.runId===J.runId),Y=X[G]??{runId:J.runId,agent:J.agent,messages:[]},V=wZ(Y,J,Z),H=G===-1?[...X,V]:X.map((K,z)=>z===G?V:K);return{...W,nested:H}})}case"tool-result":{let J=u(Q,$.messageId,Z,(W)=>({...W,content:p$(W.content,$.part,(X)=>X.type==="tool-result"&&X.toolCallId===$.part.toolCallId)}));return{...J,pending:J.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let J=Q.messages.findIndex((G)=>G.id===$.message.id),W=Q.messages.slice();if(J===-1)W.push($.message);else W[J]=$.message;let X=Q.runMessageIds.includes($.message.id)?Q.runMessageIds:[...Q.runMessageIds,$.message.id];return{...Q,messages:W,runMessageIds:X}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return u(Q,$.messageId,Z,(J)=>({...J,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?J.content.filter((W)=>!(W.type==="output"&&W.partial)):J.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...Q,usage:$.usage};case"error":return{...Q,error:$.error,pending:[]};case"run-end":return{...Q,runId:void 0,finishReason:$.finishReason,messages:o$(Q,$.finishReason)};default:return Q}}function o$(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?EZ(Z,$):Z)}function EZ(Q,$){let Z=Q.content.map((W)=>W.type==="tool-call"&&W.nested?.some((X)=>X.finishReason===void 0)?{...W,nested:W.nested.map((X)=>X.finishReason===void 0?bZ(X,$):X)}:W);if(Q.finishReason===void 0)return{...Q,finishReason:$,content:Z};return Z.some((W,X)=>W!==Q.content[X])?{...Q,content:Z}:Q}function bZ(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((J)=>J.id),loadedTools:[]};return{...Q,finishReason:$,messages:o$(Z,$)}}function c$(Q,$,Z){for(let J=Q.messages.length-1;J>=0;J--){let W=Q.messages[J],X=W.content.findIndex((H)=>H.type==="tool-call"&&H.toolCallId===$);if(X===-1)continue;if(W.finishReason!==void 0&&!IZ(Q,W,$))return Q;let G=W.content.slice();G[X]=Z(G[X]);let Y=Q.messages.slice();Y[J]={...W,content:G};let V=Q.runMessageIds.includes(W.id)?Q.runMessageIds:[...Q.runMessageIds,W.id];return{...Q,runMessageIds:V,messages:Y}}return Q}function wZ(Q,$,Z){let J={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((X)=>X.id),loadedTools:[],finishReason:Q.finishReason},W=i$(J,$.event,Z);return{...Q,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function IZ(Q,$,Z){if($.finishReason!=="awaiting-input")return!1;return!Q.messages.some((J)=>J.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Z))}function m$(Q,$){let Z=Q.messages.find((J)=>J.id===$);return Z!==void 0&&Z.finishReason!==void 0}function u(Q,$,Z,J){let W=Q.messages.findIndex((Y)=>Y.id===$),X=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(W===-1){let Y={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:X,messages:[...Q.messages,J(Y)]}}let G=Q.messages.slice();return G[W]=J(G[W]),{...Q,runMessageIds:X,messages:G}}function vZ(Q,$){let Z=Q[Q.length-1];if(Z&&Z.type==="text")return[...Q.slice(0,-1),{type:"text",text:Z.text+$}];return[...Q,{type:"text",text:$}]}function fZ(Q,$,Z){let J=Q[Q.length-1];if(J&&J.type==="reasoning"&&J.id===Z)return[...Q.slice(0,-1),{...J,text:(J.text??"")+$}];return[...Q,Z?{type:"reasoning",id:Z,text:$}:{type:"reasoning",text:$}]}function p$(Q,$,Z){let J=Q.findIndex(Z);if(J===-1)return[...Q,$];let W=Q.slice();return W[J]=$,W}class E9{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(Q,$,Z,J){this.store=Q;this.threadId=$;this.report=J;this.state=d$({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[x9(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=l$(this.state,Q),$.type){case"message":this.write(()=>[x9($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(Q=[]){this.closed=!0;for(let $ of Q)this.done.add($.id)}settled(){return this.chain}checkpoint(Q){if(this.done.has(Q))return;let $=this.state.messages.find((J)=>J.id===Q);if(!$)return;let Z=this.runId;this.write(()=>{let J=x9($);if(J.finishReason===void 0&&Z)J.runId=Z;return[J]})}write(Q){let $;try{$=Q()}catch(Z){this.report(Z);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Z)=>this.report(Z))}}function x9(Q){return structuredClone(Q)}async function n$(Q,$){let Z=[],J=null,W=Q.slice();for(let X=0;X<W.length;X++){let G=W[X];if(G.role!=="assistant"||G.finishReason!==void 0)continue;if(G.runId&&await $(G.runId))continue;J??=new Set(Q.flatMap((H)=>H.content.flatMap((K)=>K.type==="tool-result"?[K.toolCallId]:[])));let Y=G.content.map((H)=>H.type==="tool-call"?s$(H):H);for(let H of G.content){if(H.type!=="tool-call"||J.has(H.toolCallId))continue;let K={type:"tool-result",toolCallId:H.toolCallId,name:H.name,status:"denied",cause:"interrupted"};Y.push(K)}let V={...G,content:Y,finishReason:"interrupted"};W[X]=V,Z.push(V)}return{messages:W,settled:Z}}function s$(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((J)=>J.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(hZ)}}function hZ(Q){if(Q.finishReason!==void 0)return Q;return{...Q,finishReason:"interrupted",messages:Q.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Z)=>Z.type==="tool-call"?s$(Z):Z)}:$)}}var yZ=X3,bQ=new Map,t$=new WeakMap,wQ=new Map,gZ=4194304,uZ=1000,cZ=5,a$=65536,K3=()=>{};class z3{byKey=new Map;take(Q,$,Z){let J=this.byKey.get(Q);if(!J?.has($)&&(J?.size??0)>=Z)return null;if(!J)J=new Map,this.byKey.set(Q,J);J.set($,(J.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let X=this.byKey.get(Q),G=(X?.get($)??1)-1;if(!X)return;if(G>0)X.set($,G);else if(X.delete($),X.size===0)this.byKey.delete(Q)}}}var r$=new WeakMap;function mZ(Q){let $=r$.get(Q);if(!$)$=new z3,r$.set(Q,$);return $}class B3 extends yZ{static kind="agent-controller";store=A9;liveRuns=k9;attachments=PQ;attachmentStorage=H3;fileOwners=T9;nonces=m;requireKnownFiles=!1;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;maxBodyBytes=gZ;maxHistoryMessages=uZ;maxConcurrentRuns=cZ;runLimitKey(Q,$){return $.owner}authorizeRequest(Q,$){}runOwner(Q){let $=Q.ctx?.()?.user,Z=$?.id??$?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}async stream(Q=new WQ){let $=await b9(Q,this.maxBodyBytes);if($.error)return IQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,W=tZ(Z);if(W.error)return IQ({body:{},error:W.error});let X=W.turn,G=J!==void 0&&Z.regenerate===!0,Y=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,V=U3(Z);if(this.requireThread&&!J)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(G&&!this.store.removeMessages)return M(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!J&&Array.isArray(Z.messages)&&Z.messages.length>this.maxHistoryMessages)return v9(413,"history_too_long",`The conversation has ${Z.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let H=await this.runOwner(Q),K=Y?{cancelled:!1,owner:H}:null;if(K)wQ.set(Y,K);let z=null,B=[],D=async()=>{try{return await F()}finally{if(J&&B.length>0&&z===null)await this.store.appendMessages(J,B).catch((U)=>this.reportHookFailure(U))}},F=async()=>{let U;if(J){let S=await this.store.loadThread(J);if(!S)return M(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});if(U=await this.settleThread(J,S,{write:!0}),G){let c=Q6(U);if(!c)return M(409,{code:"nothing_to_regenerate",message:`Thread ${J} has no user turn to answer again.`});B=U.slice(c.index),await this.store.removeMessages(J,B.map((L3)=>L3.id)),U=U.slice(0,c.index),X=c.turn}}else U=Array.isArray(Z.messages)?Z.messages:[],V6(this.nonces);let L=await this.instructions(Q,{body:V})||void 0,C=await this.context(Q,{body:V}),R=await this.attachmentsFor(Q,J,{body:V});if(K?.cancelled)return Z3();let j=J?new E9(this.store,J,U,(S)=>this.reportHookFailure(S)):null,b=`run_${crypto.randomUUID()}`,k={req:Q,runId:b,threadId:J},N=this.agent.stream({runId:b,messages:U,turn:X,threadId:J,...j?{onMessage:(S)=>j.finish(S)}:{},instructions:L,context:C,attachments:R,body:V,redactError:(S,c)=>this.redactError(S,c,k),nonces:this.nonces,subject:H}),P=this.liveRuns.register(N,{threadId:J,owner:H,clientRunId:Y,onEvent:(S)=>this.dispatchEvent(S,k),onInternalError:(S)=>this.reportHookFailure(S),maxRunDurationMs:this.agent.maxRunDurationMs});if(z=N,j)this.follow(N,j);let{stored:w,hooks:XQ}=this.persistRun(N,k,P,j);return t$.set(N,w),Q.ctx?.()?.waitUntil(XQ),N.toResponse()};try{await this.authorizeRequest(Q,{route:"stream",threadId:J,body:V});let U=await this.foreignFile([...X?.files??[],...J?[]:Z6(Z.messages)],H);if(U)return U;if(K?.cancelled)return Z3();let L=await this.runLimitKey(Q,{owner:H,threadId:J}),C=L===null?K3:mZ(this.liveRuns).take(L,J?`thread:${J}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!C)return v9(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,H,D):await D()}finally{let R=z;if(R)R.result().then(C,C);else C()}}finally{if(K&&wQ.get(Y)===K)wQ.delete(Y)}}async withThread(Q,$,Z){let J=bQ.get(Q)??Promise.resolve(),W,X=new Promise((Y)=>{W=Y}),G=J.then(()=>X);bQ.set(Q,G),await J;try{let Y=await this.liveRuns.find({threadId:Q});if(Y&&this.liveRuns.isRunning(Y.runId)&&!this.liveRuns.mayAccess(Y.runId,$))return vQ();let V=Y?this.liveRuns.get(Y.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await t$.get(V);return await Z()}finally{if(W(),bQ.get(Q)===G)bQ.delete(Q)}}async attach(Q=new WQ){let $=await b9(Q,a$);if($.error)return IQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:eZ(Q,"threadId");if(!J)return M(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:J});let W=await this.liveRuns.find({threadId:J});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(Q)))return vQ();if(!W)return M(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`});let X=typeof Z.runId==="string"?Z.runId:void 0,G=X&&X!==W.runId?void 0:rZ(Q,Z);try{return X$(this.liveRuns.replay(W.runId,G))}catch(Y){if(Y instanceof o)return M(410,{code:Y.code,message:Y.message,oldestSeq:Y.oldest});if(Y instanceof JQ)return M(404,{code:Y.code,message:Y.message});throw Y}}async stop(Q=new WQ){let $=await b9(Q,a$);if($.error)return IQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let J=await this.runOwner(Q),W=typeof Z.runId==="string"?Z.runId:void 0;if(!W&&typeof Z.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!W){let G=wQ.get(Z.clientRunId);if(G){if(G.owner!==null&&G.owner!==J)return vQ();return G.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Z.threadId==="string")W=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let X=W?this.liveRuns.get(W):null;if(!X)return{stopped:!1};if(!this.liveRuns.mayAccess(X.runId,J))return vQ();return X.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$,Z){let J=Q.ctx()?.user,W=J?.id??J?.publicId;if(W!==void 0&&W!==null&&String(W)!=="")return{key:`user:${String(W)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(Q){return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$,Z={body:{}}){let J=await this.attachmentScope(Q,$,Z);if(!J)return null;return new QQ(this.attachments,this.attachmentStorage,J)}async upload(Q=new WQ){let $=await Q.rawRequest.formData(),Z=$.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",W=Z.type||"application/octet-stream",X=dZ($.get("body")),G=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof G==="string"&&G.length>0?G:void 0,body:X});let Y=iZ(await this.attachmentLimits(Q),Z,J,W);if(Y)throw new D3(Y.code,Y.message);let V=typeof G==="string"&&G.length>0&&await this.store.loadThread(G)!==null?G:void 0,H=await this.runOwner(Q),K=(j)=>this.fileOwners.record(j,{owner:H,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString()}),z=await this.attachmentDestination(Z,Q),B=J6(z,$.get("destination")),D=await this.attachmentScope(Q,V,{body:X}),F=B!=="provider"&&!D;if(F){if(B==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');W6()}if(B==="provider"||!D){let j=await e$(this.agent.provider,Z);await K(j);let b={fileId:j,name:J,mimeType:W,size:Z.size,destination:"provider"};if(F)b.downgraded="no_scope";return b}let U=oQ(),L=await this.attachmentStorage.put({name:nQ(U,J),body:Z,contentType:W}),C=B==="both"?await e$(this.agent.provider,Z):void 0;if(C)await K(C);let R={id:U,scopeKey:D.key,fileId:C,objectName:L,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString(),destination:B};return await this.attachments.put(D,R),{fileId:C,attachmentId:U,name:J,mimeType:W,size:Z.size,destination:B}}async foreignFile(Q,$){let Z=new Set(Q.map((J)=>J.fileId).filter((J)=>typeof J==="string"));for(let J of Z){let W=await this.fileOwners.get(J);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return $6()}return null}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}redactError(Q,$,Z){return f9(Q,$)}onError(Q,$){}onStreamComplete(Q,$){}reportHookFailure(Q){console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,$){switch(Q.type){case"tool-call":if(!Q.part.partial&&!Q.resent)await this.onToolCall({toolCallId:Q.part.toolCallId,name:String(Q.part.name),input:Q.part.input},$);return;case"awaiting-input":await this.onAwaitingInput(Q.pending,$);return;case"error":await this.onError(Y3(Q.error),$);return;default:return}}async readThread(Q){let $=await this.store.loadThread(Q);return $?await this.settleThread(Q,$,{write:!1}):null}isRunLive(Q,$){return this.liveRuns.get(Q)!==null}async settleThread(Q,$,{write:Z}){let{messages:J,settled:W}=await n$($,(X)=>this.isRunLive(X,Q));if(Z&&W.length>0)try{await this.store.appendMessages(Q,W)}catch(X){this.reportHookFailure(X)}return J}follow(Q,$){(async()=>{try{for await(let Z of Q.frames())$.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun(Q,$,Z,J=null){let W=Promise.resolve(),X=(async()=>{let Y;try{Y=await Q.result()}catch(H){J?.close(),await J?.settled(),W=this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},$));return}let V=Y.messages;if(J?.close(V),await J?.settled(),$.threadId&&V.length>0)try{await this.store.appendMessages($.threadId,V)}catch(H){this.reportHookFailure(H)}W=this.notifyRun(Y,V,$)})(),G=X.then(()=>G6(Promise.all([W,Z]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:G}}async notifyRun(Q,$,Z){for(let J of $)await this.safely(()=>this.onMessage(J,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}var w9=["turn","clientRunId","threadId","messages","regenerate"],pZ=["text","files","toolResults"];function U3(Q,$=C3(Q)?w9:[...w9,...pZ]){let Z={};for(let[J,W]of Object.entries(Q)){if($.includes(J))continue;Object.defineProperty(Z,J,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Z}function dZ(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new I9("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new I9("The upload's `body` field must be a JSON object.");return U3($,w9)}class I9 extends fQ{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function e$(Q,$){try{return await Q.upload($)}catch(Z){if(Z instanceof I&&lZ.has(Z.status))throw new F3(_(Z).message);throw Z}}var lZ=new Set([400,413,415,422]);class D3 extends fQ{constructor(Q,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}function iZ(Q,$,Z,J){if(!Q)return null;let{maxBytes:W,accept:X}=Q;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Z)} is ${Q3($.size)}; the limit is ${Q3(W)}.`};if(X&&X.length>0&&!X.some((G)=>oZ(G,Z,J)))return{code:"unsupported_file_type",message:`${JSON.stringify(Z)} is not a type this chat accepts. Accepted: ${X.join(", ")}.`};return null}function oZ(Q,$,Z){let J=Q.trim().toLowerCase();if(!J)return!1;if(J.startsWith("."))return $.toLowerCase().endsWith(J);let W=Z.toLowerCase().split(";")[0].trim();if(J.endsWith("/*"))return W.startsWith(J.slice(0,-1));return W===J}function Q3(Q){if(Q<1024)return`${Q} B`;let $=["KB","MB","GB"],Z=Q/1024,J=0;while(Z>=1024&&J<$.length-1)Z/=1024,J++;return`${Math.round(Z*10)/10} ${$[J]}`}class F3 extends fQ{constructor(Q){super(Q);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(Q)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}async function b9(Q,$){let Z=Q?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!nZ(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>$)return $3($);let W;try{let G=await sZ(Z,$);if(G===null)return $3($);W=G}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let X;try{X=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(X===null||typeof X!=="object"||Array.isArray(X))return{body:{},error:"The request body must be a JSON object."};return{body:X}}function nZ(Q){return V3(Q)==="application/json"}async function sZ(Q,$){if(!Number.isFinite($)||!Q.body)return await Q.text();let Z=Q.body.getReader(),J=[],W=0;for(;;){let{done:Y,value:V}=await Z.read();if(Y)break;if(W+=V.byteLength,W>$)return await Z.cancel().catch(K3),null;J.push(V)}let X=new Uint8Array(W),G=0;for(let Y of J)X.set(Y,G),G+=Y.byteLength;return new TextDecoder().decode(X)}function $3(Q){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${Q} bytes).`}}function v9(Q,$,Z){return M(Q,{...hQ(G3(Q),Z,Q),code:$})}function IQ(Q){if(Q.status===413)return v9(413,Q.code??"body_too_large",Q.error??"");return M(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function C3(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function tZ(Q){let $=C3(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let J=aZ($.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function aZ(Q){let $=[];for(let[Z,J]of Q.entries()){let W=`turn.files[${Z}]`;if(!J||typeof J!=="object"||Array.isArray(J))return`${W} must be an object.`;let X={};for(let K of["fileId","attachmentId","name","mimeType"]){let z=J[K];if(z===void 0||z===null||z==="")continue;if(typeof z!=="string")return`${W}.${K} must be a string.`;X[K]=z}let{fileId:G,attachmentId:Y,name:V,mimeType:H}=X;if(G?.startsWith(x))return`${W}.fileId holds a gemi attachment id (${G}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(Y!==void 0&&!Y.startsWith(x))return`${W}.attachmentId is not a gemi attachment id: it must start with "${x}".`;if(!G&&!Y)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...G?{fileId:G}:{},...Y?{attachmentId:Y}:{},...V!==void 0?{name:V}:{},...H!==void 0?{mimeType:H}:{}})}return $}function rZ(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let J=Math.floor($.cursor);if(J>=0)return J+1;return}let Z=Q?.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 eZ(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function Q6(Q){let $=OQ(Q);for(let Z=Q.length-1;Z>=0;Z--){let J=Q[Z];if(J.role!=="user"||$.has(J.id))continue;let W="",X=[];for(let G of J.content){if(G.type==="text")W+=G.text;if(G.type==="file")X.push({...G.fileId?{fileId:G.fileId}:{},...G.attachmentId?{attachmentId:G.attachmentId}:{},...G.name?{name:G.name}:{},...G.mimeType?{mimeType:G.mimeType}:{}})}if(!W&&X.length===0)continue;return{index:Z,turn:{...W?{text:W}:{},...X.length>0?{files:X}:{}}}}return null}function Z3(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function vQ(){return M(403,hQ("permission","This run belongs to someone else.",403))}function $6(){return M(403,hQ("permission","A file in this turn was uploaded by someone else.",403))}function Z6(Q){if(!Array.isArray(Q))return[];let $=[];for(let Z of Q){let J=Z?.content;if(!Array.isArray(J))continue;for(let W of J)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}function M(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function J6(Q,$){if(typeof $!=="string"||$.length===0)return Q;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===Q||Q==="both"&&$==="storage")return $;if(Q==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${Q}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var J3=!1;function W6(){if(J3)return;J3=!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 X6=2147483647;function G6(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=X6))return Z;let J,W=new Promise((X)=>{J=setTimeout(X,$)});return Promise.race([Z,W]).finally(()=>clearTimeout(J))}var W3=!1;function V6(Q){if(W3||Bun.env.NODE_ENV!=="production")return;if(!(Q instanceof r))return;W3=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}export{a3 as toAgentTools,n as supportsStrict,Y6 as s,f9 as redactError,k9 as liveRuns,q3 as generate,m as defaultNonceStore,T9 as defaultFileOwners,PQ as defaultAttachmentStore,A9 as defaultAgentStore,_Q as ToolNamespace,O as ToolError,J9 as Skill,QQ as ScopedAttachments,$Q as SKILLS_NAMESPACE,uQ as RedisNonceStore,h as PendingEscalation,M9 as OpenAIProvider,z9 as OpenAIImageProvider,r as MemoryNonceStore,AQ as MemoryLiveRuns,xQ as MemoryFileOwners,LQ as MemoryAttachmentStore,EQ as MemoryAgentStore,JQ as LiveRunNotFoundError,H6 as JSONSchemaError,d as InvalidAttachmentScopeError,SQ as ImageRequestError,RQ as ImageProvider,H9 as ImageModel,o as FrameCursorEvictedError,G9 as DEFAULT_MAX_RUN_DURATION_MS,S9 as AzureOpenAIProvider,B9 as AzureOpenAIImageProvider,e as AttachmentNotFoundError,y as AgentTool,a as AgentRunError,TQ as AgentProvider,B3 as AgentController,V9 as Agent};
|
|
19
19
|
|
|
20
|
-
//# debugId=
|
|
20
|
+
//# debugId=E653B01A6A6636E764756E2164756E21
|