gemi 0.104.0 → 0.106.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/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +8 -1
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +6 -0
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +14 -14
- package/dist/ai/index.js.map +7 -7
- package/dist/ai/providers/request.d.ts +1 -1
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/providers/stream.d.ts.map +1 -1
- package/dist/ai/types.d.ts +41 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/auth/routes.d.ts +15 -73
- package/dist/auth/routes.d.ts.map +1 -1
- package/dist/chunk-48wh5mbp.js +17 -0
- package/dist/{chunk-mp3sxvcv.js.map → chunk-48wh5mbp.js.map} +3 -3
- package/dist/{chunk-2p1wc6g8.js → chunk-70e5fypb.js} +1 -1
- package/dist/{chunk-7y2y8rxx.js → chunk-k6rd1nd4.js} +1 -1
- package/dist/{chunk-ag8mk3p3.js → chunk-qxg2dnnr.js} +2 -2
- package/dist/{chunk-ag8mk3p3.js.map → chunk-qxg2dnnr.js.map} +1 -1
- package/dist/{chunk-sryxt8df.js → chunk-tnp1sc4j.js} +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/ApiRouter.d.ts +89 -17
- package/dist/http/ApiRouter.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 +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-mp3sxvcv.js +0 -17
- /package/dist/{chunk-2p1wc6g8.js.map → chunk-70e5fypb.js.map} +0 -0
- /package/dist/{chunk-7y2y8rxx.js.map → chunk-k6rd1nd4.js.map} +0 -0
- /package/dist/{chunk-sryxt8df.js.map → chunk-tnp1sc4j.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ab as i9,Bb as M$,Cb as S$,Db as N3,zb as T}from"../chunk-wc46df4w.js";import{Ne as C3,Qe as O3,df as E1,ef as x1,ff as r,gf as KQ,uf as q3,wf as QQ,xf as d}from"../chunk-3cxbvrts.js";import{Af as uQ,Bf as cQ,yf as P3}from"../chunk-j9deswmn.js";import{Ff as RQ}from"../chunk-ayss2f8c.js";import{Lg as LQ}from"../chunk-xnggfm0s.js";import"../chunk-0fney17e.js";import"../chunk-ma5rmcbe.js";import"../chunk-1xzdexbq.js";class h extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${x3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class zQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function x3(Q){let $=o9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function o9(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 A(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 k(Q){if(Q instanceof zQ)return{code:"provider_error",message:Q.message,retryable:!0};if(v3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof h)return w3(Q.status,o9(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 w3(Q,$,Z){let J=$?.message??Z,W=($?.code??"").toLowerCase(),X=($?.type??"").toLowerCase(),G=`${W} ${X} ${J}`.toLowerCase();if(Q===429){let V=W==="insufficient_quota"||G.includes("quota");return{code:"rate_limited",message:J,retryable:!V}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(b3(G))return{code:"context_length_exceeded",message:J,retryable:!1};if(I3(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 b3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function I3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function v3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class E extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function y(Q,$){if($.aborted)return Promise.reject(new E);return new Promise((Z,J)=>{let W=()=>J(new E);$.addEventListener("abort",W,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",W))})}function M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function R(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 BQ(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 DQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:r(Q)}}function UQ(Q,$){let Z=Q.safeParse(BQ($));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 FQ(Q){if(Q.length>0)Q[0];return Q}function e(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 jQ(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 f3(Q){return mQ(Q)}async function mQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await y3(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")h3(Z,J.error,$.origin);if(Q.throwOnError)throw new $Q({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function h3(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,W={...Z,generateId:Q,error:$},X=!1;try{QQ.error(J,W),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.error(J,W)}async function y3(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=M(),G="stop",V,H={},K="";try{let U=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:DQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let j=await y(Promise.resolve(U.next()),W);if(j.done)break;let D=j.value;switch(D.type){case"output-delta":K+=D.delta;break;case"text-delta":e(J,"text",D.delta);break;case"reasoning-delta":jQ(J,D.id,D.delta);break;case"finish":if(X=R(X,D.usage),!V)G=D.reason;break;case"error":G="error",V=D.error,H=A(D);break}}}finally{if(W.aborted)Promise.resolve(U.return?.()).catch(()=>{})}}catch(B){if(B instanceof E||W.aborted)G="aborted",V=g3(W);else G="error",V=Q.provider.normalizeError(B),H=A(B)}let Y=!1,z;if(!V)if(G==="length")V={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(!K.trim())V={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let B=UQ(Q.output,K);if(B.ok===!0)Y=!0,z=B.value;else V=B.error}if(Y)J.content.push({type:"output",value:z});else if(K)e(J,"text",K);for(let B of J.content)if((B.type==="text"||B.type==="reasoning")&&typeof B.text==="string")B.text=FQ(B.text);if(J.finishReason=G,J.usage=X,Z.push(J),Y)return{ok:!0,output:z,messages:Z,usage:X,finishReason:G};return{ok:!1,error:{...V,...H},messages:Z,usage:X,finishReason:G}}function g3(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 u3,hkdfSync as c3,randomBytes as n9,timingSafeEqual as m3}from"crypto";class ZQ{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 pQ{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=LQ(),$=Q.bound(d)?Q.make(d).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 l=new ZQ;var dQ="agt2",PQ="agt1",s9=[dQ,PQ],lQ=86400000,p3=Date.now()+lQ;function t9(Q){return Q<=p3}var a9="gemi.ai.pending-call.v1",r9="gemi.ai.nested-run.v1",d3="gemi.ai.execution-receipt.v1",l3="gemi.ai.signing",CQ=new Map;function JQ(Q,$){let Z=iQ($),J=`${Q}\x00${Z}`,W=CQ.get(J);if(!W){if(W=Buffer.from(c3("sha256",Z,l3,Q,32)),CQ.size>64)CQ.clear();CQ.set(J,W)}return W}function iQ(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 I(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(I).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${I($[J])}`).join(",")}}`}function i3(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function g(Q,$){return u3("sha256",Q).update(i3($)).digest()}function e9(Q,$){let Z=Buffer.from(Q.split(".")[4],"base64url");return Z.length===$.length&&m3(Z,$)}function oQ(Q){return I(Q??null)}function Q$(Q,$,Z){return[dQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input),I(Q.path??[]),oQ(Q.subject)]}function o3(Q,$,Z){let J=[PQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input)];if(Q.path&&Q.path.length>0)J.push(I(Q.path));return J}var $$=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),n3=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function Z$(Q,$={}){let Z=JQ(a9,$.secret),W=($.now??Date.now())+($.ttlMs??lQ),X=n9(12).toString("base64url"),G=g(Z,Q$(Q,X,W)).toString("base64url");return[dQ,$$(Q.runId),X,W.toString(36),G].join(".")}function nQ(Q){return qQ(Q,s9)}function qQ(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:n3(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function J$(Q,$,Z={}){let J=qQ(Q,s9);if(!J)return{ok:!1,reason:"malformed"};if(J.version===PQ&&!t9(J.expiresAt))return{ok:!1,reason:"forged"};let W=J.version===PQ?g(iQ(Z.secret),o3($,J.nonce,J.expiresAt)):g(JQ(a9,Z.secret),Q$($,J.nonce,J.expiresAt));if(!e9(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 sQ="agn2",OQ="agn1",W$=[sQ,OQ];function X$(Q,$,Z){return[...G$(Q,$,Z,sQ),oQ(Q.subject)]}function G$(Q,$,Z,J=OQ){return[J,Q.runId,I(Q.path),Q.nestedRunId,$,String(Z),I([...Q.open].sort()),I(Q.input)]}function V$(Q,$={}){let Z=JQ(r9,$.secret),W=($.now??Date.now())+($.ttlMs??lQ),X=n9(12).toString("base64url"),G=g(Z,X$(Q,X,W)).toString("base64url");return[sQ,$$(Q.runId),X,W.toString(36),G].join(".")}function H$(Q,$,Z={}){let J=qQ(Q,W$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===OQ&&!t9(J.expiresAt))return{ok:!1,reason:"forged"};let W={...$,runId:J.runId},X=J.version===OQ?g(iQ(Z.secret),G$(W,J.nonce,J.expiresAt)):g(JQ(r9,Z.secret),X$(W,J.nonce,J.expiresAt));if(!e9(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 Y$(Q,$,Z={}){let J=JQ(d3,Z.secret);return g(J,[Q,$.runId,$.toolCallId,$.name,$.kind,I($.input),I($.path??[]),oQ($.subject)]).toString("base64url")}function K$(Q,$){return B$($,nQ(Q))}function z$(Q,$){return B$($,qQ(Q,W$))}async function B$(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class WQ extends T{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class i extends T{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function tQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new i("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 f="gemi_att_";function aQ(){return`${f}${crypto.randomUUID()}`}class XQ{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;tQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new WQ(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new WQ(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=aQ(),J=$.mimeType??Q.type??"",W=$.name??(Q instanceof File?Q.name:Z),X=await this.storage.put({name:rQ(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 rQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class NQ{rows=new Map;async put(Q,$){tQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){tQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var _Q=new NQ;var eQ=new TextEncoder;function D$(Q){return`id: ${Q.seq}
|
|
2
|
+
import{Ab as o9,Bb as S$,Cb as R$,Db as _3,zb as T}from"../chunk-wc46df4w.js";import{Ne as P3,Qe as q3,df as w1,ef as b1,ff as e,gf as zQ,uf as N3,wf as $Q,xf as d}from"../chunk-3cxbvrts.js";import{Af as cQ,Bf as mQ,yf as O3}from"../chunk-j9deswmn.js";import{Ff as TQ}from"../chunk-ayss2f8c.js";import{Lg as CQ}from"../chunk-xnggfm0s.js";import"../chunk-0fney17e.js";import"../chunk-ma5rmcbe.js";import"../chunk-1xzdexbq.js";class h extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${w3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class BQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function w3(Q){let $=n9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function n9(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 A(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 k(Q){if(Q instanceof BQ)return{code:"provider_error",message:Q.message,retryable:!0};if(f3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof h)return b3(Q.status,n9(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 b3(Q,$,Z){let J=$?.message??Z,W=($?.code??"").toLowerCase(),X=($?.type??"").toLowerCase(),G=`${W} ${X} ${J}`.toLowerCase();if(Q===429){let H=W==="insufficient_quota"||G.includes("quota");return{code:"rate_limited",message:J,retryable:!H}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(I3(G))return{code:"context_length_exceeded",message:J,retryable:!1};if(v3(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 I3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function v3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function f3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class E extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function y(Q,$){if($.aborted)return Promise.reject(new E);return new Promise((Z,J)=>{let W=()=>J(new E);$.addEventListener("abort",W,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",W))})}function M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function R(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 DQ(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 UQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:e(Q)}}function FQ(Q,$){let Z=Q.safeParse(DQ($));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 jQ(Q){if(Q.length>0)Q[0];return Q}function QQ(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 LQ(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 h3(Q){return pQ(Q)}async function pQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await g3(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")y3(Z,J.error,$.origin);if(Q.throwOnError)throw new ZQ({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function y3(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,W={...Z,generateId:Q,error:$},X=!1;try{$Q.error(J,W),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.error(J,W)}async function g3(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=M(),G="stop",H,K={},V="";try{let D=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:UQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let j=await y(Promise.resolve(D.next()),W);if(j.done)break;let U=j.value;switch(U.type){case"output-delta":V+=U.delta;break;case"text-delta":QQ(J,"text",U.delta);break;case"reasoning-delta":LQ(J,U.id,U.delta);break;case"finish":if(X=R(X,U.usage),!H)G=U.reason;break;case"error":G="error",H=U.error,K=A(U);break}}}finally{if(W.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(Y){if(Y instanceof E||W.aborted)G="aborted",H=u3(W);else G="error",H=Q.provider.normalizeError(Y),K=A(Y)}let z=!1,B;if(!H)if(G==="length")H={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(!V.trim())H={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let Y=FQ(Q.output,V);if(Y.ok===!0)z=!0,B=Y.value;else H=Y.error}if(z)J.content.push({type:"output",value:B});else if(V)QQ(J,"text",V);for(let Y of J.content)if((Y.type==="text"||Y.type==="reasoning")&&typeof Y.text==="string")Y.text=jQ(Y.text);if(J.finishReason=G,J.usage=X,Z.push(J),z)return{ok:!0,output:B,messages:Z,usage:X,finishReason:G};return{ok:!1,error:{...H,...K},messages:Z,usage:X,finishReason:G}}function u3(Q){return Q.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}import{createHmac as c3,hkdfSync as m3,randomBytes as s9,timingSafeEqual as p3}from"crypto";class JQ{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 dQ{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=CQ(),$=Q.bound(d)?Q.make(d).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 l=new JQ;var lQ="agt2",OQ="agt1",t9=[lQ,OQ],iQ=86400000,d3=Date.now()+iQ;function a9(Q){return Q<=d3}var r9="gemi.ai.pending-call.v1",e9="gemi.ai.nested-run.v1",l3="gemi.ai.execution-receipt.v1",i3="gemi.ai.signing",PQ=new Map;function WQ(Q,$){let Z=oQ($),J=`${Q}\x00${Z}`,W=PQ.get(J);if(!W){if(W=Buffer.from(m3("sha256",Z,i3,Q,32)),PQ.size>64)PQ.clear();PQ.set(J,W)}return W}function oQ(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 I(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(I).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${I($[J])}`).join(",")}}`}function o3(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function g(Q,$){return c3("sha256",Q).update(o3($)).digest()}function Q$(Q,$){let Z=Buffer.from(Q.split(".")[4],"base64url");return Z.length===$.length&&p3(Z,$)}function nQ(Q){return I(Q??null)}function $$(Q,$,Z){return[lQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input),I(Q.path??[]),nQ(Q.subject)]}function n3(Q,$,Z){let J=[OQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input)];if(Q.path&&Q.path.length>0)J.push(I(Q.path));return J}var Z$=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),s3=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function J$(Q,$={}){let Z=WQ(r9,$.secret),W=($.now??Date.now())+($.ttlMs??iQ),X=s9(12).toString("base64url"),G=g(Z,$$(Q,X,W)).toString("base64url");return[lQ,Z$(Q.runId),X,W.toString(36),G].join(".")}function sQ(Q){return NQ(Q,t9)}function NQ(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:s3(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function W$(Q,$,Z={}){let J=NQ(Q,t9);if(!J)return{ok:!1,reason:"malformed"};if(J.version===OQ&&!a9(J.expiresAt))return{ok:!1,reason:"forged"};let W=J.version===OQ?g(oQ(Z.secret),n3($,J.nonce,J.expiresAt)):g(WQ(r9,Z.secret),$$($,J.nonce,J.expiresAt));if(!Q$(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 tQ="agn2",qQ="agn1",X$=[tQ,qQ];function G$(Q,$,Z){return[...V$(Q,$,Z,tQ),nQ(Q.subject)]}function V$(Q,$,Z,J=qQ){return[J,Q.runId,I(Q.path),Q.nestedRunId,$,String(Z),I([...Q.open].sort()),I(Q.input)]}function H$(Q,$={}){let Z=WQ(e9,$.secret),W=($.now??Date.now())+($.ttlMs??iQ),X=s9(12).toString("base64url"),G=g(Z,G$(Q,X,W)).toString("base64url");return[tQ,Z$(Q.runId),X,W.toString(36),G].join(".")}function Y$(Q,$,Z={}){let J=NQ(Q,X$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===qQ&&!a9(J.expiresAt))return{ok:!1,reason:"forged"};let W={...$,runId:J.runId},X=J.version===qQ?g(oQ(Z.secret),V$(W,J.nonce,J.expiresAt)):g(WQ(e9,Z.secret),G$(W,J.nonce,J.expiresAt));if(!Q$(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 K$(Q,$,Z={}){let J=WQ(l3,Z.secret);return g(J,[Q,$.runId,$.toolCallId,$.name,$.kind,I($.input),I($.path??[]),nQ($.subject)]).toString("base64url")}function z$(Q,$){return D$($,sQ(Q))}function B$(Q,$){return D$($,NQ(Q,X$))}async function D$(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class XQ extends T{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class i extends T{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function aQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new i("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 f="gemi_att_";function rQ(){return`${f}${crypto.randomUUID()}`}class GQ{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;aQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new XQ(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new XQ(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=rQ(),J=$.mimeType??Q.type??"",W=$.name??(Q instanceof File?Q.name:Z),X=await this.storage.put({name:eQ(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 eQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class _Q{rows=new Map;async put(Q,$){aQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){aQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var MQ=new _Q;var Q9=new TextEncoder;function U$(Q){return`id: ${Q.seq}
|
|
3
3
|
data: ${JSON.stringify(Q.event)}
|
|
4
4
|
|
|
5
|
-
`}var
|
|
5
|
+
`}var t3=5000,a3=`: keepalive
|
|
6
6
|
|
|
7
|
-
`;function
|
|
8
|
-
${await
|
|
7
|
+
`;function $9(Q,$=t3){let Z=null,J=!1,W=()=>{if(J)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,J)return;try{Q.enqueue(Q9.encode(a3))}catch{X();return}W()},$)},X=()=>{if(J=!0,Z!==null)clearTimeout(Z);Z=null};return W(),{touch:W,stop:X}}function r3(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function F$(Q,$=200){let Z=Q[Symbol.asyncIterator](),J=-1,W,X=new ReadableStream({start(G){W=$9(G)},async pull(G){try{let H=await Z.next();if(H.done){W.stop(),G.close();return}J=H.value.seq,G.enqueue(Q9.encode(U$(H.value))),W.touch()}catch(H){let K={type:"error",error:QZ(H)};W.stop(),G.enqueue(Q9.encode(U$({seq:J+1,event:K}))),G.close()}},cancel(G){W.stop(),Z.return?.(G)}});return new Response(X,{status:$,headers:r3()})}var e3=new Set(["frame_cursor_evicted","live_run_not_found"]);function QZ(Q){let $=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof $==="string"&&e3.has($))return{code:"unknown",message:Q.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",Q),{code:"unknown",message:"The run's stream failed.",retryable:!1}}class u extends Error{pending;path;nested;constructor(Q){super(`A nested agent run is waiting on the user for ${Q.pending.length} tool call(s).`);this.name="PendingEscalation",this.pending=Q.pending,this.path=Q.path,this.nested=Q.nested}}class c{name;description;inputSchema;outputSchema;requiresApproval;deferred;answeredBy;timeoutMs;execute;constructor(Q){this.name=Q.name,this.description=Q.description,this.inputSchema=Q.inputSchema,this.outputSchema=Q.outputSchema,this.requiresApproval=Q.requiresApproval===!0,this.deferred=Q.deferred===!0,this.answeredBy=Q.answeredBy==="client"?"client":"server",this.execute=Q.execute??void 0,this.timeoutMs=Q.timeoutMs}static create(Q){if(typeof Q.inputSchema!=="function")Y9(Q.inputSchema,`The tool "${Q.name}"`,"inputSchema");if(Q.timeoutMs!==void 0)W9(Q.timeoutMs,`The tool "${Q.name}"`,"timeoutMs");return new c(Q)}static ask(Q){return c.create({name:Q.name,description:Q.description,inputSchema:V9,outputSchema:Q.outputSchema,answeredBy:"client"})}}var V9={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=V9.safeParse(Q);if($.ok===!1)throw Error($.errors.join(", "));return $.value},safeParse(Q){if(typeof Q!=="object"||Q===null||typeof Q.question!=="string")return{ok:!1,errors:["question: expected a string"]};return{ok:!0,value:{question:Q.question}}}};class o{name;description;tools;deferred;constructor(Q){this.name=Q.name,this.description=Q.description,this.tools=Q.tools,this.deferred=Q.deferred===!0}static create(Q){return new o(Q)}}class H9{name;description;instructions;files;constructor(Q){this.name=Q.name,this.description=Q.description,this.instructions=Q.instructions,this.files=Q.files}static create(Q){return new H9(Q)}}var VQ="skills",$Z="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.";function Y9(Q,$,Z){let J=Q?.toJSONSchema?.();if(J?.type==="object")return;let W=!J?"no JSON Schema":J.anyOf?"a union (`anyOf`) \u2014 `s.union(...)`":J.type!==void 0?`a schema of type ${JSON.stringify(J.type)}`:"an unconstrained schema (`s.json()`)";throw Error(`${$} declares an \`${Z}\` whose root is ${W}, but the provider only accepts an object there (OpenAI rejects \`anyOf\` or a non-object at the root of tool parameters and structured output). Wrap it in an object, e.g. \`s.object({ value: s.union([...]) })\`, and read \`.value\` off the result.`)}function W9(Q,$,Z){if(typeof Q==="number"&&Q>0)return;throw Error(`${$} sets \`${Z}\` to ${String(Q)}, but it has to be a positive number of milliseconds. Use \`null\` for no limit.`)}function j$(Q){if(Q===void 0)return;if(Q===null||!Number.isFinite(Q))return null;return Q}var ZZ=2147483647;function L$(Q,$){if(Q===null||Q>ZZ)return()=>{};let Z=setTimeout($,Q);return()=>clearTimeout(Z)}function Z9(Q){if(Q<1000)return`${Q}ms`;if(Q<60000)return`${+(Q/1000).toFixed(1)}s`;return`${+(Q/60000).toFixed(1)}m`}var K9={type:"object",properties:{},required:[],additionalProperties:!1},z9=600000;class ZQ extends Error{code;retryable;status;requestId;toolCallId;runId;result;constructor(Q){super(Q.error.message);this.name="AgentRunError",this.code=Q.error.code,this.retryable=Q.error.retryable,this.status=Q.error.status,this.requestId=Q.error.requestId,this.toolCallId=Q.error.toolCallId,this.runId=Q.runId,this.result=Q}}var JZ=8,WZ=3;class B9{name;tools;skills;provider;output;instructions;maxSteps;maxDepth;reasoning;maxRunDurationMs;config;constructor(Q){this.name=Q.name,this.instructions=Q.instructions,this.provider=Q.provider,this.tools=Q.tools??[],this.skills=Q.skills??[],this.output=Q.output,this.maxSteps=Q.maxSteps??JZ,this.maxDepth=Q.maxDepth??WZ,this.reasoning=Q.reasoning;let $=j$(Q.maxRunDurationMs);this.maxRunDurationMs=$===void 0?z9:$;let{registry:Z,providerTools:J}=XZ(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:Z,providerTools:J,output:Q.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,logErrors:Q.logErrors??!0,maxRunDurationMs:$}}static create(Q){if(Q.output)Y9(Q.output,`The agent "${Q.name}"`,"output");if(Q.maxRunDurationMs!=null)W9(Q.maxRunDurationMs,`The agent "${Q.name}"`,"maxRunDurationMs");return new B9(Q)}stream(Q){let $={...this.config,provider:Q.provider??this.config.provider,maxSteps:Q.maxSteps??this.config.maxSteps,reasoning:Q.reasoning??this.config.reasoning,maxOutputTokens:Q.maxOutputTokens??this.config.maxOutputTokens,temperature:Q.temperature??this.config.temperature,maxRunDurationMs:Q.maxRunDurationMs!==void 0?j$(Q.maxRunDurationMs):this.config.maxRunDurationMs};if(Q.maxRunDurationMs!=null)W9(Q.maxRunDurationMs,`Agent.stream for "${this.name}"`,"maxRunDurationMs");return new k$($,Q)}}function X9(Q){let $=Q.inputSchema;return{name:Q.tool.name,description:Q.tool.description,parameters:$?$.toJSONSchema():K9,strict:$?e($):!0,deferred:Q.deferred}}function J9(Q){return typeof Q.inputSchema==="function"?void 0:Q.inputSchema}function XZ(Q,$){let Z=new Map,J=[],W=(X)=>{if(Z.has(X.tool.name))throw Error(`Two tools are named "${X.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(X.tool.name,X)};for(let X of Q){if(X instanceof o){if(X.name===VQ)throw Error(`"${VQ}" is reserved for the namespace skills are lowered into. Rename the namespace \u2014 silently shadowing it would make every skill unreachable with no error to read.`);let H=[];for(let K of X.tools){let V={tool:K,namespace:X.name,deferred:X.deferred||K.deferred,inputSchema:J9(K)};W(V),H.push(X9(V))}J.push({name:X.name,description:X.description,tools:H});continue}let G={tool:X,deferred:X.deferred,inputSchema:J9(X)};W(G),J.push(X9(G))}if($.length>0){let X=[];for(let G of $){let H=GZ(G);W({tool:H,namespace:VQ,deferred:!1,inputSchema:J9(H)}),X.push({name:G.name,description:G.description,parameters:K9,strict:!0,deferred:!1})}J.push({name:VQ,description:$Z,tools:X})}return{registry:Z,providerTools:J}}function GZ(Q){return c.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>K9,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Z=[typeof Q.instructions==="function"?await Q.instructions():Q.instructions];for(let J of Q.files??[])Z.push(`--- ${J} ---
|
|
8
|
+
${await VZ(J)}`);return Z.join(`
|
|
9
9
|
|
|
10
|
-
`)}})}async function
|
|
11
|
-
data: ${JSON.stringify(
|
|
10
|
+
`)}})}async function VZ(Q){try{return await Bun.file(Q).text()}catch($){return`(could not be read: ${$.message})`}}function HZ(Q){return typeof Q==="object"&&Q!==null&&typeof Q.next==="function"&&Symbol.asyncIterator in Q}function C$(Q,$){let Z=[...Q],J=new Map(Z.map((W,X)=>[W.id,X]));for(let W of $){let X=J.get(W.id);if(X===void 0)J.set(W.id,Z.length),Z.push(W);else Z[X]=W}return Z}function SQ(Q){let $=new Set;for(let J of Q)for(let W of J.content)if(W.type==="tool-result")$.add(W.toolCallId);let Z=new Set;for(let J of Q)for(let W of J.content)if(W.type==="tool-call"&&!$.has(W.toolCallId))Z.add(W.toolCallId);return Z}function P$(Q){for(let $=Q.length-1;$>=0;$--){let Z=Q[$].content;for(let J=Z.length-1;J>=0;J--){let W=Z[J];if(W.type==="output"&&W.partial!==!0)return W.value}}return}function O$(Q,$){return $===void 0?`"${Q}"`:`"${Q}" labelled "${$}"`}function T$(Q){return Q.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function YZ(Q){if(Q.prompt!==void 0)return`user:${Q.prompt}`;let $=Q.messages?.[0];return $?`${$.role}:${T$($)}`:null}function RQ(Q){let $=new Set;for(let Z of Q)for(let J of Z.content){if(J.type!=="tool-call")continue;for(let W of J.attachments??[])if("shown"in W&&W.shown)$.add(W.shown.messageId)}return $}var q$=1;function KZ(Q,$,Z){let J=Z.mimeType||$.type||"";if(J&&Q.attachment.mimeType!==J)return`was ${JSON.stringify(Q.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(J)} on the replay`;let W=Boolean(Z.showModel);if(W!==Boolean(Q.shown))return W?"was stored without showModel on the turn that escalated and asks for showModel on the replay":"was stored with showModel on the turn that escalated and asks for a plain put on the replay";return null}function zZ(Q,$,Z){if(Q.agent!==$.name||Q.label!==Z.label)return`was ${O$(Q.agent,Q.label)} on the turn that escalated and is ${O$($.name,Z.label)} on the replay`;let J=YZ(Z),W=Q.messages[0],X=W?`${W.role}:${T$(W)}`:null;if(J!==null&&X!==null&&J!==X)return`was started with ${JSON.stringify(X)} on the turn that escalated and with ${JSON.stringify(J)} on the replay`;return null}function N$(Q,$){let Z=Q??[];if(Z.length<$.length)return null;for(let J=0;J<$.length;J++)if(Z[J]!==$[J])return null;return Z.slice($.length)}class G9{read;create;fill;index=0;replayable;constructor(Q,$,Z){this.read=Q;this.create=$;this.fill=Z;this.replayable=Q()?.length??0}next(){let Q=this.index++;return{at:Q,recorded:Q<this.replayable?this.read()?.[Q]:void 0,write:($)=>{let Z=this.read()??this.create();if(this.fill)for(let J=Z.length;J<Q;J++)Z[J]=this.fill();Z[Q]=$}}}}class k${runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=M();finishReason="stop";failure;output;stopReason;timedOutAfter;cancelDeadline=()=>{};settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor(Q,$){this.config=Q,this.params=$,this.context=$.context??{},this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages];let Z=$.nesting;if(this.depth=Z?.depth??0,this.maxDepth=Z?.maxDepth??Q.maxDepth,this.chain=Z?.chain??[Q.name],this.signingRunId=Z?.signingRunId??this.runId,this.pathPrefix=Z?.signingPath??[],this.onPending=Z?.onPending??"escalate",$.signal)if($.signal.aborted)this.controller.abort();else $.signal.addEventListener("abort",()=>this.stop(),{once:!0});let J=Q.maxRunDurationMs!==void 0?Q.maxRunDurationMs:Z?null:z9;this.cancelDeadline=L$(J,()=>this.expire(J)),this.settled=this.execute(),TQ.getStore()?.waitUntil(this.settled)}emit(Q){if(this.ended)return;this.buffer.push({seq:++this.seq,event:Q}),this.wake()}wake(){let Q=[...this.waiters];this.waiters.clear();for(let $ of Q)$()}nextFrame(){return new Promise((Q)=>this.waiters.add(Q))}async*frames(Q=0){let $=Q>0?Q-1:0;for(;;){while($<this.buffer.length)yield this.buffer[$++];if(this.ended)return;await this.nextFrame()}}async*[Symbol.asyncIterator](){for await(let Q of this.frames())yield Q.event}toResponse(Q){let $=this.frames(Q?.from),Z=new TextEncoder,J=!1,W,X=new ReadableStream({start:async(G)=>{W=$9(G);try{for await(let H of $){if(J)break;G.enqueue(Z.encode(`id: ${H.seq}
|
|
11
|
+
data: ${JSON.stringify(H.event)}
|
|
12
12
|
|
|
13
|
-
`)),W.touch()}}catch{}W.stop();try{G.close()}catch{}},cancel:()=>{J=!0,W.stop()}});return new Response(X,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(Q){if(!Q?.throwOnError)return this.settled;return this.settled.then(($)=>{if($.error)throw new
|
|
13
|
+
`)),W.touch()}}catch{}W.stop();try{G.close()}catch{}},cancel:()=>{J=!0,W.stop()}});return new Response(X,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(Q){if(!Q?.throwOnError)return this.settled;return this.settled.then(($)=>{if($.error)throw new ZQ({...$,error:$.error});return $})}stop(Q){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Q?.reason,this.controller.abort()}expire(Q){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=Q,this.stopReason=`The run reached its time limit of ${Z9(Q)} and was stopped.`,this.controller.abort(new DOMException(this.stopReason,"TimeoutError"))}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{let $=await this.resolveToolSchemas(),Z=$?[]:await this.ingestTurn();if($)this.fail($),this.finishReason="error";else if(Z.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:Z});else await this.loop()}catch($){if($ instanceof E||this.controller.signal.aborted)await this.finalizeAborted();else this.fail(this.config.provider.normalizeError($),A($)),await this.finalizeMessage("error"),this.finishReason="error"}this.cancelDeadline(),this.emit({type:"usage",usage:this.usage}),this.emit({type:"run-end",runId:this.runId,finishReason:this.finishReason}),this.ended=!0,this.wake();let Q=this.finishReason==="error"?this.failure:void 0;if(Q&&this.config.logErrors)this.logFailure(Q);return{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,output:this.output,...Q?{error:Q}:{}}}async resolveToolSchemas(){let Q=[...this.config.registry.values()].filter((K)=>!K.inputSchema);if(Q.length===0)return;let $={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,signal:this.controller.signal},Z=new Map,J=await Promise.all(Q.map(async(K)=>{try{let V=K.tool.inputSchema,z=await V($);Y9(z,`The tool "${K.tool.name}"`,"inputSchema"),Z.set(K.tool.name,z);return}catch(V){return`"${K.tool.name}": ${V instanceof Error?V.message:String(V)}`}}));if(this.controller.signal.aborted)throw new E;let W=J.filter((K)=>K!==void 0);if(W.length>0)return{code:"tool_error",message:`Could not resolve the input schema of ${W.join("; ")}`,retryable:!1};let X=new Map;for(let[K,V]of this.config.registry)X.set(K,Z.has(K)?{...V,inputSchema:Z.get(K)}:V);let G=(K)=>Z.has(K.name)?X9(X.get(K.name)):K,H=this.config.providerTools.map((K)=>("tools"in K)?{...K,tools:K.tools.map(G)}:G(K));this.config={...this.config,registry:X,providerTools:H};return}fail(Q,$={}){let Z={...Q,...$};this.failure=Z,this.emit({type:"error",error:this.redact(Z,{source:"run",failure:Z})})}redact(Q,$){let Z=S$(this.params.redactError,Q,$,(J)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:J}));return R$(Z,Q),Z}logFailure(Q){let $=`[gemi/ai] agent "${this.config.name}" run failed (${Q.code}${Q.status!==void 0?` ${Q.status}`:""}): ${Q.message}`;this.writeLog($,{error:Q})}logToolFailure(Q,$){let Z=$ instanceof Error?$.message:String($);this.writeLog(`[gemi/ai] agent "${this.config.name}" tool "${String(Q.name)}" threw: ${Z}`,{toolCallId:Q.toolCallId,error:$})}writeLog(Q,$){let Z={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},...$},J=!1;try{$Q.error(Q,Z),J=!0}catch{}if(!J||Bun.env.NODE_ENV==="development")console.error(Q,Z)}async loop(){let Q=Math.max(1,this.config.maxSteps);for(let $=1;$<=Q;$++){let Z=this.startMessage(),J=await this.runStep(Z);if(J.error){this.fail(J.error,J.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let W=Z.content.filter((G)=>G.type==="tool-call");if(W.length===0){this.finishReason=J.reason,await this.finalizeMessage(J.reason);return}let X=await this.runTools(Z,W,$);if(X.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:X});return}if($===Q){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(J.reason)}}startMessage(){let Q={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()};return this.current=Q,this.history.push(Q),this.produced.push(Q),this.emit({type:"message-start",messageId:Q.id,role:"assistant"}),Q}async finalizeMessage(Q){let $=this.current;if(!$)return;this.current=null;let Z=this.outputTruncated;if(this.outputTruncated=!1,$.finishReason=Q,Z)$.outputTruncated=!0;for(let J of $.content)if(J.type==="text"||J.type==="reasoning"){if(typeof J.text==="string")J.text=jQ(J.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Q,...Z?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{}}),await this.report($),await this.reportDeferred()}async report(Q){if(!this.params.onMessage)return;try{await this.params.onMessage(Q)}catch{}}async runStep(Q){let $=this.controller.signal,Z=this.config.provider,J={reason:"stop"},W=new Map,X=[],G=()=>{if(X.length===0)return{};let B=X;return X=[],{toolSearches:B}},H="",V=Z.stream({messages:this.historyForProvider(Q),systemPrompt:await this.systemPrompt(),tools:this.config.providerTools.length>0?this.config.providerTools:void 0,output:this.config.output?UQ(this.config.output):void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:$})[Symbol.asyncIterator]();for(;;){let B=await y(Promise.resolve(V.next()),$);if(B.done)break;let Y=B.value;switch(Y.type){case"text-delta":{QQ(Q,"text",Y.delta),this.emit({type:"text-delta",messageId:Q.id,delta:Y.delta});break}case"reasoning-delta":{LQ(Q,Y.id,Y.delta),this.emit({type:"reasoning-delta",messageId:Q.id,delta:Y.delta,id:Y.id});break}case"output-delta":{H+=Y.delta,this.emit({type:"output-delta",messageId:Q.id,delta:Y.delta,snapshot:DQ(H)});break}case"tool-search":{X.push({namespaces:Y.namespaces,loaded:Y.loaded,...Y.arguments!==void 0?{arguments:Y.arguments}:{}}),this.emit({type:"tool-search",loaded:Y.loaded});break}case"tool-call-delta":{let D=W.get(Y.toolCallId)??{name:Y.name,args:""};D.args+=Y.argsDelta,D.name=Y.name||D.name,D.namespace=Y.namespace||D.namespace,W.set(Y.toolCallId,D),this.emit({type:"tool-call",messageId:Q.id,part:{type:"tool-call",toolCallId:Y.toolCallId,name:D.name,input:DQ(D.args),partial:!0,...D.namespace?{namespace:D.namespace}:{}}});break}case"tool-call":{let D=Y.namespace||W.get(Y.toolCallId)?.namespace;W.delete(Y.toolCallId);let j={type:"tool-call",toolCallId:Y.toolCallId,name:Y.name,input:M$(Y.args),...D?{namespace:D}:{},...G()};Q.content.push(j),this.emit({type:"tool-call",messageId:Q.id,part:j});break}case"finish":{if(this.usage=R(this.usage,Y.usage),Q.usage=R(Q.usage??M(),Y.usage),!J.error)J={reason:Y.reason};break}case"error":{J={reason:"error",error:Y.error,detail:A(Y)};break}case"file-rejected":{this.markFileRejected(Y.fileId,Y.message,A(Y));break}}}for(let[B,Y]of W){let D={type:"tool-call",toolCallId:B,name:Y.name,input:M$(Y.args),...Y.namespace?{namespace:Y.namespace}:{},...G()};Q.content.push(D),this.emit({type:"tool-call",messageId:Q.id,part:D})}let z=J.reason==="length";if(z)this.outputTruncated=!0;if(this.config.output&&H&&!J.error&&!z){let B=FQ(this.config.output,H);if(B.ok===!0)this.output=B.value,Q.content.push({type:"output",value:B.value});else this.emit({type:"error",error:B.error})}return J}async systemPrompt(){let Q=[this.config.instructions,this.params.instructions].filter(($)=>Boolean($&&$.trim()));return Q.length>0?Q.join(`
|
|
14
14
|
|
|
15
|
-
`):void 0}async runTools(Q,$,Z){let J=[],W=[];for(let X of $){let G=this.config.registry.get(String(X.name));if(!G){this.addResult(Q,{type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(X.name)}".`,toolCallId:X.toolCallId,retryable:!0}});continue}let V=G.inputSchema.safeParse(X.input);if(V.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(X.name)}": ${V.errors.join(", ")}`,toolCallId:X.toolCallId,retryable:!0}});continue}X.input=V.value;let H=N$(G.tool);if(H){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(X));continue}J.push({toolCallId:X.toolCallId,name:X.name,input:V.value,kind:H,signature:Z$(this.claimsFor(X.toolCallId,String(X.name),H,V.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}W.push(this.executeTool(G,Q.id,X,V.value,Z).then(async(K)=>{this.addResult(Q,K),await this.settleShown(X.toolCallId)}).catch((K)=>{if(K instanceof u){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(X));return}J.push(...K.pending);return}}))}return await y(Promise.all(W).then(()=>{return}),this.controller.signal),J}claimsFor(Q,$,Z,J){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:J,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0,subject:this.params.subject??null}}deniedByPolicy(Q){return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"refused",reason:`"${String(Q.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Q,$,Z,J,W,X){let G=Q.tool.timeoutMs;if(G===void 0)return this.runToolBody(Q,$,Z,J,W,X,this.controller.signal,()=>!1);let V=new AbortController,H=this.controller.signal,K=()=>V.abort(H.reason);if(H.aborted)K();else H.addEventListener("abort",K,{once:!0});let Y=!1,z=this.runToolBody(Q,$,Z,J,W,X,V.signal,()=>Y),B=()=>{},U=new Promise((j)=>{B=j$(G,()=>{let D=`"${String(Z.name)}" did not finish within ${$9(G)} (timeoutMs: ${G}) and was cancelled.`;V.abort(new DOMException(D,"TimeoutError")),j({type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"timeout",message:D,toolCallId:Z.toolCallId,retryable:!0}})})});z.catch(()=>{});try{return await Promise.race([z,U])}finally{Y=!0,B()}}async runToolBody(Q,$,Z,J,W,X,G,V){let H=this.toolFiles(Z,G),K={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:G,step:W,depth:this.depth,resumed:X!==void 0,attachments:H.attachments,generateImage:H.generateImage,editImage:H.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,G,X),generate:(Y)=>this.generateForTool(Y,G,Z.toolCallId)};try{let Y=Q.tool.execute(J,K),z;if(VZ(Y)){let B=await Y.next();while(!B.done){if(V())throw Y.return(void 0).catch(()=>{}),new E;this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:B.value}),B=await Y.next()}z=B.value}else z=await Y;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:z}}catch(Y){if(Y instanceof E||this.controller.signal.aborted)throw new E;if(Y instanceof u)throw Y;let z=Y instanceof T;if(!z&&this.config.logErrors)this.logToolFailure(Z,Y);let B={code:"tool_error",message:Y instanceof Error?Y.message:String(Y),toolCallId:Z.toolCallId,retryable:z?Y.retryable:!0};return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:this.redact(B,{source:"tool",toolName:String(Z.name),cause:Y})}}}async generateForTool(Q,$,Z){let J=this.controller.signal;return mQ({...Q,signal:Q.signal?AbortSignal.any([$,Q.signal]):$},{origin:{agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},toolCallId:Z},settled:(W)=>{if(this.usage=R(this.usage,W.usage),J.aborted)throw new E}})}nestedRunner(Q,$,Z,J){let W=new X9(()=>$.nested,()=>$.nested=[]);return async(X,G={})=>{let{at:V,recorded:H,write:K}=W.next();if(H){let Y=KZ(H,X,G);if(Y)throw new T(`Nested run ${V} of "${String($.name)}" ${Y}. `+"runAgent is memoized by call index, so a body whose runAgent calls depend on a condition that changed between turns cannot be resumed \u2014 the answer would be paired with a different sub-run. "+"Make the sequence of runAgent calls, and what each one is asked, the same every time this tool runs, or branch on ctx.resumed.");if(H.finishReason!=="awaiting-input")return{runId:H.runId,agent:H.agent,messages:H.messages,finishReason:H.finishReason??"stop",usage:H.usage??M(),output:C$(H.messages),nested:H}}return this.runNested(Q,$,Z,X,G,K,H,J?.answers??[])}}async runNested(Q,$,Z,J,W,X,G,V){let H=[...this.chain,J.name];if(this.chain.includes(J.name))throw new T(`"${J.name}" is already running further up this chain: ${H.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let K=this.depth+1;if(K>this.maxDepth)throw new T(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${K}: ${H.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let Y=W.label,z=[...this.pathPrefix,$.toolCallId],B=this.onPending==="deny"?"deny":W.onPending??"escalate",U=G!==void 0,j=U?MQ(G.messages):new Set,D=U?V.filter((q)=>{let C=q$(q.path,z);if(C===null)return!1;return j.has(C.length>0?C[0]:q.toolCallId)}):[],L=J.stream({messages:U?G.messages:W.messages??[],turn:U?{toolResults:D}:W.prompt?{text:W.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:Z,threadId:this.params.threadId,redactError:this.params.redactError,nonces:this.params.nonces,receipts:this.params.receipts,subject:this.params.subject,instructions:W.instructions,maxOutputTokens:W.maxOutputTokens,temperature:W.temperature,runId:U?G.runId:void 0,nesting:{depth:K,maxDepth:this.maxDepth,chain:H,signingRunId:this.signingRunId,signingPath:z,onPending:B}}),F=[],S=(q)=>this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:L.runId,agent:J.name,label:Y,event:q}),N=(async()=>{for await(let q of L){if(q.type==="awaiting-input")F=q.pending;if(S(q),q.type==="run-start"&&!U)for(let C of W.messages??[])S({type:"message",message:C});if(q.type==="error")this.emit({type:"error",error:q.error,nested:{toolCallId:$.toolCallId,runId:L.runId,agent:J.name}})}})(),v=(async()=>{let q=await L.result();await N;let C=U?L$(G.messages,q.messages):L$(W.messages??[],q.messages),O={runId:L.runId,agent:J.name,label:Y,messages:C,finishReason:q.finishReason,usage:U?R(G.usage??M(),q.usage):q.usage,...q.finishReason==="awaiting-input"?{signature:V$({runId:this.signingRunId,path:z,nestedRunId:L.runId,open:[...MQ(C)],input:$.input,subject:this.params.subject??null})}:{}};return X(O),this.usage=R(this.usage,q.usage),{result:q,record:O}})(),w=v.then(()=>{return},()=>{return});this.nestedSettling.add(w);let _,b;try{({result:_,record:b}=await v)}finally{this.nestedSettling.delete(w)}if(this.controller.signal.aborted)throw new E;if(_.finishReason==="awaiting-input"){if(F.length===0)throw new T(`"${J.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Q,part:$,resent:!0}),new u({pending:F,path:z,nested:b})}return{runId:b.runId,agent:J.name,messages:b.messages,finishReason:_.finishReason,usage:b.usage??M(),output:_.output??C$(b.messages),..._.error?{error:_.error}:{},nested:b}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolFiles(Q,$){let Z=this.params.attachments??null,J=new X9(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),W=()=>{if(!Z)throw new i("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return Z},X=async(K,Y,z)=>{let B=W(),U=Y.mimeType||K.type||"",j=Y.name??(K instanceof File?K.name:"attachment"),D;if(Y.showModel){let F=this.config.provider;if(!F.capabilities.fileInput)throw new T(`"${String(Q.name)}" asked to show a file to ${F.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);D=await F.upload(new File([K],j,{type:U||void 0}))}return{attachment:await B.put(K,{name:j,mimeType:U,fileId:D}),...z?{generated:z}:{},...D?{shown:{fileId:D,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},G=(K,Y,z)=>{let B=K.generated?"image":"put";if(B===Y)return;throw new T(`Attachment ${z} of "${String(Q.name)}" was ${B==="image"?"a generated image":"a stored file"} on the first attempt and is ${Y==="image"?"a generated image":"a stored file"} now. ctx.attachments.put, ctx.generateImage and ctx.editImage share one memo indexed by call order within a tool call, so the sequence has to be the same every time this tool runs. Branch on ctx.resumed if it cannot be.`)},V=async(K,Y,z)=>{let{at:B,recorded:U,write:j}=J.next();if(U&&"attachment"in U){if(G(U,"image",B),U.shown)this.queueShown(Q.toolCallId,U);return{attachment:U.attachment,size:U.generated.size,mimeType:U.attachment.mimeType,usage:U.generated.usage}}let D=await z();this.usage=R(this.usage,D.usage);let L=D.mimeType==="image/jpeg"?"jpg":"png",F=await X(D.image,{name:Y.name??`${K.name}.${L}`,mimeType:D.mimeType,...Y.showModel?{showModel:!0}:{}},{size:D.size,usage:D.usage});if(j(F),F.shown)this.queueShown(Q.toolCallId,F);return{attachment:F.attachment,size:D.size,mimeType:D.mimeType,usage:D.usage}},H=async(K)=>typeof K==="string"?await W().file(K):K;return{generateImage:(K,Y)=>V(K,Y,()=>K.generate({...Y,signal:$})),editImage:(K,Y)=>V(K,Y,async()=>{let{images:z,mask:B,...U}=Y;return await K.edit({...U,images:await Promise.all(z.map(H)),...B?{mask:await H(B)}:{},signal:$})}),attachments:{get:(K)=>W().get(K),read:(K)=>W().read(K),file:(K)=>W().file(K),put:async(K,Y={})=>{let{at:z,recorded:B,write:U}=J.next();if(B&&"attachment"in B){G(B,"put",z);let D=YZ(B,K,Y);if(D)throw new T(`Attachment ${z} of "${String(Q.name)}" ${D}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(B.shown)this.queueShown(Q.toolCallId,B);return B.attachment}let j=await X(K,Y);if(U(j),j.shown)this.queueShown(Q.toolCallId,j);return j.attachment}}}}toolTurn(Q){let $=this.history.findIndex((X)=>X.id===Q),Z=SQ(this.history),J;for(let X=$-1;X>=0;X--){let G=this.history[X];if(G.role!=="user"||Z.has(G.id))continue;J=G;break}let W=[];for(let X of J?.content??[]){if(X.type!=="file")continue;let G=X.attachmentId;if(typeof G!=="string"||!G.startsWith(f))continue;if(!W.includes(G))W.push(G)}return Object.freeze({attachments:Object.freeze(W)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let J=this.shownQueue.get(Q)??[];if(J.some((W)=>W.id===Z.messageId))return;J.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set(Q,J)}async settleShown(Q){let $=this.shownQueue.get(Q);if(!$||$.length===0)return;if(this.shownQueue.delete(Q),this.ended||this.controller.signal.aborted)return;for(let Z of $){if(this.history.some((J)=>J.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider(Q){let $=this.history.filter((X)=>X!==Q),Z=SQ($),J=[];for(let X of $){if(!Z.has(X.id))continue;for(let G of X.content)if(G.type==="file")J.push(G)}if(J.length<=O$)return $;let W=new Set(J.slice(0,J.length-O$));return $.map((X)=>{if(!X.content.some((G)=>G.type==="file"&&W.has(G)))return X;return{...X,content:X.content.map((G)=>G.type==="file"&&W.has(G)?{type:"text",text:`[A ${G.mimeType||"file"} produced by a tool (attachment ${G.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:G)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let J=new Set,W=new Set,X=new Map;for(let G of Q?.toolResults??[]){let V=`${(G.path??[]).join("/")}#${G.toolCallId}`;if(W.has(V))continue;W.add(V);let H=(B)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:B,toolCallId:G.toolCallId,retryable:!1}}),K=q$(G.path,this.pathPrefix);if(K===null){H(`The answer for "${G.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(K.length>0){let B=K[0],U=$.find((L)=>L.call.toolCallId===B);if(!U){H(`No pending tool call with id "${B}" to deliver a nested answer to.`);continue}let j=this.parkedBelow(U.call,K,G.toolCallId);if(j.ok===!1){let L=`The answer for "${G.toolCallId}" is addressed under "${B}", which`;H(j.reason==="unparked"?`${L} has no sub-agent run waiting on that question.`:j.reason==="expired"?`${L} parked a sub-agent run that has since expired. Ask again.`:`${L} carries a record of a parked sub-agent run the server did not sign.`);continue}let D=X.get(B);if(!D){if(!await this.spend(z$,j.signature)){H(`The answer for "${G.toolCallId}" is addressed under "${B}", which has already been re-entered on that record. Ask again.`);continue}D=[],X.set(B,D),J.add(B)}D.push(G);continue}let Y=$.find((B)=>B.call.toolCallId===G.toolCallId);if(!Y){H(`No pending tool call with id "${G.toolCallId}".`);continue}let z=await this.resolveAnswer(Y,G,Z);if(z===null)continue;if(J.add(G.toolCallId),z!=="open")this.attachToHistory(Y,z),await this.settleShown(G.toolCallId)}for(let[G,V]of X){let H=$.find((Y)=>Y.call.toolCallId===G),K=await this.reenter(H,V,Z);if(K)this.attachToHistory(H,K),await this.settleShown(G)}for(let G of $){if(J.has(G.call.toolCallId))continue;this.attachToHistory(G,{type:"tool-result",toolCallId:G.call.toolCallId,name:G.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if(Q&&(Q.text||Q.files&&Q.files.length>0)){let J={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((W)=>({type:"file",...W.fileId?{fileId:W.fileId}:{},name:W.name,mimeType:W.mimeType,...W.attachmentId?{attachmentId:W.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};if(this.history.push(J),this.produced.push(J),this.depth>0)this.emit({type:"message",message:J});else if(Q.localId)this.emit({type:"message-id",localId:Q.localId,messageId:J.id});await this.report(J)}return Z}parkedBelow(Q,$,Z){let J=$.length>1?$[1]:Z,W=[...this.pathPrefix,Q.toolCallId],X=(Q.nested??[]).find((V)=>V.finishReason==="awaiting-input"&&MQ(V.messages).has(J));if(!X)return{ok:!1,reason:"unparked"};if(typeof X.signature!=="string")return{ok:!1,reason:"unsigned"};let G=H$(X.signature,{path:W,nestedRunId:X.runId,open:[...MQ(X.messages)],input:Q.input,subject:this.params.subject??null});if(G.ok===!1)return{ok:!1,reason:G.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:X.signature}}async reenter(Q,$,Z){let J=String(Q.call.name),W=this.config.registry.get(J);if(!W||!W.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${J}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let X=W.inputSchema.safeParse(Q.call.input);if(X.ok===!1)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${J}": ${X.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let G=this.amendCall(Q);G.input=X.value;try{return await y(this.executeTool(W,Q.message.id,G,X.value,0,{answers:$}),this.controller.signal)}catch(V){if(V instanceof u)return Z.push(...V.pending),null;throw V}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),J={...Q.call,nested:(Q.call.nested??[]).map((W)=>({...W})),...Q.call.attachments?{attachments:Q.call.attachments.map((W)=>({...W}))}:{}};if(Z>=0)$.content[Z]=J;return this.unreported.add($),J}openCalls(){let Q=new Set;for(let Z of this.history)for(let J of Z.content)if(J.type==="tool-result")Q.add(J.toolCallId);let $=[];for(let Z of this.history)for(let J of Z.content)if(J.type==="tool-call"&&!Q.has(J.toolCallId))$.push({message:Z,call:J});return $}async spend(Q,$){try{return await Q($,this.params.nonces??l)}catch(Z){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not spend a nonce`,{error:Z}),!1}}async recordReceipt(Q,$){let Z=await $;try{await Q.store.complete(Q.id,Z,Q.expiresAt)}catch(J){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record a tool receipt`,{error:J})}return Z}async resolveAnswer(Q,$,Z){let J=Q.call,W=String(J.name),X=this.config.registry.get(W),G=(z)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:J.toolCallId,retryable:!1}}),null};if(!X)return G(`The tool "${W}" no longer exists, so its answer cannot be checked.`);let V=N$(X.tool);if(!V)return G(`"${W}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return G(`The answer for "${W}" carried no signature.`);let H=nQ($.signature);if(!H)return G(`The signature for "${W}" is malformed.`);let K=J$($.signature,{...this.claimsFor(J.toolCallId,W,V,J.input),runId:H.runId});if(K.ok===!1)return G(K.reason==="expired"?`The approval for "${W}" has expired. Ask again.`:`The answer for "${W}" does not match the call the server made.`);let Y;if(this.params.receipts&&V==="approval"&&"approve"in $&&$.approve===!0){let z=this.params.receipts,B=Y$(this.config.name,{...this.claimsFor(J.toolCallId,W,V,J.input),runId:H.runId}),U;try{U=await z.claim(B,H.expiresAt)}catch(j){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not claim a tool receipt`,{error:j}),G(`The approval for "${W}" could not be checked. Ask again.`)}if(U.status==="replay")return{...U.result,toolCallId:J.toolCallId,name:J.name};if(U.status==="blocked")return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"tool_error",message:`"${W}" was already approved and started, and its result is not recorded yet: it is still running, or it stopped before finishing. It was not run again.`,toolCallId:J.toolCallId,retryable:!1}};Y={store:z,id:B,expiresAt:H.expiresAt}}if(!await this.spend(K$,$.signature))return await Y?.store.release(Y.id).catch((z)=>{this.writeLog(`[gemi/ai] agent "${this.config.name}" could not release a tool receipt`,{error:z})}),G(`The answer for "${W}" has already been used. Ask again.`);if("approve"in $){if(V!=="approval")return G(`"${W}" is answered by the client, not approved.`);if($.approve===!0){let z=this.amendCall(Q),B=this.executeTool(X,Q.message.id,z,z.input,0);try{return await y(Y?this.recordReceipt(Y,B):B,this.controller.signal)}catch(U){if(U instanceof u)return Z.push(...U.pending),"open";throw U}}return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(V==="approval")return G(`"${W}" is approved, not answered: the server produces its result.`);let z=X.tool.outputSchema,B=z?z.safeParse($.output):{ok:!0,value:$.output};if(B.ok===!1)return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${W}" did not match its output schema: ${B.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"ok",output:B.value}}return G(`The answer for "${W}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let Z=this.amend(Q.message);Z.content.push($),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:$})}markFileRejected(Q,$,Z){for(let G of this.history){if(!G.content.some((K)=>K.type==="file"&&K.fileId===Q&&!K.providerRejected))continue;let H=this.produced.includes(G)?G:this.amend(G);if(H.content=H.content.map((K)=>K.type==="file"&&K.fileId===Q&&!K.providerRejected?{...K,providerRejected:!0}:K),H!==this.current)this.unreported.add(H)}if(!this.config.logErrors)return;let J=`[gemi/ai] agent "${this.config.name}": the provider refused file ${Q}${Z.status!==void 0?` (${Z.status})`:""}; it was left out of the request and will not be sent again: ${$}`,W={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},fileId:Q,...Z},X=!1;try{QQ.warning(J,W),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.warn(J,W)}amend(Q){let $=this.amended.get(Q.id);if($)return $;let Z={...Q,content:[...Q.content]},J=this.history.indexOf(Q);if(J>=0)this.history[J]=Z;return this.produced.push(Z),this.amended.set(Q.id,Z),Z}async reportDeferred(){let Q=[...this.unreported];this.unreported.clear();for(let $ of Q)await this.report($)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let $ of this.openCalls()){if($.message===this.current)continue;this.attachToHistory($,{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let Q=this.current;if(Q){let $=new Set(Q.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...Q.content]){if(Z.type!=="tool-call"||$.has(Z.toolCallId))continue;delete Z.partial,this.addResult(Q,{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"stopped",reason:this.stopReason})}}if(this.timedOutAfter!==void 0){this.fail({code:"timeout",message:`The run did not finish within its time limit of ${$9(this.timedOutAfter)} (maxRunDurationMs: ${this.timedOutAfter}) and was stopped.`,retryable:!0}),this.finishReason="error",await this.finalizeMessage("error");return}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function N$(Q){if(Q.answeredBy==="client")return Q.inputSchema===G9?"question":"client";return Q.requiresApproval?"approval":null}function _$(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}var zZ=/^[A-Za-z0-9_-]{1,64}$/;function BZ(Q,$){let Z=DZ($)?$:{filter:$},J=Z.deferred===!0,W=Q.descriptors(Z.filter);if(!Z.namespaces)return W.map((Y)=>B9(Q,Y,J));let X=Object.entries(Z.namespaces),G=new Set(Q.descriptors().flatMap((Y)=>Y.tags));for(let[Y,z]of X){if(!zZ.test(Y))throw Error(`toAgentTools: "${Y}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof z?.description!=="string"||z.description.trim()==="")throw Error(`toAgentTools: the namespace "${Y}" needs a description. It is what the model reads to decide whether to look inside.`);if(!G.has(Y))throw Error(`toAgentTools: no tool is tagged "${Y}", so its namespace would be empty.`)}let V=new Map(X.map(([Y])=>[Y,[]])),H=[];for(let Y of W){let z=X.find(([B])=>Y.tags.includes(B))?.[0];if(z===void 0)H.push(B9(Q,Y,J));else V.get(z).push(B9(Q,Y,!1))}let K=[];for(let[Y,z]of X){let B=V.get(Y);if(B.length===0)continue;K.push(o.create({name:Y,description:z.description,tools:B,deferred:z.deferred??J}))}return[...K,...H]}function DZ(Q){return typeof Q==="object"&&Q!==null&&(("filter"in Q)||("namespaces"in Q)||("deferred"in Q))}function B9(Q,$,Z){return c.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Z,execute:(J,W)=>{let X=RQ.getStore()?.req;if(!X)throw new T(`"${$.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return Q.execute({kind:"local",req:X},$.name,J,W)}})}function UZ(Q){if(Q==="auto")return;let $=/^(\d+)x(\d+)$/.exec(Q);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(Q)}.`);let Z=Number($[1]),J=Number($[2]);if(Z%16!==0||J%16!==0)throw Error(`Image size ${Q} is not supported: width and height must both be divisible by 16.`);if(Math.max(Z/J,J/Z)>3)throw Error(`Image size ${Q} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function k$(Q,$){if(Q.size!==void 0)try{UZ(Q.size)}catch(Z){throw Error(`${$}: ${Z.message}`)}if(Q.background==="transparent"&&Q.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(Q.compression!==void 0){let Z=Q.compression;if(!Number.isInteger(Z)||Z<0||Z>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Z}.`)}}function A$(Q,$){if(Q instanceof File)return Q;let Z=Q.type||"image/png",J=Z==="image/jpeg"?"jpg":Z.split("/")[1]??"png";return new File([Q],`${$}.${J}`,{type:Z})}class D9{name;provider;settings;constructor(Q){let{name:$,provider:Z,...J}=Q;k$(J,`ImageModel "${$}"`),this.name=$,this.provider=Z,this.settings=J}static create(Q){return new D9(Q)}async generate(Q){let $=this.merge(Q);return E$(await this.provider.generate({prompt:Q.prompt,...$,signal:Q.signal}))}async edit(Q){let $=this.merge(Q);return E$(await this.provider.edit({prompt:Q.prompt,...$,images:Q.images.map((Z,J)=>A$(Z,`image-${J}`)),...Q.mask?{mask:A$(Q.mask,"mask")}:{},signal:Q.signal}))}merge(Q){let $={...this.settings,...Q.size!==void 0?{size:Q.size}:{},...Q.quality!==void 0?{quality:Q.quality}:{},...Q.background!==void 0?{background:Q.background}:{},...Q.format!==void 0?{format:Q.format}:{},...Q.compression!==void 0?{compression:Q.compression}:{}};return k$($,`ImageModel "${this.name}"`),$}}function E$(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}function m(Q){return typeof process>"u"?void 0:process.env?.[Q]}var FZ="preview";function x$(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function jZ(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function TQ(Q,$={}){return{base:(Q.baseURL??m("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let J=Q.apiKey??m("OPENAI_API_KEY");return{...J?{authorization:`Bearer ${J}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}function LZ(Q){let $=Q.baseURL??Q.endpoint??m("AZURE_OPENAI_ENDPOINT");if($)return x$($);let Z=Q.resourceName??m("AZURE_OPENAI_RESOURCE_NAME")??m("AZURE_RESOURCE_NAME");return Z?x$(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function kQ(Q,$={}){let Z=Q.apiVersion??m("AZURE_OPENAI_API_VERSION")??FZ;return{base:`${LZ(Q)}${jZ(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let J=Q.apiKey??m("AZURE_OPENAI_API_KEY");return{...J?{"api-key":J}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}var CZ=500,b$=20000;function PZ(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let J=Date.parse(Z);if(Number.isNaN(J))return;return Math.max(0,J-$)}function w$(Q,$){let Z=Math.min(b$,CZ*2**Q);return Math.round(Z*(0.5+$()*0.5))}function OZ(Q){return Q===429||Q===408||Q===409||Q>=500}function qZ(Q,$){return OZ(Q)&&k($).retryable}function I$(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function NZ(Q,$){return new Promise((Z,J)=>{let W=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(W),J(I$($))},{once:!0})})}async function VQ(Q,$,Z){let J=Z.fetchImpl??((Y,z)=>fetch(Y,z)),W=Z.sleep??NZ,X=Z.random??Math.random,G=Z.now??Date.now,V=Math.max(0,Z.maxRetries),H=async(Y)=>{let z=Z.signal;if(!z)return await W(Y);z.throwIfAborted();let B;try{await Promise.race([W(Y,z),new Promise((U,j)=>{B=()=>j(I$(z)),z.addEventListener("abort",B,{once:!0})})])}finally{if(B)z.removeEventListener("abort",B)}},K;for(let Y=0;Y<=V;Y++){Z.signal?.throwIfAborted();let z=new AbortController,B=()=>z.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",B,{once:!0});let U=!1,j=Z.timeoutMs>0?setTimeout(()=>{U=!0,z.abort()},Z.timeoutMs):void 0,D;try{D=await J(Q,{...$,signal:z.signal})}catch(N){if(j!==void 0)clearTimeout(j);if(Z.signal?.removeEventListener("abort",B),Z.signal?.aborted)throw N;if(K=U?new zQ(Z.timeoutMs):N,U&&Z.retryTimeouts===!1)throw K;if(Y===V)throw K;await H(w$(Y,X));continue}if(j!==void 0)clearTimeout(j);if(D.ok)return D;Z.signal?.removeEventListener("abort",B);let L=await _Z(D),F=new h(D.status,L,D.headers.get("x-request-id")??void 0);if(Y===V||!qZ(D.status,F))throw F;let S=PZ(D.headers.get("retry-after"),G());await H(S===void 0?w$(Y,X):Math.min(S,b$)),K=F}throw K??Error("Provider request failed with no response.")}async function _Z(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var U9=300000;function F9(Q){return{generationsUrl:`${Q.base}/images/generations${Q.query}`,editsUrl:`${Q.base}/images/edits${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}class AQ extends Error{code;retryable;constructor(Q,$={}){super(Q.message,$);this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable}}var MZ={png:"image/png",jpeg:"image/jpeg"};function SZ(Q){let $=Number(Q?.input_tokens??0),Z=Number(Q?.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q?.total_tokens??$+Z)},W=Q?.input_tokens_details?.image_tokens;if(typeof W==="number")J.imageInputTokens=W;let X=Q?.output_tokens_details?.image_tokens;if(typeof X==="number")J.imageOutputTokens=X;return J}function RZ(Q){let $=atob(Q),Z=new Uint8Array($.length);for(let J=0;J<$.length;J++)Z[J]=$.charCodeAt(J);return Z}function TZ(Q){let Z=Q?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new AQ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let J=typeof Q.output_format==="string"?Q.output_format:"png";return{bytes:RZ(Z),mimeType:MZ[J]??`image/${J}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:SZ(Q.usage)}}async function v$(Q,$,Z,J){let W;try{W=await VQ(Q,$,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:J.signal,fetchImpl:Z.fetchImpl})}catch(X){if(J.signal?.aborted)throw X;throw new AQ(k(X),{cause:X})}return TZ(await W.json())}async function f$(Q,$,Z={}){return await v$(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},Q,Z)}async function h$(Q,$,Z={}){return await v$(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:$},Q,Z)}class EQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await f$(this.endpoint(),this.body(Q),{signal:Q.signal})}async edit(Q){let $=new FormData;for(let[Z,J]of Object.entries(this.body(Q)))if(J!==void 0)$.set(Z,String(J));for(let Z of Q.images)$.append("image[]",Z,Z.name);if(Q.mask)$.set("mask",Q.mask,Q.mask.name);return await h$(this.endpoint(),$,{signal:Q.signal})}body(Q){return{model:this.modelName(),prompt:Q.prompt,...Q.size?{size:Q.size}:{},...Q.quality?{quality:Q.quality}:{},...Q.background?{background:Q.background}:{},...Q.format?{output_format:Q.format}:{},...Q.compression!==void 0?{output_compression:Q.compression}:{}}}normalizeError(Q){return k(Q)}}var y$=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class j9 extends EQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new j9(Q,$)}static models(){return y$}endpoint(){return F9(TQ(this.config,{timeoutMs:U9}))}}class L9 extends EQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new L9(Q,$)}static models(){return y$}modelName(){return this.config.deployment??this.model}endpoint(){return F9(kQ(this.config,{timeoutMs:U9}))}}var c$=3;function C9(Q){let $=new Map;for(let Z of Q)for(let J of Z.content??[]){if(J.type!=="file"||!J.fileId||$.has(J.fileId))continue;$.set(J.fileId,{name:J.name,mimeType:J.mimeType})}return $}function m$(Q,$,Z=new Map){if(!($ instanceof h))return[];if($.status!==400&&$.status!==404)return[];let J=AZ($.body);if(!J)return[];let W=kZ(Q.input);if(W.length===0)return[];let X=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(J.param??"");if(X){let K=Q.input[Number(X[1])],Y=O9(K)[Number(X[2])],z=Y&&typeof Y.file_id==="string"?Y.file_id:void 0;if(z)return[z]}let G=J.message??"",V=u$(W.map((K)=>K.fileId).filter((K)=>EZ(G,K)));if(V.length>0)return V;let H=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(G);if(H){let K=H[1].toLowerCase()==="image type"?"input_image":"input_file",Y=H[2].toLowerCase(),z=u$(W.filter((U)=>U.type===K).map((U)=>U.fileId)),B=z.filter((U)=>(Z.get(U)?.name??"").trim().toLowerCase().endsWith(`.${Y}`));if(B.length===1)return B;if(B.length===0&&z.length===1)return z}return[]}function p$(Q,$,Z=new Map){return{...Q,input:Q.input.map((J)=>{let W=O9(J);if(!W.some((X)=>g$(X,$)))return J;return{...J,content:W.map((X)=>g$(X,$)?{type:"input_text",text:P9(Z.get(String(X.file_id))?.name)}:X)}})}}function P9(Q){return`[${Q?`attachment ${JSON.stringify(Q)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function g$(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function O9(Q){let $=Q?.content;return Array.isArray($)?$:[]}function kZ(Q){let $=[];for(let Z of Q)for(let J of O9(Z))if(typeof J.file_id==="string"&&J.file_id)$.push({type:String(J.type),fileId:J.file_id});return $}function AZ(Q){if(!Q||typeof Q!=="object")return null;let $=Q,Z=$.error&&typeof $.error==="object"?$.error:Q;return{message:typeof Z.message==="string"?Z.message:void 0,param:typeof Z.param==="string"?Z.param:void 0}}function EZ(Q,$){let Z=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Z}($|[^A-Za-z0-9_-])`).test(Q)}function u$(Q){return[...new Set(Q)]}async function*xZ(Q){let $="",Z="",J=[],W,X=()=>{if(J.length===0&&!Z)return null;let H={event:Z,data:J.join(`
|
|
16
|
-
`),id:W};return Z="",J=[],W=void 0,
|
|
17
|
-
`);while(
|
|
18
|
-
`)}}if($.length>0){let H=G($);if(H)yield H}let V=X();if(V)yield V}async function*d$(Q,$={}){let Z=new Map,J=new Set,W=!1,X,G=(V,H)=>({type:"finish",reason:V,usage:H,...X?{model:X}:{}});for await(let V of xZ(Q)){if(V.data==="[DONE]")break;let H;try{H=JSON.parse(V.data)}catch{continue}let K=typeof H.type==="string"?H.type:V.event,Y=H.response?.model;if(typeof Y==="string"&&Y)X=Y;switch(K){case"response.output_text.delta":{let z=String(H.delta??"");if(!z)break;yield $.structuredOutput?{type:"output-delta",delta:z}:{type:"text-delta",delta:z};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let z=String(H.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:H.item_id};break}case"response.output_item.added":{let z=H.item;if(!z)break;if(z.type==="function_call"){let B=String(z.id??H.item_id??z.call_id??"");Z.set(B,{callId:String(z.call_id??B),name:String(z.name??""),namespace:typeof z.namespace==="string"&&z.namespace?z.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let z=Z.get(String(H.item_id??""));if(!z)break;let B=String(H.delta??"");if(!B)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:B,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(H.item_id??""),B=Z.get(z);if(!B)break;B.done=!0,yield{type:"tool-call",toolCallId:B.callId,name:B.name,args:String(H.arguments??""),...B.namespace?{namespace:B.namespace}:{}};break}case"response.output_item.done":{let z=H.item;if(!z)break;if(z.type==="function_call"){let B=String(z.id??H.item_id??z.call_id??""),U=Z.get(B);if(U?.done)break;let j=(typeof z.namespace==="string"?z.namespace:"")||U?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??B),name:String(z.name??U?.name??""),args:String(z.arguments??""),...j?{namespace:j}:{}},U)U.done=!0;break}if(z.type==="tool_search_call"||z.type==="tool_search_output"){let B=wZ(z);if(B.loaded.length===0&&B.namespaces.length===0)break;let U=String(z.tool_search_call_id??z.id??"");if(J.has(U))break;J.add(U),yield{type:"tool-search",...B}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(H.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{W=!0,yield G("stop",q9(H.response?.usage));break}case"response.incomplete":{W=!0;let z=q9(H.response?.usage),B=H.response?.incomplete_details?.reason;if(B==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:bZ(H.response?.content_filters),retryable:!1}},yield G("error",z);break}yield G(B==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{W=!0;let z=H.response?.error??H.error??H;yield{type:"error",error:IZ(z)},yield G("error",q9(H.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 G("error",n())}function wZ(Q){let $=[],Z=[];return l$(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:N9($),namespaces:N9(Z)}}function l$(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:"",V=X.tools??X.functions;if(Array.isArray(V)){if(G)Z.push(G);l$(V,$,Z,J+1);continue}if(G)$.push(G)}}function N9(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function bZ(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,V]of Object.entries(X))if(V&&typeof V==="object"&&V.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: ${N9(Z).join(", ")}.`}function IZ(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 n(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function q9(Q){if(!Q)return n();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*i$(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 _9(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*M9(Q,$,Z){let J,W=$,X=new Set;for(let G=0;J===void 0;G++)try{J=await VQ(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(V){let H=G<c$?m$(W,V,Z.files).filter((Y)=>!X.has(Y)):[];if(H.length>0){let Y=k(V).message;for(let z of H)X.add(z),yield{type:"file-rejected",fileId:z,message:Y,...A(V)};W=p$(W,new Set(H),Z.files);continue}let K=k(V);if(K.code!=="aborted")yield{type:"error",error:K,...A(V)};yield{type:"finish",reason:K.code==="aborted"?"aborted":"error",usage:n()};return}try{yield*d$(i$(J.body),{structuredOutput:Z.structuredOutput})}catch(G){let V=k(G);if(V.code==="aborted"){yield{type:"finish",reason:"aborted",usage:n()};return}yield{type:"error",error:V},yield{type:"finish",reason:"error",usage:n()}}}async function S9(Q,$,Z="user_data"){let J=new FormData;J.set("purpose",Z),J.set("file",$);let X=await(await VQ(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 R9(Q){let $=vZ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=fZ($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:o$(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:o$(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function o$(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function vZ(Q){return Q.trim().toLowerCase()}function fZ(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 k9(Q,$){let{capabilities:Z}=$,J={model:$.model,input:hZ(Q.messages,Z),stream:!0};if(Q.systemPrompt)J.instructions=Q.systemPrompt;let W=iZ(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 hZ(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 V of J.content??[])switch(V.type){case"text":{if(!V.text)break;X.push(s(W,V.text));break}case"output":{if(V.partial)break;X.push(s(W,JSON.stringify(V.value)));break}case"file":{if(W==="assistant")break;let H=uZ(V);if(!$.fileInput){if(H)X.push(s(W,T9(V,!1)));break}if(V.fileId?.startsWith(f))throw Error(`FilePart.fileId holds a gemi attachment id (${V.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(!V.fileId&&!H)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(V.providerRejected){if(H)X.push(s(W,T9(V,!1)));X.push(s(W,P9(V.name)));break}if(H)X.push(s(W,T9(V,!!V.fileId)));if(V.fileId)X.push(cZ(V));break}case"reasoning":{G();let H=dZ(V);if(H)Z.push(H);break}case"tool-call":{if(V.partial)break;G(),Z.push({type:"function_call",call_id:V.toolCallId,name:String(V.name),arguments:JSON.stringify(V.input??{})});break}case"tool-result":{G(),Z.push({type:"function_call_output",call_id:V.toolCallId,output:lZ(V)});break}}G()}return gZ(Z)}var yZ="No result was recorded for this tool call. Assume it did not complete.";function gZ(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:yZ})}return W}function s(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function uZ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(f)?$:void 0}function T9(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 cZ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":mZ(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function mZ(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&pZ.has($[1])}var pZ=new Set(["jpeg","jpg","png","gif","webp"]);function dZ(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function lZ(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 n$(Q){return Array.isArray(Q.tools)}function iZ(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let W=[];for(let X of Q)if(n$(X))for(let G of X.tools)W.push(xQ(G,!1));else W.push(xQ(X,!1));return W}let Z=[],J=!1;for(let W of Q)if(n$(W)){let X=W.tools.map((G)=>{if(G.deferred)J=!0;return xQ(G,!0)});Z.push({type:"namespace",name:W.name,description:W.description,tools:X})}else{if(W.deferred)J=!0;Z.push(xQ(W,!0))}if(J)Z.push({type:"tool_search"});return Z}function xQ(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 t{static models(){return[]}normalizeError(Q){return k(Q)}}var s$=["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 A9 extends t{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=R9(Q),this.config=$}static model(Q,$){return new A9(Q,$)}static models(){return s$}stream(Q){let $=k9(Q,{model:this.model,capabilities:this.capabilities});return M9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:C9(Q.messages)})}upload(Q){return S9(this.endpoint(),Q)}endpoint(){return _9(TQ(this.config))}}class E9 extends t{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=R9(Q),this.config=$}static model(Q,$){return new E9(Q,$)}static models(){return s$}stream(Q){let $=k9(Q,{model:this.deployment(),capabilities:this.capabilities});return M9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:C9(Q.messages)})}upload(Q){return S9(this.endpoint(),Q,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return _9(kQ(this.config))}}class wQ{now;entries=new Map;constructor(Q=Date.now){this.now=Q}allow(Q,$){let Z=this.entries.get(Q);if(Z?.openUntil===void 0)return!0;let J=this.now();if(J<Z.openUntil)return!1;if(Z.probeUntil!==void 0&&J<Z.probeUntil)return!1;return Z.probeUntil=J+$.cooldownMs,!0}record(Q,$,Z){let J=this.entries.get(Q)??{failures:0},W=J.openUntil!==void 0;if($==="success")return this.entries.delete(Q),W?"closed":void 0;if($==="none"){delete J.probeUntil;return}if(J.failures+=1,this.entries.set(Q,J),W||J.failures>=Z.failures)return J.openUntil=this.now()+Z.cooldownMs,delete J.probeUntil,W?void 0:"open";return}state(Q){let $=this.entries.get(Q);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}function oZ(Q){switch(Q.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}var t$=Symbol("timed-out");class HQ extends t{model;capabilities;entries;options;circuit;constructor(Q,$={}){super();if(Q.length===0)throw Error("FallbackProvider needs at least one provider.");for(let J of Q)if(J.timeoutMs!==void 0&&!(J.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${J.provider.model} must be a positive number, got ${J.timeoutMs}.`);this.entries=[...Q];let Z=$.circuit;if(Z){let J=Z.failures??3,W=Z.cooldownMs??30000;if(!Number.isInteger(J)||J<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${J}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let X=new Set;for(let V of Q){let H=x9(V);if(X.has(H))throw Error(`FallbackProvider: two legs share the circuit key "${H}". Give one of them a \`circuitKey\`.`);X.add(H)}let G=Z.store??new wQ;this.options={...$,circuit:{...Z,store:G}},this.circuit={policy:{failures:J,cooldownMs:W},store:G,...Z.onStateChange?{onStateChange:Z.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=Q[0].provider.model,this.capabilities=nZ(Q.map((J)=>J.provider.capabilities))}static chain(Q,$){return new HQ(Q,$)}from(Q){if(!Number.isInteger(Q)||Q<0||Q>=this.entries.length)throw RangeError(`FallbackProvider.from(${Q}): the chain has ${this.entries.length} entries.`);return new HQ(this.entries.slice(Q),this.options)}leg(Q){let $=this.from(Q).entries[0];return new HQ([$],this.options)}upload(Q){return this.entries[0].provider.upload(Q)}normalizeError(Q){return this.entries[0].provider.normalizeError(Q)}stream(Q){return this.run(Q)}async*run(Q){let $,Z=Q.signal,J=0;for(let W=0;W<this.entries.length;W++){let X=this.entries[W],G=W===this.entries.length-1,V=X.provider.model;if(this.circuit&&!G&&!await this.allow(X))continue;J+=1;let H=!1,K=async(C)=>{if(H)return;H=!0,await this.record(W,X,C)},Y=new AbortController,z=()=>Y.abort(Z?.reason);if(Z?.aborted)Y.abort(Z.reason);else Z?.addEventListener("abort",z,{once:!0});let B=[],U=!1,j=!1,D,L,F,S=!1,N,v=!1,w=(C)=>{let O=$?R(R(M(),$),C.usage):C.usage;return $=void 0,{...C,usage:O}};try{N=X.provider.stream({...Q,...X.reasoning!==void 0?{reasoning:X.reasoning}:{},signal:Y.signal})[Symbol.asyncIterator]();let C=!0;for(;;){let O=C&&X.timeoutMs!==void 0?await sZ(N.next(),X.timeoutMs):await N.next();if(O===t$){S=!0,F={error:{code:"provider_error",message:`${V} sent nothing within ${X.timeoutMs}ms.`,retryable:!0}};break}if(C=!1,O.done){v=!0;break}let P=O.value;if(P.type==="finish"&&P.model)L=P.model;if(U){if(P.type==="finish")D=R(D??M(),P.usage),j=!0,yield w(P);else{if(P.type==="error")F={error:P.error};yield P}continue}if(oZ(P)){U=!0,await K("success"),yield*B.splice(0),yield P;continue}if(P.type==="error")F={error:P.error,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}};else if(P.type==="finish"){if(D=R(D??M(),P.usage),P.reason==="error"&&!F)F={error:{code:"provider_error",message:`${V} ended the call with an error and did not say which.`,retryable:!1}}}B.push(P)}}catch(C){let O=X.provider.normalizeError(C);if(U){if(O.code!=="aborted")yield{type:"error",error:O,...A(C)};this.report({index:W,model:V,responseModel:L,attempt:J,usage:D,outcome:w9(O),error:O}),yield w({type:"finish",reason:O.code==="aborted"?"aborted":"error",usage:M(),...L?{model:L}:{}});return}F={error:O,...A(C)}}finally{if(Z?.removeEventListener("abort",z),!v)Y.abort(),N?.return?.()?.catch(()=>{})}if(U){if(!j&&$)yield{type:"finish",reason:F?"error":"stop",usage:$},$=void 0;this.report({index:W,model:V,responseModel:L,attempt:J,usage:D,outcome:F?w9(F.error):"ok",...F?{error:F.error}:{}});return}if(Z?.aborted){await K("none"),this.report({index:W,model:V,responseModel:L,attempt:J,usage:D,outcome:"aborted"}),yield w({type:"finish",reason:"aborted",usage:D??M(),...L?{model:L}:{}});return}if(!F){await K("success"),this.report({index:W,model:V,responseModel:L,attempt:J,usage:D,outcome:"ok"});for(let C of B)yield C.type==="finish"?w(C):C;return}let _=!G&&F.error.code!=="aborted"&&this.shouldFallBack(F.error,{index:W,model:V,timedOut:S,...F.status!==void 0?{status:F.status}:{},...F.requestId!==void 0?{requestId:F.requestId}:{}});if(await K(_?"failure":"none"),this.report({index:W,model:V,responseModel:L,attempt:J,usage:D,outcome:_?"fallback":w9(F.error),error:F.error}),_){if(D)$=R($??M(),D);continue}let b=!1,q;for(let C of B){if(C.type==="finish"){q=C;continue}if(C.type==="error")b=!0;yield C}if(!b&&F.error.code!=="aborted")yield{type:"error",error:F.error,...F.status!==void 0?{status:F.status}:{},...F.requestId!==void 0?{requestId:F.requestId}:{}};yield w({type:"finish",reason:F.error.code==="aborted"?"aborted":q?.reason??"error",usage:D??M(),...L?{model:L}:{}});return}}async allow(Q){if(!this.circuit)return!0;try{return await this.circuit.store.allow(x9(Q),this.circuit.policy)}catch{return!0}}async record(Q,$,Z){if(!this.circuit)return;let J=x9($),W;try{W=await this.circuit.store.record(J,Z,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:Q,model:$.provider.model,key:J,state:W})}catch{}}shouldFallBack(Q,$){let Z=this.options.fallbackOn??((J)=>J.retryable);try{return Z(Q,$)}catch{return!1}}report(Q){if(Q.usage===void 0)delete Q.usage;if(Q.responseModel===void 0)delete Q.responseModel;try{this.options.onUsage?.(Q)}catch{}}}function x9(Q){return Q.circuitKey??Q.provider.model}function w9(Q){return Q.code==="aborted"?"aborted":"failed"}function nZ(Q){return{reasoning:Q.every(($)=>$.reasoning),structuredOutput:Q.every(($)=>$.structuredOutput),fileInput:Q.every(($)=>$.fileInput),parallelToolCalls:Q.every(($)=>$.parallelToolCalls),toolSearch:Q.every(($)=>$.toolSearch)}}function sZ(Q,$){let Z,J=new Promise((W)=>{Z=setTimeout(()=>W(t$),$)});return Promise.race([Q,J]).finally(()=>clearTimeout(Z))}async function tZ(Q,$,Z={}){let J=Z.samples??1;if(!Number.isInteger(J)||J<1)throw RangeError(`evalChain: samples must be a positive integer, got ${J}.`);let W=[];for(let X=0;X<Q.entries.length;X++){let G=Q.leg(X),V={index:X,model:G.model,results:[],errors:[]};for(let H=0;H<J;H++)try{V.results.push(await $(G,{index:X,sample:H}))}catch(K){V.errors.push({sample:H,error:K})}W.push(V)}return W}class a 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 YQ extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class bQ{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 YQ(Q);if($!==void 0&&$<Z.lostBefore)throw new a(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)=>b9($,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)=>b9($,X))}}catch(J){b9($,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 a($,J,Q.lostBefore);let X=Q.frames,G=X[0]?.seq;if(G===void 0)break;let V=Math.max(0,J-G);if(V>=X.length)break;let H=X[V];yield H,J=H.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 I9=new bQ;function b9(Q,$){try{Q.onInternalError?.($)}catch{}}class IQ{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 v9=new IQ;class h9{now;receipts=new Map;sweepAt=1024;constructor(Q=Date.now){this.now=Q}async claim(Q,$){let Z=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Z);let J=this.receipts.get(Q);if(J&&J.expiresAt>Z)return J.result?{status:"replay",result:structuredClone(J.result)}:{status:"blocked"};return this.receipts.set(Q,{expiresAt:$}),{status:"claimed"}}async complete(Q,$,Z){this.receipts.set(Q,{result:structuredClone($),expiresAt:Z})}async release(Q){let $=this.receipts.get(Q);if($&&!$.result)this.receipts.delete(Q)}get size(){return this.receipts.size}sweep(Q){for(let[$,Z]of this.receipts)if(Z.expiresAt<=Q)this.receipts.delete($);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var a$="pending",f9="done:",aZ=`
|
|
15
|
+
`):void 0}async runTools(Q,$,Z){let J=[],W=[];for(let X of $){let G=this.config.registry.get(String(X.name));if(!G){this.addResult(Q,{type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(X.name)}".`,toolCallId:X.toolCallId,retryable:!0}});continue}let H=G.inputSchema.safeParse(X.input);if(H.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:X.toolCallId,name:X.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(X.name)}": ${H.errors.join(", ")}`,toolCallId:X.toolCallId,retryable:!0}});continue}X.input=H.value;let K=_$(G.tool);if(K){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(X));continue}J.push({toolCallId:X.toolCallId,name:X.name,input:H.value,kind:K,signature:J$(this.claimsFor(X.toolCallId,String(X.name),K,H.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}W.push(this.executeTool(G,Q.id,X,H.value,Z).then(async(V)=>{this.addResult(Q,V),await this.settleShown(X.toolCallId)}).catch((V)=>{if(V instanceof u){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(X));return}J.push(...V.pending);return}}))}return await y(Promise.all(W).then(()=>{return}),this.controller.signal),J}claimsFor(Q,$,Z,J){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:J,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0,subject:this.params.subject??null}}deniedByPolicy(Q){return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"refused",reason:`"${String(Q.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Q,$,Z,J,W,X){let G=Q.tool.timeoutMs;if(G===void 0)return this.runToolBody(Q,$,Z,J,W,X,this.controller.signal,()=>!1);let H=new AbortController,K=this.controller.signal,V=()=>H.abort(K.reason);if(K.aborted)V();else K.addEventListener("abort",V,{once:!0});let z=!1,B=this.runToolBody(Q,$,Z,J,W,X,H.signal,()=>z),Y=()=>{},D=new Promise((j)=>{Y=L$(G,()=>{let U=`"${String(Z.name)}" did not finish within ${Z9(G)} (timeoutMs: ${G}) and was cancelled.`;H.abort(new DOMException(U,"TimeoutError")),j({type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"timeout",message:U,toolCallId:Z.toolCallId,retryable:!0}})})});B.catch(()=>{});try{return await Promise.race([B,D])}finally{z=!0,Y()}}async runToolBody(Q,$,Z,J,W,X,G,H){let K=this.toolFiles(Z,G),V={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:G,step:W,depth:this.depth,resumed:X!==void 0,attachments:K.attachments,generateImage:K.generateImage,editImage:K.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,G,X),generate:(z)=>this.generateForTool(z,G,Z.toolCallId)};try{let z=Q.tool.execute(J,V),B;if(HZ(z)){let Y=await z.next();while(!Y.done){if(H())throw z.return(void 0).catch(()=>{}),new E;this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:Y.value}),Y=await z.next()}B=Y.value}else B=await z;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:B}}catch(z){if(z instanceof E||this.controller.signal.aborted)throw new E;if(z instanceof u)throw z;let B=z instanceof T;if(!B&&this.config.logErrors)this.logToolFailure(Z,z);let Y={code:"tool_error",message:z instanceof Error?z.message:String(z),toolCallId:Z.toolCallId,retryable:B?z.retryable:!0};return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:this.redact(Y,{source:"tool",toolName:String(Z.name),cause:z})}}}async generateForTool(Q,$,Z){let J=this.controller.signal;return pQ({...Q,signal:Q.signal?AbortSignal.any([$,Q.signal]):$},{origin:{agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},toolCallId:Z},settled:(W)=>{if(this.usage=R(this.usage,W.usage),J.aborted)throw new E}})}nestedRunner(Q,$,Z,J){let W=new G9(()=>$.nested,()=>$.nested=[]);return async(X,G={})=>{let{at:H,recorded:K,write:V}=W.next();if(K){let z=zZ(K,X,G);if(z)throw new T(`Nested run ${H} of "${String($.name)}" ${z}. `+"runAgent is memoized by call index, so a body whose runAgent calls depend on a condition that changed between turns cannot be resumed \u2014 the answer would be paired with a different sub-run. "+"Make the sequence of runAgent calls, and what each one is asked, the same every time this tool runs, or branch on ctx.resumed.");if(K.finishReason!=="awaiting-input")return{runId:K.runId,agent:K.agent,messages:K.messages,finishReason:K.finishReason??"stop",usage:K.usage??M(),output:P$(K.messages),nested:K}}return this.runNested(Q,$,Z,X,G,V,K,J?.answers??[])}}async runNested(Q,$,Z,J,W,X,G,H){let K=[...this.chain,J.name];if(this.chain.includes(J.name))throw new T(`"${J.name}" is already running further up this chain: ${K.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let V=this.depth+1;if(V>this.maxDepth)throw new T(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${V}: ${K.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let z=W.label,B=[...this.pathPrefix,$.toolCallId],Y=this.onPending==="deny"?"deny":W.onPending??"escalate",D=G!==void 0,j=D?SQ(G.messages):new Set,U=D?H.filter((q)=>{let C=N$(q.path,B);if(C===null)return!1;return j.has(C.length>0?C[0]:q.toolCallId)}):[],L=J.stream({messages:D?G.messages:W.messages??[],turn:D?{toolResults:U}:W.prompt?{text:W.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:Z,threadId:this.params.threadId,redactError:this.params.redactError,nonces:this.params.nonces,receipts:this.params.receipts,subject:this.params.subject,instructions:W.instructions,maxOutputTokens:W.maxOutputTokens,temperature:W.temperature,runId:D?G.runId:void 0,nesting:{depth:V,maxDepth:this.maxDepth,chain:K,signingRunId:this.signingRunId,signingPath:B,onPending:Y}}),F=[],S=(q)=>this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:L.runId,agent:J.name,label:z,event:q}),N=(async()=>{for await(let q of L){if(q.type==="awaiting-input")F=q.pending;if(S(q),q.type==="run-start"&&!D)for(let C of W.messages??[])S({type:"message",message:C});if(q.type==="error")this.emit({type:"error",error:q.error,nested:{toolCallId:$.toolCallId,runId:L.runId,agent:J.name}})}})(),v=(async()=>{let q=await L.result();await N;let C=D?C$(G.messages,q.messages):C$(W.messages??[],q.messages),O={runId:L.runId,agent:J.name,label:z,messages:C,finishReason:q.finishReason,usage:D?R(G.usage??M(),q.usage):q.usage,...q.finishReason==="awaiting-input"?{signature:H$({runId:this.signingRunId,path:B,nestedRunId:L.runId,open:[...SQ(C)],input:$.input,subject:this.params.subject??null})}:{}};return X(O),this.usage=R(this.usage,q.usage),{result:q,record:O}})(),w=v.then(()=>{return},()=>{return});this.nestedSettling.add(w);let _,b;try{({result:_,record:b}=await v)}finally{this.nestedSettling.delete(w)}if(this.controller.signal.aborted)throw new E;if(_.finishReason==="awaiting-input"){if(F.length===0)throw new T(`"${J.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Q,part:$,resent:!0}),new u({pending:F,path:B,nested:b})}return{runId:b.runId,agent:J.name,messages:b.messages,finishReason:_.finishReason,usage:b.usage??M(),output:_.output??P$(b.messages),..._.error?{error:_.error}:{},nested:b}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolFiles(Q,$){let Z=this.params.attachments??null,J=new G9(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),W=()=>{if(!Z)throw new i("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return Z},X=async(V,z,B)=>{let Y=W(),D=z.mimeType||V.type||"",j=z.name??(V instanceof File?V.name:"attachment"),U;if(z.showModel){let F=this.config.provider;if(!F.capabilities.fileInput)throw new T(`"${String(Q.name)}" asked to show a file to ${F.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);U=await F.upload(new File([V],j,{type:D||void 0}))}return{attachment:await Y.put(V,{name:j,mimeType:D,fileId:U}),...B?{generated:B}:{},...U?{shown:{fileId:U,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},G=(V,z,B)=>{let Y=V.generated?"image":"put";if(Y===z)return;throw new T(`Attachment ${B} of "${String(Q.name)}" was ${Y==="image"?"a generated image":"a stored file"} on the first attempt and is ${z==="image"?"a generated image":"a stored file"} now. ctx.attachments.put, ctx.generateImage and ctx.editImage share one memo indexed by call order within a tool call, so the sequence has to be the same every time this tool runs. Branch on ctx.resumed if it cannot be.`)},H=async(V,z,B)=>{let{at:Y,recorded:D,write:j}=J.next();if(D&&"attachment"in D){if(G(D,"image",Y),D.shown)this.queueShown(Q.toolCallId,D);return{attachment:D.attachment,size:D.generated.size,mimeType:D.attachment.mimeType,usage:D.generated.usage}}let U=await B();this.usage=R(this.usage,U.usage);let L=U.mimeType==="image/jpeg"?"jpg":"png",F=await X(U.image,{name:z.name??`${V.name}.${L}`,mimeType:U.mimeType,...z.showModel?{showModel:!0}:{}},{size:U.size,usage:U.usage});if(j(F),F.shown)this.queueShown(Q.toolCallId,F);return{attachment:F.attachment,size:U.size,mimeType:U.mimeType,usage:U.usage}},K=async(V)=>typeof V==="string"?await W().file(V):V;return{generateImage:(V,z)=>H(V,z,()=>V.generate({...z,signal:$})),editImage:(V,z)=>H(V,z,async()=>{let{images:B,mask:Y,...D}=z;return await V.edit({...D,images:await Promise.all(B.map(K)),...Y?{mask:await K(Y)}:{},signal:$})}),attachments:{get:(V)=>W().get(V),read:(V)=>W().read(V),file:(V)=>W().file(V),put:async(V,z={})=>{let{at:B,recorded:Y,write:D}=J.next();if(Y&&"attachment"in Y){G(Y,"put",B);let U=KZ(Y,V,z);if(U)throw new T(`Attachment ${B} of "${String(Q.name)}" ${U}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(Y.shown)this.queueShown(Q.toolCallId,Y);return Y.attachment}let j=await X(V,z);if(D(j),j.shown)this.queueShown(Q.toolCallId,j);return j.attachment}}}}toolTurn(Q){let $=this.history.findIndex((X)=>X.id===Q),Z=RQ(this.history),J;for(let X=$-1;X>=0;X--){let G=this.history[X];if(G.role!=="user"||Z.has(G.id))continue;J=G;break}let W=[];for(let X of J?.content??[]){if(X.type!=="file")continue;let G=X.attachmentId;if(typeof G!=="string"||!G.startsWith(f))continue;if(!W.includes(G))W.push(G)}return Object.freeze({attachments:Object.freeze(W)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let J=this.shownQueue.get(Q)??[];if(J.some((W)=>W.id===Z.messageId))return;J.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set(Q,J)}async settleShown(Q){let $=this.shownQueue.get(Q);if(!$||$.length===0)return;if(this.shownQueue.delete(Q),this.ended||this.controller.signal.aborted)return;for(let Z of $){if(this.history.some((J)=>J.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider(Q){let $=this.history.filter((X)=>X!==Q),Z=RQ($),J=[];for(let X of $){if(!Z.has(X.id))continue;for(let G of X.content)if(G.type==="file")J.push(G)}if(J.length<=q$)return $;let W=new Set(J.slice(0,J.length-q$));return $.map((X)=>{if(!X.content.some((G)=>G.type==="file"&&W.has(G)))return X;return{...X,content:X.content.map((G)=>G.type==="file"&&W.has(G)?{type:"text",text:`[A ${G.mimeType||"file"} produced by a tool (attachment ${G.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:G)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let J=new Set,W=new Set,X=new Map;for(let G of Q?.toolResults??[]){let H=`${(G.path??[]).join("/")}#${G.toolCallId}`;if(W.has(H))continue;W.add(H);let K=(Y)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:Y,toolCallId:G.toolCallId,retryable:!1}}),V=N$(G.path,this.pathPrefix);if(V===null){K(`The answer for "${G.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(V.length>0){let Y=V[0],D=$.find((L)=>L.call.toolCallId===Y);if(!D){K(`No pending tool call with id "${Y}" to deliver a nested answer to.`);continue}let j=this.parkedBelow(D.call,V,G.toolCallId);if(j.ok===!1){let L=`The answer for "${G.toolCallId}" is addressed under "${Y}", which`;K(j.reason==="unparked"?`${L} has no sub-agent run waiting on that question.`:j.reason==="expired"?`${L} parked a sub-agent run that has since expired. Ask again.`:`${L} carries a record of a parked sub-agent run the server did not sign.`);continue}let U=X.get(Y);if(!U){if(!await this.spend(B$,j.signature)){K(`The answer for "${G.toolCallId}" is addressed under "${Y}", which has already been re-entered on that record. Ask again.`);continue}U=[],X.set(Y,U),J.add(Y)}U.push(G);continue}let z=$.find((Y)=>Y.call.toolCallId===G.toolCallId);if(!z){K(`No pending tool call with id "${G.toolCallId}".`);continue}let B=await this.resolveAnswer(z,G,Z);if(B===null)continue;if(J.add(G.toolCallId),B!=="open")this.attachToHistory(z,B),await this.settleShown(G.toolCallId)}for(let[G,H]of X){let K=$.find((z)=>z.call.toolCallId===G),V=await this.reenter(K,H,Z);if(V)this.attachToHistory(K,V),await this.settleShown(G)}for(let G of $){if(J.has(G.call.toolCallId))continue;this.attachToHistory(G,{type:"tool-result",toolCallId:G.call.toolCallId,name:G.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if(Q&&(Q.text||Q.files&&Q.files.length>0)){let J={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((W)=>({type:"file",...W.fileId?{fileId:W.fileId}:{},name:W.name,mimeType:W.mimeType,...W.attachmentId?{attachmentId:W.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};if(this.history.push(J),this.produced.push(J),this.depth>0)this.emit({type:"message",message:J});else if(Q.localId)this.emit({type:"message-id",localId:Q.localId,messageId:J.id});await this.report(J)}return Z}parkedBelow(Q,$,Z){let J=$.length>1?$[1]:Z,W=[...this.pathPrefix,Q.toolCallId],X=(Q.nested??[]).find((H)=>H.finishReason==="awaiting-input"&&SQ(H.messages).has(J));if(!X)return{ok:!1,reason:"unparked"};if(typeof X.signature!=="string")return{ok:!1,reason:"unsigned"};let G=Y$(X.signature,{path:W,nestedRunId:X.runId,open:[...SQ(X.messages)],input:Q.input,subject:this.params.subject??null});if(G.ok===!1)return{ok:!1,reason:G.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:X.signature}}async reenter(Q,$,Z){let J=String(Q.call.name),W=this.config.registry.get(J);if(!W||!W.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${J}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let X=W.inputSchema.safeParse(Q.call.input);if(X.ok===!1)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${J}": ${X.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let G=this.amendCall(Q);G.input=X.value;try{return await y(this.executeTool(W,Q.message.id,G,X.value,0,{answers:$}),this.controller.signal)}catch(H){if(H instanceof u)return Z.push(...H.pending),null;throw H}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),J={...Q.call,nested:(Q.call.nested??[]).map((W)=>({...W})),...Q.call.attachments?{attachments:Q.call.attachments.map((W)=>({...W}))}:{}};if(Z>=0)$.content[Z]=J;return this.unreported.add($),J}openCalls(){let Q=new Set;for(let Z of this.history)for(let J of Z.content)if(J.type==="tool-result")Q.add(J.toolCallId);let $=[];for(let Z of this.history)for(let J of Z.content)if(J.type==="tool-call"&&!Q.has(J.toolCallId))$.push({message:Z,call:J});return $}async spend(Q,$){try{return await Q($,this.params.nonces??l)}catch(Z){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not spend a nonce`,{error:Z}),!1}}async recordReceipt(Q,$){let Z=await $;try{await Q.store.complete(Q.id,Z,Q.expiresAt)}catch(J){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record a tool receipt`,{error:J})}return Z}async resolveAnswer(Q,$,Z){let J=Q.call,W=String(J.name),X=this.config.registry.get(W),G=(B)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:B,toolCallId:J.toolCallId,retryable:!1}}),null};if(!X)return G(`The tool "${W}" no longer exists, so its answer cannot be checked.`);let H=_$(X.tool);if(!H)return G(`"${W}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return G(`The answer for "${W}" carried no signature.`);let K=sQ($.signature);if(!K)return G(`The signature for "${W}" is malformed.`);let V=W$($.signature,{...this.claimsFor(J.toolCallId,W,H,J.input),runId:K.runId});if(V.ok===!1)return G(V.reason==="expired"?`The approval for "${W}" has expired. Ask again.`:`The answer for "${W}" does not match the call the server made.`);let z;if(this.params.receipts&&H==="approval"&&"approve"in $&&$.approve===!0){let B=this.params.receipts,Y=K$(this.config.name,{...this.claimsFor(J.toolCallId,W,H,J.input),runId:K.runId}),D;try{D=await B.claim(Y,K.expiresAt)}catch(j){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not claim a tool receipt`,{error:j}),G(`The approval for "${W}" could not be checked. Ask again.`)}if(D.status==="replay")return{...D.result,toolCallId:J.toolCallId,name:J.name};if(D.status==="blocked")return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"tool_error",message:`"${W}" was already approved and started, and its result is not recorded yet: it is still running, or it stopped before finishing. It was not run again.`,toolCallId:J.toolCallId,retryable:!1}};z={store:B,id:Y,expiresAt:K.expiresAt}}if(!await this.spend(z$,$.signature))return await z?.store.release(z.id).catch((B)=>{this.writeLog(`[gemi/ai] agent "${this.config.name}" could not release a tool receipt`,{error:B})}),G(`The answer for "${W}" has already been used. Ask again.`);if("approve"in $){if(H!=="approval")return G(`"${W}" is answered by the client, not approved.`);if($.approve===!0){let B=this.amendCall(Q),Y=this.executeTool(X,Q.message.id,B,B.input,0);try{return await y(z?this.recordReceipt(z,Y):Y,this.controller.signal)}catch(D){if(D instanceof u)return Z.push(...D.pending),"open";throw D}}return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(H==="approval")return G(`"${W}" is approved, not answered: the server produces its result.`);let B=X.tool.outputSchema,Y=B?B.safeParse($.output):{ok:!0,value:$.output};if(Y.ok===!1)return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${W}" did not match its output schema: ${Y.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"ok",output:Y.value}}return G(`The answer for "${W}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let Z=this.amend(Q.message);Z.content.push($),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:$})}markFileRejected(Q,$,Z){for(let G of this.history){if(!G.content.some((V)=>V.type==="file"&&V.fileId===Q&&!V.providerRejected))continue;let K=this.produced.includes(G)?G:this.amend(G);if(K.content=K.content.map((V)=>V.type==="file"&&V.fileId===Q&&!V.providerRejected?{...V,providerRejected:!0}:V),K!==this.current)this.unreported.add(K)}if(!this.config.logErrors)return;let J=`[gemi/ai] agent "${this.config.name}": the provider refused file ${Q}${Z.status!==void 0?` (${Z.status})`:""}; it was left out of the request and will not be sent again: ${$}`,W={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},fileId:Q,...Z},X=!1;try{$Q.warning(J,W),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.warn(J,W)}amend(Q){let $=this.amended.get(Q.id);if($)return $;let Z={...Q,content:[...Q.content]},J=this.history.indexOf(Q);if(J>=0)this.history[J]=Z;return this.produced.push(Z),this.amended.set(Q.id,Z),Z}async reportDeferred(){let Q=[...this.unreported];this.unreported.clear();for(let $ of Q)await this.report($)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let $ of this.openCalls()){if($.message===this.current)continue;this.attachToHistory($,{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let Q=this.current;if(Q){let $=new Set(Q.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...Q.content]){if(Z.type!=="tool-call"||$.has(Z.toolCallId))continue;delete Z.partial,this.addResult(Q,{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"stopped",reason:this.stopReason})}}if(this.timedOutAfter!==void 0){this.fail({code:"timeout",message:`The run did not finish within its time limit of ${Z9(this.timedOutAfter)} (maxRunDurationMs: ${this.timedOutAfter}) and was stopped.`,retryable:!0}),this.finishReason="error",await this.finalizeMessage("error");return}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function _$(Q){if(Q.answeredBy==="client")return Q.inputSchema===V9?"question":"client";return Q.requiresApproval?"approval":null}function M$(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}var BZ=/^[A-Za-z0-9_-]{1,64}$/;function DZ(Q,$){let Z=UZ($)?$:{filter:$},J=Z.deferred===!0,W=Q.descriptors(Z.filter);if(!Z.namespaces)return W.map((z)=>D9(Q,z,J));let X=Object.entries(Z.namespaces),G=new Set(Q.descriptors().flatMap((z)=>z.tags));for(let[z,B]of X){if(!BZ.test(z))throw Error(`toAgentTools: "${z}" is not a valid namespace name. A namespace is named by its tag and sent to the provider as a tool name is \u2014 letters, digits, "_" and "-", at most 64.`);if(typeof B?.description!=="string"||B.description.trim()==="")throw Error(`toAgentTools: the namespace "${z}" needs a description. It is what the model reads to decide whether to look inside.`);if(!G.has(z))throw Error(`toAgentTools: no tool is tagged "${z}", so its namespace would be empty.`)}let H=new Map(X.map(([z])=>[z,[]])),K=[];for(let z of W){let B=X.find(([Y])=>z.tags.includes(Y))?.[0];if(B===void 0)K.push(D9(Q,z,J));else H.get(B).push(D9(Q,z,!1))}let V=[];for(let[z,B]of X){let Y=H.get(z);if(Y.length===0)continue;V.push(o.create({name:z,description:B.description,tools:Y,deferred:B.deferred??J}))}return[...V,...K]}function UZ(Q){return typeof Q==="object"&&Q!==null&&(("filter"in Q)||("namespaces"in Q)||("deferred"in Q))}function D9(Q,$,Z){return c.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Z,execute:(J,W)=>{let X=TQ.getStore()?.req;if(!X)throw new T(`"${$.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return Q.execute({kind:"local",req:X},$.name,J,W)}})}function FZ(Q){if(Q==="auto")return;let $=/^(\d+)x(\d+)$/.exec(Q);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(Q)}.`);let Z=Number($[1]),J=Number($[2]);if(Z%16!==0||J%16!==0)throw Error(`Image size ${Q} is not supported: width and height must both be divisible by 16.`);if(Math.max(Z/J,J/Z)>3)throw Error(`Image size ${Q} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function A$(Q,$){if(Q.size!==void 0)try{FZ(Q.size)}catch(Z){throw Error(`${$}: ${Z.message}`)}if(Q.background==="transparent"&&Q.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(Q.compression!==void 0){let Z=Q.compression;if(!Number.isInteger(Z)||Z<0||Z>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Z}.`)}}function E$(Q,$){if(Q instanceof File)return Q;let Z=Q.type||"image/png",J=Z==="image/jpeg"?"jpg":Z.split("/")[1]??"png";return new File([Q],`${$}.${J}`,{type:Z})}class U9{name;provider;settings;constructor(Q){let{name:$,provider:Z,...J}=Q;A$(J,`ImageModel "${$}"`),this.name=$,this.provider=Z,this.settings=J}static create(Q){return new U9(Q)}async generate(Q){let $=this.merge(Q);return x$(await this.provider.generate({prompt:Q.prompt,...$,signal:Q.signal}))}async edit(Q){let $=this.merge(Q);return x$(await this.provider.edit({prompt:Q.prompt,...$,images:Q.images.map((Z,J)=>E$(Z,`image-${J}`)),...Q.mask?{mask:E$(Q.mask,"mask")}:{},signal:Q.signal}))}merge(Q){let $={...this.settings,...Q.size!==void 0?{size:Q.size}:{},...Q.quality!==void 0?{quality:Q.quality}:{},...Q.background!==void 0?{background:Q.background}:{},...Q.format!==void 0?{format:Q.format}:{},...Q.compression!==void 0?{compression:Q.compression}:{}};return A$($,`ImageModel "${this.name}"`),$}}function x$(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}function m(Q){return typeof process>"u"?void 0:process.env?.[Q]}var jZ="preview";function w$(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function LZ(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function kQ(Q,$={}){return{base:(Q.baseURL??m("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let J=Q.apiKey??m("OPENAI_API_KEY");return{...J?{authorization:`Bearer ${J}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}function CZ(Q){let $=Q.baseURL??Q.endpoint??m("AZURE_OPENAI_ENDPOINT");if($)return w$($);let Z=Q.resourceName??m("AZURE_OPENAI_RESOURCE_NAME")??m("AZURE_RESOURCE_NAME");return Z?w$(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function AQ(Q,$={}){let Z=Q.apiVersion??m("AZURE_OPENAI_API_VERSION")??jZ;return{base:`${CZ(Q)}${LZ(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let J=Q.apiKey??m("AZURE_OPENAI_API_KEY");return{...J?{"api-key":J}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}var PZ=500,I$=20000;function OZ(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let J=Date.parse(Z);if(Number.isNaN(J))return;return Math.max(0,J-$)}function b$(Q,$){let Z=Math.min(I$,PZ*2**Q);return Math.round(Z*(0.5+$()*0.5))}function qZ(Q){return Q===429||Q===408||Q===409||Q>=500}function NZ(Q,$){return qZ(Q)&&k($).retryable}function v$(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function _Z(Q,$){return new Promise((Z,J)=>{let W=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(W),J(v$($))},{once:!0})})}async function HQ(Q,$,Z){let J=Z.fetchImpl??((z,B)=>fetch(z,B)),W=Z.sleep??_Z,X=Z.random??Math.random,G=Z.now??Date.now,H=Math.max(0,Z.maxRetries),K=async(z)=>{let B=Z.signal;if(!B)return await W(z);B.throwIfAborted();let Y;try{await Promise.race([W(z,B),new Promise((D,j)=>{Y=()=>j(v$(B)),B.addEventListener("abort",Y,{once:!0})})])}finally{if(Y)B.removeEventListener("abort",Y)}},V;for(let z=0;z<=H;z++){Z.signal?.throwIfAborted();let B=new AbortController,Y=()=>B.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",Y,{once:!0});let D=!1,j=Z.timeoutMs>0?setTimeout(()=>{D=!0,B.abort()},Z.timeoutMs):void 0,U;try{U=await J(Q,{...$,signal:B.signal})}catch(N){if(j!==void 0)clearTimeout(j);if(Z.signal?.removeEventListener("abort",Y),Z.signal?.aborted)throw N;if(V=D?new BQ(Z.timeoutMs):N,D&&Z.retryTimeouts===!1)throw V;if(z===H)throw V;await K(b$(z,X));continue}if(j!==void 0)clearTimeout(j);if(U.ok)return U;Z.signal?.removeEventListener("abort",Y);let L=await MZ(U),F=new h(U.status,L,U.headers.get("x-request-id")??void 0);if(z===H||!NZ(U.status,F))throw F;let S=OZ(U.headers.get("retry-after"),G());await K(S===void 0?b$(z,X):Math.min(S,I$)),V=F}throw V??Error("Provider request failed with no response.")}async function MZ(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var F9=300000;function j9(Q){return{generationsUrl:`${Q.base}/images/generations${Q.query}`,editsUrl:`${Q.base}/images/edits${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}class EQ extends Error{code;retryable;constructor(Q,$={}){super(Q.message,$);this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable}}var SZ={png:"image/png",jpeg:"image/jpeg"};function RZ(Q){let $=Number(Q?.input_tokens??0),Z=Number(Q?.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q?.total_tokens??$+Z)},W=Q?.input_tokens_details?.image_tokens;if(typeof W==="number")J.imageInputTokens=W;let X=Q?.output_tokens_details?.image_tokens;if(typeof X==="number")J.imageOutputTokens=X;return J}function TZ(Q){let $=atob(Q),Z=new Uint8Array($.length);for(let J=0;J<$.length;J++)Z[J]=$.charCodeAt(J);return Z}function kZ(Q){let Z=Q?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new EQ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let J=typeof Q.output_format==="string"?Q.output_format:"png";return{bytes:TZ(Z),mimeType:SZ[J]??`image/${J}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:RZ(Q.usage)}}async function f$(Q,$,Z,J){let W;try{W=await HQ(Q,$,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:J.signal,fetchImpl:Z.fetchImpl})}catch(X){if(J.signal?.aborted)throw X;throw new EQ(k(X),{cause:X})}return kZ(await W.json())}async function h$(Q,$,Z={}){return await f$(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},Q,Z)}async function y$(Q,$,Z={}){return await f$(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:$},Q,Z)}class xQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await h$(this.endpoint(),this.body(Q),{signal:Q.signal})}async edit(Q){let $=new FormData;for(let[Z,J]of Object.entries(this.body(Q)))if(J!==void 0)$.set(Z,String(J));for(let Z of Q.images)$.append("image[]",Z,Z.name);if(Q.mask)$.set("mask",Q.mask,Q.mask.name);return await y$(this.endpoint(),$,{signal:Q.signal})}body(Q){return{model:this.modelName(),prompt:Q.prompt,...Q.size?{size:Q.size}:{},...Q.quality?{quality:Q.quality}:{},...Q.background?{background:Q.background}:{},...Q.format?{output_format:Q.format}:{},...Q.compression!==void 0?{output_compression:Q.compression}:{}}}normalizeError(Q){return k(Q)}}var g$=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class L9 extends xQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new L9(Q,$)}static models(){return g$}endpoint(){return j9(kQ(this.config,{timeoutMs:F9}))}}class C9 extends xQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new C9(Q,$)}static models(){return g$}modelName(){return this.config.deployment??this.model}endpoint(){return j9(AQ(this.config,{timeoutMs:F9}))}}var m$=3;function P9(Q){let $=new Map;for(let Z of Q)for(let J of Z.content??[]){if(J.type!=="file"||!J.fileId||$.has(J.fileId))continue;$.set(J.fileId,{name:J.name,mimeType:J.mimeType})}return $}function p$(Q,$,Z=new Map){if(!($ instanceof h))return[];if($.status!==400&&$.status!==404)return[];let J=EZ($.body);if(!J)return[];let W=AZ(Q.input);if(W.length===0)return[];let X=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(J.param??"");if(X){let V=Q.input[Number(X[1])],z=q9(V)[Number(X[2])],B=z&&typeof z.file_id==="string"?z.file_id:void 0;if(B)return[B]}let G=J.message??"",H=c$(W.map((V)=>V.fileId).filter((V)=>xZ(G,V)));if(H.length>0)return H;let K=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(G);if(K){let V=K[1].toLowerCase()==="image type"?"input_image":"input_file",z=K[2].toLowerCase(),B=c$(W.filter((D)=>D.type===V).map((D)=>D.fileId)),Y=B.filter((D)=>(Z.get(D)?.name??"").trim().toLowerCase().endsWith(`.${z}`));if(Y.length===1)return Y;if(Y.length===0&&B.length===1)return B}return[]}function d$(Q,$,Z=new Map){return{...Q,input:Q.input.map((J)=>{let W=q9(J);if(!W.some((X)=>u$(X,$)))return J;return{...J,content:W.map((X)=>u$(X,$)?{type:"input_text",text:O9(Z.get(String(X.file_id))?.name)}:X)}})}}function O9(Q){return`[${Q?`attachment ${JSON.stringify(Q)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function u$(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function q9(Q){let $=Q?.content;return Array.isArray($)?$:[]}function AZ(Q){let $=[];for(let Z of Q)for(let J of q9(Z))if(typeof J.file_id==="string"&&J.file_id)$.push({type:String(J.type),fileId:J.file_id});return $}function EZ(Q){if(!Q||typeof Q!=="object")return null;let $=Q,Z=$.error&&typeof $.error==="object"?$.error:Q;return{message:typeof Z.message==="string"?Z.message:void 0,param:typeof Z.param==="string"?Z.param:void 0}}function xZ(Q,$){let Z=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Z}($|[^A-Za-z0-9_-])`).test(Q)}function c$(Q){return[...new Set(Q)]}async function*wZ(Q){let $="",Z="",J=[],W,X=()=>{if(J.length===0&&!Z)return null;let K={event:Z,data:J.join(`
|
|
16
|
+
`),id:W};return Z="",J=[],W=void 0,K.data?K:null},G=(K)=>{let V=K.endsWith("\r")?K.slice(0,-1):K;if(V==="")return X();if(V.startsWith(":"))return null;let z=V.indexOf(":"),B=z===-1?V:V.slice(0,z),Y=z===-1?"":V.slice(z+1);if(Y.startsWith(" "))Y=Y.slice(1);if(B==="event")Z=Y;else if(B==="data")J.push(Y);else if(B==="id")W=Y;return null};for await(let K of Q){$+=K;let V=$.indexOf(`
|
|
17
|
+
`);while(V!==-1){let z=$.slice(0,V);$=$.slice(V+1);let B=G(z);if(B)yield B;V=$.indexOf(`
|
|
18
|
+
`)}}if($.length>0){let K=G($);if(K)yield K}let H=X();if(H)yield H}async function*l$(Q,$={}){let Z=new Map,J=new Set,W,X=!1,G,H=(K,V)=>({type:"finish",reason:K,usage:V,...G?{model:G}:{}});for await(let K of wZ(Q)){if(K.data==="[DONE]")break;let V;try{V=JSON.parse(K.data)}catch{continue}let z=typeof V.type==="string"?V.type:K.event,B=V.response?.model;if(typeof B==="string"&&B)G=B;switch(z){case"response.output_text.delta":{let Y=String(V.delta??"");if(!Y)break;yield $.structuredOutput?{type:"output-delta",delta:Y}:{type:"text-delta",delta:Y};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let Y=String(V.delta??"");if(!Y)break;yield{type:"reasoning-delta",delta:Y,id:V.item_id};break}case"response.output_item.added":{let Y=V.item;if(!Y)break;if(Y.type==="function_call"){let D=String(Y.id??V.item_id??Y.call_id??"");Z.set(D,{callId:String(Y.call_id??D),name:String(Y.name??""),namespace:typeof Y.namespace==="string"&&Y.namespace?Y.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let Y=Z.get(String(V.item_id??""));if(!Y)break;let D=String(V.delta??"");if(!D)break;yield{type:"tool-call-delta",toolCallId:Y.callId,name:Y.name,argsDelta:D,...Y.namespace?{namespace:Y.namespace}:{}};break}case"response.function_call_arguments.done":{let Y=String(V.item_id??""),D=Z.get(Y);if(!D)break;D.done=!0,yield{type:"tool-call",toolCallId:D.callId,name:D.name,args:String(V.arguments??""),...D.namespace?{namespace:D.namespace}:{}};break}case"response.output_item.done":{let Y=V.item;if(!Y)break;if(Y.type==="function_call"){let D=String(Y.id??V.item_id??Y.call_id??""),j=Z.get(D);if(j?.done)break;let U=(typeof Y.namespace==="string"?Y.namespace:"")||j?.namespace;if(yield{type:"tool-call",toolCallId:String(Y.call_id??D),name:String(Y.name??j?.name??""),args:String(Y.arguments??""),...U?{namespace:U}:{}},j)j.done=!0;break}if(Y.type==="tool_search_call"||Y.type==="tool_search_output"){if(Y.type==="tool_search_call"&&Y.arguments!==void 0)W=Y.arguments;let D=bZ(Y);if(D.loaded.length===0&&D.namespaces.length===0)break;let j=String(Y.tool_search_call_id??Y.id??"");if(J.has(j))break;J.add(j);let U=W;W=void 0,yield{type:"tool-search",...D,...U!==void 0&&U!==null?{arguments:U}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(V.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{X=!0,yield H("stop",N9(V.response?.usage));break}case"response.incomplete":{X=!0;let Y=N9(V.response?.usage),D=V.response?.incomplete_details?.reason;if(D==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:IZ(V.response?.content_filters),retryable:!1}},yield H("error",Y);break}yield H(D==="max_output_tokens"?"length":"stop",Y);break}case"response.failed":case"error":{X=!0;let Y=V.response?.error??V.error??V;yield{type:"error",error:vZ(Y)},yield H("error",N9(V.response?.usage));break}}if(X)return}if(!X)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield H("error",n())}function bZ(Q){let $=[],Z=[];return i$(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:_9($),namespaces:_9(Z)}}function i$(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:"",H=X.tools??X.functions;if(Array.isArray(H)){if(G)Z.push(G);i$(H,$,Z,J+1);continue}if(G)$.push(G)}}function _9(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function IZ(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,H]of Object.entries(X))if(H&&typeof H==="object"&&H.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: ${_9(Z).join(", ")}.`}function vZ(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 n(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function N9(Q){if(!Q)return n();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*o$(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 M9(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*S9(Q,$,Z){let J,W=$,X=new Set;for(let G=0;J===void 0;G++)try{J=await HQ(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(H){let K=G<m$?p$(W,H,Z.files).filter((z)=>!X.has(z)):[];if(K.length>0){let z=k(H).message;for(let B of K)X.add(B),yield{type:"file-rejected",fileId:B,message:z,...A(H)};W=d$(W,new Set(K),Z.files);continue}let V=k(H);if(V.code!=="aborted")yield{type:"error",error:V,...A(H)};yield{type:"finish",reason:V.code==="aborted"?"aborted":"error",usage:n()};return}try{yield*l$(o$(J.body),{structuredOutput:Z.structuredOutput})}catch(G){let H=k(G);if(H.code==="aborted"){yield{type:"finish",reason:"aborted",usage:n()};return}yield{type:"error",error:H},yield{type:"finish",reason:"error",usage:n()}}}async function R9(Q,$,Z="user_data"){let J=new FormData;J.set("purpose",Z),J.set("file",$);let X=await(await HQ(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 T9(Q){let $=fZ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=hZ($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:n$(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:n$(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function n$(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function fZ(Q){return Q.trim().toLowerCase()}function hZ(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 A9(Q,$){let{capabilities:Z}=$,J={model:$.model,input:yZ(Q.messages,Z,Q.tools),stream:!0};if(Q.systemPrompt)J.instructions=Q.systemPrompt;let W=nZ(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 yZ(Q,$,Z){let J=[],W=new Map;if($.toolSearch){for(let X of Z??[])if(wQ(X))W.set(X.name,X)}for(let X of Q){let G=X.role,H=[],K=()=>{if(H.length===0)return;J.push({type:"message",role:G,content:H}),H=[]};for(let V of X.content??[])switch(V.type){case"text":{if(!V.text)break;H.push(s(G,V.text));break}case"output":{if(V.partial)break;H.push(s(G,JSON.stringify(V.value)));break}case"file":{if(G==="assistant")break;let z=cZ(V);if(!$.fileInput){if(z)H.push(s(G,k9(V,!1)));break}if(V.fileId?.startsWith(f))throw Error(`FilePart.fileId holds a gemi attachment id (${V.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(!V.fileId&&!z)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(V.providerRejected){if(z)H.push(s(G,k9(V,!1)));H.push(s(G,O9(V.name)));break}if(z)H.push(s(G,k9(V,!!V.fileId)));if(V.fileId)H.push(mZ(V));break}case"reasoning":{K();let z=lZ(V);if(z)J.push(z);break}case"tool-call":{if(V.partial)break;if(K(),$.toolSearch&&Array.isArray(V.toolSearches))for(let B of V.toolSearches)J.push(...oZ(B,Z??[]));let z={type:"function_call",call_id:V.toolCallId,name:String(V.name),arguments:JSON.stringify(V.input??{})};if(V.namespace&&W.has(V.namespace))z.namespace=V.namespace;J.push(z);break}case"tool-result":{K(),J.push({type:"function_call_output",call_id:V.toolCallId,output:iZ(V)});break}}K()}return uZ(J)}var gZ="No result was recorded for this tool call. Assume it did not complete.";function uZ(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:gZ})}return W}function s(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function cZ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(f)?$:void 0}function k9(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 mZ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":pZ(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function pZ(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&dZ.has($[1])}var dZ=new Set(["jpeg","jpg","png","gif","webp"]);function lZ(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function iZ(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 oZ(Q,$){let Z=new Set(s$(Q?.loaded)),J=s$(Q?.namespaces),W=new Set(J),X=[];for(let H of $)if(wQ(H)){if(!W.has(H.name))continue;let K=H.tools.filter((V)=>Z.size===0||Z.has(V.name));if(K.length===0)continue;X.push({type:"namespace",name:H.name,description:H.description,tools:K.map((V)=>t(V,!0))})}else if(H.deferred&&Z.has(H.name))X.push(t(H,!0));if(X.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:Q.arguments&&typeof Q.arguments==="object"?Q.arguments:{paths:J.length>0?J:[...Z]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:X}]}function s$(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function wQ(Q){return Array.isArray(Q.tools)}function nZ(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let W=[];for(let X of Q)if(wQ(X))for(let G of X.tools)W.push(t(G,!1));else W.push(t(X,!1));return W}let Z=[],J=!1;for(let W of Q)if(wQ(W)){let X=W.tools.map((G)=>{if(G.deferred)J=!0;return t(G,!0)});Z.push({type:"namespace",name:W.name,description:W.description,tools:X})}else{if(W.deferred)J=!0;Z.push(t(W,!0))}if(J)Z.push({type:"tool_search"});return Z}function t(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 a{static models(){return[]}normalizeError(Q){return k(Q)}}var t$=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class E9 extends a{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=T9(Q),this.config=$}static model(Q,$){return new E9(Q,$)}static models(){return t$}stream(Q){let $=A9(Q,{model:this.model,capabilities:this.capabilities});return S9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:P9(Q.messages)})}upload(Q){return R9(this.endpoint(),Q)}endpoint(){return M9(kQ(this.config))}}class x9 extends a{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=T9(Q),this.config=$}static model(Q,$){return new x9(Q,$)}static models(){return t$}stream(Q){let $=A9(Q,{model:this.deployment(),capabilities:this.capabilities});return S9(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:P9(Q.messages)})}upload(Q){return R9(this.endpoint(),Q,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return M9(AQ(this.config))}}class bQ{now;entries=new Map;constructor(Q=Date.now){this.now=Q}allow(Q,$){let Z=this.entries.get(Q);if(Z?.openUntil===void 0)return!0;let J=this.now();if(J<Z.openUntil)return!1;if(Z.probeUntil!==void 0&&J<Z.probeUntil)return!1;return Z.probeUntil=J+$.cooldownMs,!0}record(Q,$,Z){let J=this.entries.get(Q)??{failures:0},W=J.openUntil!==void 0;if($==="success")return this.entries.delete(Q),W?"closed":void 0;if($==="none"){delete J.probeUntil;return}if(J.failures+=1,this.entries.set(Q,J),W||J.failures>=Z.failures)return J.openUntil=this.now()+Z.cooldownMs,delete J.probeUntil,W?void 0:"open";return}state(Q){let $=this.entries.get(Q);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}function sZ(Q){switch(Q.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}var a$=Symbol("timed-out");class YQ extends a{model;capabilities;entries;options;circuit;constructor(Q,$={}){super();if(Q.length===0)throw Error("FallbackProvider needs at least one provider.");for(let J of Q)if(J.timeoutMs!==void 0&&!(J.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${J.provider.model} must be a positive number, got ${J.timeoutMs}.`);this.entries=[...Q];let Z=$.circuit;if(Z){let J=Z.failures??3,W=Z.cooldownMs??30000;if(!Number.isInteger(J)||J<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${J}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let X=new Set;for(let H of Q){let K=w9(H);if(X.has(K))throw Error(`FallbackProvider: two legs share the circuit key "${K}". Give one of them a \`circuitKey\`.`);X.add(K)}let G=Z.store??new bQ;this.options={...$,circuit:{...Z,store:G}},this.circuit={policy:{failures:J,cooldownMs:W},store:G,...Z.onStateChange?{onStateChange:Z.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=Q[0].provider.model,this.capabilities=tZ(Q.map((J)=>J.provider.capabilities))}static chain(Q,$){return new YQ(Q,$)}from(Q){if(!Number.isInteger(Q)||Q<0||Q>=this.entries.length)throw RangeError(`FallbackProvider.from(${Q}): the chain has ${this.entries.length} entries.`);return new YQ(this.entries.slice(Q),this.options)}leg(Q){let $=this.from(Q).entries[0];return new YQ([$],this.options)}upload(Q){return this.entries[0].provider.upload(Q)}normalizeError(Q){return this.entries[0].provider.normalizeError(Q)}stream(Q){return this.run(Q)}async*run(Q){let $,Z=Q.signal,J=0;for(let W=0;W<this.entries.length;W++){let X=this.entries[W],G=W===this.entries.length-1,H=X.provider.model;if(this.circuit&&!G&&!await this.allow(X))continue;J+=1;let K=!1,V=async(C)=>{if(K)return;K=!0,await this.record(W,X,C)},z=new AbortController,B=()=>z.abort(Z?.reason);if(Z?.aborted)z.abort(Z.reason);else Z?.addEventListener("abort",B,{once:!0});let Y=[],D=!1,j=!1,U,L,F,S=!1,N,v=!1,w=(C)=>{let O=$?R(R(M(),$),C.usage):C.usage;return $=void 0,{...C,usage:O}};try{N=X.provider.stream({...Q,...X.reasoning!==void 0?{reasoning:X.reasoning}:{},signal:z.signal})[Symbol.asyncIterator]();let C=!0;for(;;){let O=C&&X.timeoutMs!==void 0?await aZ(N.next(),X.timeoutMs):await N.next();if(O===a$){S=!0,F={error:{code:"provider_error",message:`${H} sent nothing within ${X.timeoutMs}ms.`,retryable:!0}};break}if(C=!1,O.done){v=!0;break}let P=O.value;if(P.type==="finish"&&P.model)L=P.model;if(D){if(P.type==="finish")U=R(U??M(),P.usage),j=!0,yield w(P);else{if(P.type==="error")F={error:P.error};yield P}continue}if(sZ(P)){D=!0,await V("success"),yield*Y.splice(0),yield P;continue}if(P.type==="error")F={error:P.error,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}};else if(P.type==="finish"){if(U=R(U??M(),P.usage),P.reason==="error"&&!F)F={error:{code:"provider_error",message:`${H} ended the call with an error and did not say which.`,retryable:!1}}}Y.push(P)}}catch(C){let O=X.provider.normalizeError(C);if(D){if(O.code!=="aborted")yield{type:"error",error:O,...A(C)};this.report({index:W,model:H,responseModel:L,attempt:J,usage:U,outcome:b9(O),error:O}),yield w({type:"finish",reason:O.code==="aborted"?"aborted":"error",usage:M(),...L?{model:L}:{}});return}F={error:O,...A(C)}}finally{if(Z?.removeEventListener("abort",B),!v)z.abort(),N?.return?.()?.catch(()=>{})}if(D){if(!j&&$)yield{type:"finish",reason:F?"error":"stop",usage:$},$=void 0;this.report({index:W,model:H,responseModel:L,attempt:J,usage:U,outcome:F?b9(F.error):"ok",...F?{error:F.error}:{}});return}if(Z?.aborted){await V("none"),this.report({index:W,model:H,responseModel:L,attempt:J,usage:U,outcome:"aborted"}),yield w({type:"finish",reason:"aborted",usage:U??M(),...L?{model:L}:{}});return}if(!F){await V("success"),this.report({index:W,model:H,responseModel:L,attempt:J,usage:U,outcome:"ok"});for(let C of Y)yield C.type==="finish"?w(C):C;return}let _=!G&&F.error.code!=="aborted"&&this.shouldFallBack(F.error,{index:W,model:H,timedOut:S,...F.status!==void 0?{status:F.status}:{},...F.requestId!==void 0?{requestId:F.requestId}:{}});if(await V(_?"failure":"none"),this.report({index:W,model:H,responseModel:L,attempt:J,usage:U,outcome:_?"fallback":b9(F.error),error:F.error}),_){if(U)$=R($??M(),U);continue}let b=!1,q;for(let C of Y){if(C.type==="finish"){q=C;continue}if(C.type==="error")b=!0;yield C}if(!b&&F.error.code!=="aborted")yield{type:"error",error:F.error,...F.status!==void 0?{status:F.status}:{},...F.requestId!==void 0?{requestId:F.requestId}:{}};yield w({type:"finish",reason:F.error.code==="aborted"?"aborted":q?.reason??"error",usage:U??M(),...L?{model:L}:{}});return}}async allow(Q){if(!this.circuit)return!0;try{return await this.circuit.store.allow(w9(Q),this.circuit.policy)}catch{return!0}}async record(Q,$,Z){if(!this.circuit)return;let J=w9($),W;try{W=await this.circuit.store.record(J,Z,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:Q,model:$.provider.model,key:J,state:W})}catch{}}shouldFallBack(Q,$){let Z=this.options.fallbackOn??((J)=>J.retryable);try{return Z(Q,$)}catch{return!1}}report(Q){if(Q.usage===void 0)delete Q.usage;if(Q.responseModel===void 0)delete Q.responseModel;try{this.options.onUsage?.(Q)}catch{}}}function w9(Q){return Q.circuitKey??Q.provider.model}function b9(Q){return Q.code==="aborted"?"aborted":"failed"}function tZ(Q){return{reasoning:Q.every(($)=>$.reasoning),structuredOutput:Q.every(($)=>$.structuredOutput),fileInput:Q.every(($)=>$.fileInput),parallelToolCalls:Q.every(($)=>$.parallelToolCalls),toolSearch:Q.every(($)=>$.toolSearch)}}function aZ(Q,$){let Z,J=new Promise((W)=>{Z=setTimeout(()=>W(a$),$)});return Promise.race([Q,J]).finally(()=>clearTimeout(Z))}async function rZ(Q,$,Z={}){let J=Z.samples??1;if(!Number.isInteger(J)||J<1)throw RangeError(`evalChain: samples must be a positive integer, got ${J}.`);let W=[];for(let X=0;X<Q.entries.length;X++){let G=Q.leg(X),H={index:X,model:G.model,results:[],errors:[]};for(let K=0;K<J;K++)try{H.results.push(await $(G,{index:X,sample:K}))}catch(V){H.errors.push({sample:K,error:V})}W.push(H)}return W}class r 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 KQ extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class IQ{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 KQ(Q);if($!==void 0&&$<Z.lostBefore)throw new r(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)=>I9($,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)=>I9($,X))}}catch(J){I9($,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 r($,J,Q.lostBefore);let X=Q.frames,G=X[0]?.seq;if(G===void 0)break;let H=Math.max(0,J-G);if(H>=X.length)break;let K=X[H];yield K,J=K.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 v9=new IQ;function I9(Q,$){try{Q.onInternalError?.($)}catch{}}class vQ{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 f9=new vQ;class y9{now;receipts=new Map;sweepAt=1024;constructor(Q=Date.now){this.now=Q}async claim(Q,$){let Z=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Z);let J=this.receipts.get(Q);if(J&&J.expiresAt>Z)return J.result?{status:"replay",result:structuredClone(J.result)}:{status:"blocked"};return this.receipts.set(Q,{expiresAt:$}),{status:"claimed"}}async complete(Q,$,Z){this.receipts.set(Q,{result:structuredClone($),expiresAt:Z})}async release(Q){let $=this.receipts.get(Q);if($&&!$.result)this.receipts.delete(Q)}get size(){return this.receipts.size}sweep(Q){for(let[$,Z]of this.receipts)if(Z.expiresAt<=Q)this.receipts.delete($);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var r$="pending",h9="done:",eZ=`
|
|
19
19
|
if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
|
|
20
20
|
local held = redis.call('GET', KEYS[1])
|
|
21
21
|
if not held then return ARGV[1] end
|
|
22
|
-
return held`,
|
|
22
|
+
return held`,Q1=`
|
|
23
23
|
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
24
|
-
return 0`;class y9{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:receipt"}async claim(Q,$){let Z=await this.client.send("EVAL",[aZ,"1",this.key(Q),a$,r$($)]);if(Z==="claimed")return{status:"claimed"};let J=String(Z??"");if(J.startsWith(f9))return{status:"replay",result:JSON.parse(J.slice(f9.length))};return{status:"blocked"}}async complete(Q,$,Z){await this.client.send("SET",[this.key(Q),f9+JSON.stringify($),"PX",r$(Z)])}async release(Q){await this.client.send("EVAL",[rZ,"1",this.key(Q),a$])}key(Q){return`${this.prefix}:${Q}`}get client(){if(this.injectedClient)return this.injectedClient;let Q=LQ(),$=Q.bound(d)?Q.make(d).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function r$(Q){return String(Math.max(1,Math.ceil(Q-Date.now())))}class vQ{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 g9=new vQ;function Z3(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 J3(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...W3(Q,$.event,Z),seq:$.seq}}function W3(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 p(Q,$.messageId,Z,(J)=>({...J,role:$.role}));case"text-delta":if(Q3(Q,$.messageId))return Q;return p(Q,$.messageId,Z,(J)=>({...J,content:J1(J.content,$.delta)}));case"reasoning-delta":if(Q3(Q,$.messageId))return Q;return p(Q,$.messageId,Z,(J)=>({...J,content:W1(J.content,$.delta,$.id)}));case"output-delta":return p(Q,$.messageId,Z,(J)=>({...J,content:$3(J.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return p(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,V=$.part.nested??X?.nested,H=$.part.attachments??X?.attachments,K={...$.part,...G?{progress:G}:{},...V?{nested:V}:{},...H?{attachments:H}:{}},Y=J.content.slice();if(W===-1)Y.push(K);else Y[W]=K;return{...J,content:Y}});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 e$(Q,$.toolCallId,(J)=>({...J,progress:[...J.progress??[],$.data]}));case"nested-event":{let J=$;return e$(Q,$.toolCallId,(W)=>{let X=W.nested??[],G=X.findIndex((Y)=>Y.runId===J.runId),V=X[G]??{runId:J.runId,agent:J.agent,messages:[]},H=$1(V,J,Z),K=G===-1?[...X,H]:X.map((Y,z)=>z===G?H:Y);return{...W,nested:K}})}case"tool-result":{let J=p(Q,$.messageId,Z,(W)=>({...W,content:$3(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"message-id":{let J=Q.messages.findIndex((X)=>X.id===$.localId);if(J===-1)return Q;let W=Q.messages.some((X)=>X.id===$.messageId)?Q.messages.filter((X,G)=>G!==J):Q.messages.map((X,G)=>G===J?{...X,id:$.messageId}:X);return{...Q,messages:W}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return p(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:X3(Q,$.finishReason)};default:return Q}}function X3(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?Q1(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 Q1(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((J)=>J.id),loadedTools:[]};return{...Q,finishReason:$,messages:X3(Z,$)}}function e$(Q,$,Z){for(let J=Q.messages.length-1;J>=0;J--){let W=Q.messages[J],X=W.content.findIndex((K)=>K.type==="tool-call"&&K.toolCallId===$);if(X===-1)continue;if(W.finishReason!==void 0&&!Z1(Q,W,$))return Q;let G=W.content.slice();G[X]=Z(G[X]);let V=Q.messages.slice();V[J]={...W,content:G};let H=Q.runMessageIds.includes(W.id)?Q.runMessageIds:[...Q.runMessageIds,W.id];return{...Q,runMessageIds:H,messages:V}}return Q}function $1(Q,$,Z){let J={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((X)=>X.id),loadedTools:[],finishReason:Q.finishReason},W=W3(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 Z1(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 Q3(Q,$){let Z=Q.messages.find((J)=>J.id===$);return Z!==void 0&&Z.finishReason!==void 0}function p(Q,$,Z,J){let W=Q.messages.findIndex((V)=>V.id===$),X=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(W===-1){let V={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:X,messages:[...Q.messages,J(V)]}}let G=Q.messages.slice();return G[W]=J(G[W]),{...Q,runMessageIds:X,messages:G}}function J1(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 W1(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 $3(Q,$,Z){let J=Q.findIndex(Z);if(J===-1)return[...Q,$];let W=Q.slice();return W[J]=$,W}class c9{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=Z3({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[u9(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=J3(this.state,Q),$.type){case"message":this.write(()=>[u9($.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=u9($);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 u9(Q){return structuredClone(Q)}async function G3(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((K)=>K.content.flatMap((Y)=>Y.type==="tool-result"?[Y.toolCallId]:[])));let V=G.content.map((K)=>K.type==="tool-call"?V3(K):K);for(let K of G.content){if(K.type!=="tool-call"||J.has(K.toolCallId))continue;let Y={type:"tool-result",toolCallId:K.toolCallId,name:K.name,status:"denied",cause:"interrupted"};V.push(Y)}let H={...G,content:V,finishReason:"interrupted"};W[X]=H,Z.push(H)}return{messages:W,settled:Z}}function V3(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((J)=>J.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(X1)}}function X1(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"?V3(Z):Z)}:$)}}var G1=C3,fQ=new Map,H3=new WeakMap,hQ=new Map,V1=4194304,H1=1000,Y1=5,Y3=65536,_3=()=>{};class M3{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 K3=new WeakMap;function K1(Q){let $=K3.get(Q);if(!$)$=new M3,K3.set(Q,$);return $}class S3 extends G1{static kind="agent-controller";store=g9;liveRuns=I9;attachments=_Q;attachmentStorage=q3;fileOwners=v9;nonces=l;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;maxBodyBytes=V1;maxHistoryMessages=H1;maxConcurrentRuns=Y1;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 KQ){let $=await m9(Q,this.maxBodyBytes);if($.error)return yQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,W=C1(Z);if(W.error)return yQ({body:{},error:W.error});let X=W.turn,G=J!==void 0&&Z.regenerate===!0,V=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,H=R3(Z);if(this.requireThread&&!J)return x(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(G&&!this.store.removeMessages)return x(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 l9(413,"history_too_long",`The conversation has ${Z.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let K=await this.runOwner(Q),Y=V?{cancelled:!1,owner:K}:null;if(Y)hQ.set(V,Y);let z=null,B=[],U=async()=>{try{return await j()}finally{if(J&&B.length>0&&z===null)await this.store.appendMessages(J,B).catch((D)=>this.reportHookFailure(D))}},j=async()=>{let D;if(J){let O=await this.store.loadThread(J);if(!O)return x(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});if(D=await this.settleThread(J,O,{write:!0}),G){let P=N1(D);if(!P)return x(409,{code:"nothing_to_regenerate",message:`Thread ${J} has no user turn to answer again.`});B=D.slice(P.index),await this.store.removeMessages(J,B.map((E3)=>E3.id)),D=D.slice(0,P.index),X=X?.localId?{...P.turn,localId:X.localId}:P.turn}}else D=Array.isArray(Z.messages)?Z.messages:[],A1(this.nonces);let L=await this.instructions(Q,{body:H})||void 0,F=await this.context(Q,{body:H}),S=await this.attachmentsFor(Q,J,{body:H});if(Y?.cancelled)return F3();let N=J?new c9(this.store,J,D,(O)=>this.reportHookFailure(O)):null,v=`run_${crypto.randomUUID()}`,w={req:Q,runId:v,threadId:J},_=this.agent.stream({runId:v,messages:D,turn:X,threadId:J,...N?{onMessage:(O)=>N.finish(O)}:{},instructions:L,context:F,attachments:S,body:H,redactError:(O,P)=>this.redactError(O,P,w),nonces:this.nonces,receipts:this.receipts,subject:K}),b=this.liveRuns.register(_,{threadId:J,owner:K,clientRunId:V,onEvent:(O)=>this.dispatchEvent(O,w),onInternalError:(O)=>this.reportHookFailure(O),maxRunDurationMs:this.agent.maxRunDurationMs});if(z=_,N)this.follow(_,N);let{stored:q,hooks:C}=this.persistRun(_,w,b,N);return H3.set(_,q),Q.ctx?.()?.waitUntil(C),_.toResponse()};try{await this.authorizeRequest(Q,{route:"stream",threadId:J,body:H});let D=await this.foreignFile([...X?.files??[],...J?[]:M1(Z.messages)],K);if(D)return D;if(Y?.cancelled)return F3();let L=await this.runLimitKey(Q,{owner:K,threadId:J}),F=L===null?_3:K1(this.liveRuns).take(L,J?`thread:${J}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!F)return l9(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,K,U):await U()}finally{let S=z;if(S)S.result().then(F,F);else F()}}finally{if(Y&&hQ.get(V)===Y)hQ.delete(V)}}async withThread(Q,$,Z){let J=fQ.get(Q)??Promise.resolve(),W,X=new Promise((V)=>{W=V}),G=J.then(()=>X);fQ.set(Q,G),await J;try{let V=await this.liveRuns.find({threadId:Q});if(V&&this.liveRuns.isRunning(V.runId)&&!this.liveRuns.mayAccess(V.runId,$))return gQ();let H=V?this.liveRuns.get(V.runId):null;if(H)H.stop({reason:"superseded by a later turn on this thread"}),await H3.get(H);return await Z()}finally{if(W(),fQ.get(Q)===G)fQ.delete(Q)}}async attach(Q=new KQ){let $=await m9(Q,Y3);if($.error)return yQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:q1(Q,"threadId");if(!J)return x(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 gQ();if(!W)return x(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:O1(Q,Z);try{return U$(this.liveRuns.replay(W.runId,G))}catch(V){if(V instanceof a)return x(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof YQ)return x(404,{code:V.code,message:V.message});throw V}}async stop(Q=new KQ){let $=await m9(Q,Y3);if($.error)return yQ($);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=hQ.get(Z.clientRunId);if(G){if(G.owner!==null&&G.owner!==J)return gQ();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 gQ();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 XQ(this.attachments,this.attachmentStorage,J)}async upload(Q=new KQ){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=B1($.get("body")),G=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof G==="string"&&G.length>0?G:void 0,body:X});let V=U1(await this.attachmentLimits(Q),Z,J,W);if(V)throw new T3(V.code,V.message);let H=typeof G==="string"&&G.length>0&&await this.store.loadThread(G)!==null?G:void 0,K=await this.runOwner(Q),Y=(N)=>this.fileOwners.record(N,{owner:K,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString()}),z=await this.attachmentDestination(Z,Q),B=S1(z,$.get("destination")),U=await this.attachmentScope(Q,H,{body:X}),j=B!=="provider"&&!U;if(j){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()`.');R1()}if(B==="provider"||!U){let N=await z3(this.agent.provider,Z);await Y(N);let v={fileId:N,name:J,mimeType:W,size:Z.size,destination:"provider"};if(j)v.downgraded="no_scope";return v}let D=aQ(),L=await this.attachmentStorage.put({name:rQ(D,J),body:Z,contentType:W}),F=B==="both"?await z3(this.agent.provider,Z):void 0;if(F)await Y(F);let S={id:D,scopeKey:U.key,fileId:F,objectName:L,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString(),destination:B};return await this.attachments.put(U,S),{fileId:F,attachmentId:D,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 _1()}return null}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}redactError(Q,$,Z){return i9(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(N3(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 G3($,(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 V;try{V=await Q.result()}catch(K){J?.close(),await J?.settled(),W=this.safely(()=>this.onError({code:"unknown",message:K instanceof Error?K.message:String(K),retryable:!1},$));return}let H=V.messages;if(J?.close(H),await J?.settled(),$.threadId&&H.length>0)try{await this.store.appendMessages($.threadId,H)}catch(K){this.reportHookFailure(K)}W=this.notifyRun(V,H,$)})(),G=X.then(()=>k1(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 p9=["turn","clientRunId","threadId","messages","regenerate"],z1=["text","files","toolResults"];function R3(Q,$=A3(Q)?p9:[...p9,...z1]){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 B1(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new d9("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new d9("The upload's `body` field must be a JSON object.");return R3($,p9)}class d9 extends uQ{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function z3(Q,$){try{return await Q.upload($)}catch(Z){if(Z instanceof h&&D1.has(Z.status))throw new k3(k(Z).message);throw Z}}var D1=new Set([400,413,415,422]);class T3 extends uQ{constructor(Q,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}function U1(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 ${B3($.size)}; the limit is ${B3(W)}.`};if(X&&X.length>0&&!X.some((G)=>F1(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 F1(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 B3(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 k3 extends uQ{constructor(Q){super(Q);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(Q)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}async function m9(Q,$){let Z=Q?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!j1(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 D3($);let W;try{let G=await L1(Z,$);if(G===null)return D3($);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 j1(Q){return O3(Q)==="application/json"}async function L1(Q,$){if(!Number.isFinite($)||!Q.body)return await Q.text();let Z=Q.body.getReader(),J=[],W=0;for(;;){let{done:V,value:H}=await Z.read();if(V)break;if(W+=H.byteLength,W>$)return await Z.cancel().catch(_3),null;J.push(H)}let X=new Uint8Array(W),G=0;for(let V of J)X.set(V,G),G+=V.byteLength;return new TextDecoder().decode(X)}function D3(Q){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${Q} bytes).`}}function l9(Q,$,Z){return x(Q,{...cQ(P3(Q),Z,Q),code:$})}function yQ(Q){if(Q.status===413)return l9(413,Q.code??"body_too_large",Q.error??"");return x(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function A3(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function C1(Q){let $=A3(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let J=P1($.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;if(Object.keys(Z).length===0)return{};if($===Q.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:J}=$;if(typeof J!=="string")return{error:"turn.localId must be a string."};if(J.length>U3)return{error:`turn.localId is longer than ${U3} characters.`};Z.localId=J}return{turn:Z}}var U3=200;function P1(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 Y of["fileId","attachmentId","name","mimeType"]){let z=J[Y];if(z===void 0||z===null||z==="")continue;if(typeof z!=="string")return`${W}.${Y} must be a string.`;X[Y]=z}let{fileId:G,attachmentId:V,name:H,mimeType:K}=X;if(G?.startsWith(f))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(V!==void 0&&!V.startsWith(f))return`${W}.attachmentId is not a gemi attachment id: it must start with "${f}".`;if(!G&&!V)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...G?{fileId:G}:{},...V?{attachmentId:V}:{},...H!==void 0?{name:H}:{},...K!==void 0?{mimeType:K}:{}})}return $}function O1(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 q1(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function N1(Q){let $=SQ(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 F3(){return x(409,{code:"stopped",message:"The turn was stopped before it started."})}function gQ(){return x(403,cQ("permission","This run belongs to someone else.",403))}function _1(){return x(403,cQ("permission","A file in this turn was uploaded by someone else.",403))}function M1(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 x(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function S1(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 R1(){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 T1=2147483647;function k1(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=T1))return Z;let J,W=new Promise((X)=>{J=setTimeout(X,$)});return Promise.race([Z,W]).finally(()=>clearTimeout(J))}var L3=!1;function A1(Q){if(L3||Bun.env.NODE_ENV!=="production")return;if(!(Q instanceof ZQ))return;L3=!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{BZ as toAgentTools,r as supportsStrict,x1 as s,i9 as redactError,I9 as liveRuns,f3 as generate,tZ as evalChain,l as defaultNonceStore,v9 as defaultFileOwners,_Q as defaultAttachmentStore,g9 as defaultAgentStore,o as ToolNamespace,T as ToolError,V9 as Skill,XQ as ScopedAttachments,GQ as SKILLS_NAMESPACE,y9 as RedisReceiptStore,pQ as RedisNonceStore,u as PendingEscalation,A9 as OpenAIProvider,j9 as OpenAIImageProvider,h9 as MemoryReceiptStore,ZQ as MemoryNonceStore,bQ as MemoryLiveRuns,IQ as MemoryFileOwners,wQ as MemoryCircuitStore,NQ as MemoryAttachmentStore,vQ as MemoryAgentStore,YQ as LiveRunNotFoundError,E1 as JSONSchemaError,i as InvalidAttachmentScopeError,AQ as ImageRequestError,EQ as ImageProvider,D9 as ImageModel,a as FrameCursorEvictedError,HQ as FallbackProvider,K9 as DEFAULT_MAX_RUN_DURATION_MS,E9 as AzureOpenAIProvider,L9 as AzureOpenAIImageProvider,WQ as AttachmentNotFoundError,c as AgentTool,$Q as AgentRunError,t as AgentProvider,S3 as AgentController,z9 as Agent};
|
|
24
|
+
return 0`;class g9{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:receipt"}async claim(Q,$){let Z=await this.client.send("EVAL",[eZ,"1",this.key(Q),r$,e$($)]);if(Z==="claimed")return{status:"claimed"};let J=String(Z??"");if(J.startsWith(h9))return{status:"replay",result:JSON.parse(J.slice(h9.length))};return{status:"blocked"}}async complete(Q,$,Z){await this.client.send("SET",[this.key(Q),h9+JSON.stringify($),"PX",e$(Z)])}async release(Q){await this.client.send("EVAL",[Q1,"1",this.key(Q),r$])}key(Q){return`${this.prefix}:${Q}`}get client(){if(this.injectedClient)return this.injectedClient;let Q=CQ(),$=Q.bound(d)?Q.make(d).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function e$(Q){return String(Math.max(1,Math.ceil(Q-Date.now())))}class fQ{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 u9=new fQ;function J3(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 W3(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...X3(Q,$.event,Z),seq:$.seq}}function X3(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 p(Q,$.messageId,Z,(J)=>({...J,role:$.role}));case"text-delta":if($3(Q,$.messageId))return Q;return p(Q,$.messageId,Z,(J)=>({...J,content:X1(J.content,$.delta)}));case"reasoning-delta":if($3(Q,$.messageId))return Q;return p(Q,$.messageId,Z,(J)=>({...J,content:G1(J.content,$.delta,$.id)}));case"output-delta":return p(Q,$.messageId,Z,(J)=>({...J,content:Z3(J.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return p(Q,$.messageId,Z,(J)=>{let W=J.content.findIndex((B)=>B.type==="tool-call"&&B.toolCallId===$.part.toolCallId),X=W===-1?void 0:J.content[W],G=$.part.progress??X?.progress,H=$.part.nested??X?.nested,K=$.part.attachments??X?.attachments,V={...$.part,...G?{progress:G}:{},...H?{nested:H}:{},...K?{attachments:K}:{}},z=J.content.slice();if(W===-1)z.push(V);else z[W]=V;return{...J,content:z}});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 Q3(Q,$.toolCallId,(J)=>({...J,progress:[...J.progress??[],$.data]}));case"nested-event":{let J=$;return Q3(Q,$.toolCallId,(W)=>{let X=W.nested??[],G=X.findIndex((z)=>z.runId===J.runId),H=X[G]??{runId:J.runId,agent:J.agent,messages:[]},K=J1(H,J,Z),V=G===-1?[...X,K]:X.map((z,B)=>B===G?K:z);return{...W,nested:V}})}case"tool-result":{let J=p(Q,$.messageId,Z,(W)=>({...W,content:Z3(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"message-id":{let J=Q.messages.findIndex((X)=>X.id===$.localId);if(J===-1)return Q;let W=Q.messages.some((X)=>X.id===$.messageId)?Q.messages.filter((X,G)=>G!==J):Q.messages.map((X,G)=>G===J?{...X,id:$.messageId}:X);return{...Q,messages:W}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return p(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:G3(Q,$.finishReason)};default:return Q}}function G3(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?$1(Z,$):Z)}function $1(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?Z1(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 Z1(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((J)=>J.id),loadedTools:[]};return{...Q,finishReason:$,messages:G3(Z,$)}}function Q3(Q,$,Z){for(let J=Q.messages.length-1;J>=0;J--){let W=Q.messages[J],X=W.content.findIndex((V)=>V.type==="tool-call"&&V.toolCallId===$);if(X===-1)continue;if(W.finishReason!==void 0&&!W1(Q,W,$))return Q;let G=W.content.slice();G[X]=Z(G[X]);let H=Q.messages.slice();H[J]={...W,content:G};let K=Q.runMessageIds.includes(W.id)?Q.runMessageIds:[...Q.runMessageIds,W.id];return{...Q,runMessageIds:K,messages:H}}return Q}function J1(Q,$,Z){let J={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((X)=>X.id),loadedTools:[],finishReason:Q.finishReason},W=X3(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 W1(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 $3(Q,$){let Z=Q.messages.find((J)=>J.id===$);return Z!==void 0&&Z.finishReason!==void 0}function p(Q,$,Z,J){let W=Q.messages.findIndex((H)=>H.id===$),X=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(W===-1){let H={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:X,messages:[...Q.messages,J(H)]}}let G=Q.messages.slice();return G[W]=J(G[W]),{...Q,runMessageIds:X,messages:G}}function X1(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 G1(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 Z3(Q,$,Z){let J=Q.findIndex(Z);if(J===-1)return[...Q,$];let W=Q.slice();return W[J]=$,W}class m9{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=J3({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[c9(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=W3(this.state,Q),$.type){case"message":this.write(()=>[c9($.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=c9($);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 c9(Q){return structuredClone(Q)}async function V3(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((V)=>V.content.flatMap((z)=>z.type==="tool-result"?[z.toolCallId]:[])));let H=G.content.map((V)=>V.type==="tool-call"?H3(V):V);for(let V of G.content){if(V.type!=="tool-call"||J.has(V.toolCallId))continue;let z={type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"interrupted"};H.push(z)}let K={...G,content:H,finishReason:"interrupted"};W[X]=K,Z.push(K)}return{messages:W,settled:Z}}function H3(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((J)=>J.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(V1)}}function V1(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"?H3(Z):Z)}:$)}}var H1=P3,hQ=new Map,Y3=new WeakMap,yQ=new Map,Y1=4194304,K1=1000,z1=5,K3=65536,M3=()=>{};class S3{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 z3=new WeakMap;function B1(Q){let $=z3.get(Q);if(!$)$=new S3,z3.set(Q,$);return $}class R3 extends H1{static kind="agent-controller";store=u9;liveRuns=v9;attachments=MQ;attachmentStorage=N3;fileOwners=f9;nonces=l;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;maxBodyBytes=Y1;maxHistoryMessages=K1;maxConcurrentRuns=z1;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 zQ){let $=await p9(Q,this.maxBodyBytes);if($.error)return gQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,W=O1(Z);if(W.error)return gQ({body:{},error:W.error});let X=W.turn,G=J!==void 0&&Z.regenerate===!0,H=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,K=T3(Z);if(this.requireThread&&!J)return x(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(G&&!this.store.removeMessages)return x(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 i9(413,"history_too_long",`The conversation has ${Z.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let V=await this.runOwner(Q),z=H?{cancelled:!1,owner:V}:null;if(z)yQ.set(H,z);let B=null,Y=[],D=async()=>{try{return await j()}finally{if(J&&Y.length>0&&B===null)await this.store.appendMessages(J,Y).catch((U)=>this.reportHookFailure(U))}},j=async()=>{let U;if(J){let O=await this.store.loadThread(J);if(!O)return x(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});if(U=await this.settleThread(J,O,{write:!0}),G){let P=M1(U);if(!P)return x(409,{code:"nothing_to_regenerate",message:`Thread ${J} has no user turn to answer again.`});Y=U.slice(P.index),await this.store.removeMessages(J,Y.map((x3)=>x3.id)),U=U.slice(0,P.index),X=X?.localId?{...P.turn,localId:X.localId}:P.turn}}else U=Array.isArray(Z.messages)?Z.messages:[],x1(this.nonces);let L=await this.instructions(Q,{body:K})||void 0,F=await this.context(Q,{body:K}),S=await this.attachmentsFor(Q,J,{body:K});if(z?.cancelled)return j3();let N=J?new m9(this.store,J,U,(O)=>this.reportHookFailure(O)):null,v=`run_${crypto.randomUUID()}`,w={req:Q,runId:v,threadId:J},_=this.agent.stream({runId:v,messages:U,turn:X,threadId:J,...N?{onMessage:(O)=>N.finish(O)}:{},instructions:L,context:F,attachments:S,body:K,redactError:(O,P)=>this.redactError(O,P,w),nonces:this.nonces,receipts:this.receipts,subject:V}),b=this.liveRuns.register(_,{threadId:J,owner:V,clientRunId:H,onEvent:(O)=>this.dispatchEvent(O,w),onInternalError:(O)=>this.reportHookFailure(O),maxRunDurationMs:this.agent.maxRunDurationMs});if(B=_,N)this.follow(_,N);let{stored:q,hooks:C}=this.persistRun(_,w,b,N);return Y3.set(_,q),Q.ctx?.()?.waitUntil(C),_.toResponse()};try{await this.authorizeRequest(Q,{route:"stream",threadId:J,body:K});let U=await this.foreignFile([...X?.files??[],...J?[]:R1(Z.messages)],V);if(U)return U;if(z?.cancelled)return j3();let L=await this.runLimitKey(Q,{owner:V,threadId:J}),F=L===null?M3:B1(this.liveRuns).take(L,J?`thread:${J}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!F)return i9(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,V,D):await D()}finally{let S=B;if(S)S.result().then(F,F);else F()}}finally{if(z&&yQ.get(H)===z)yQ.delete(H)}}async withThread(Q,$,Z){let J=hQ.get(Q)??Promise.resolve(),W,X=new Promise((H)=>{W=H}),G=J.then(()=>X);hQ.set(Q,G),await J;try{let H=await this.liveRuns.find({threadId:Q});if(H&&this.liveRuns.isRunning(H.runId)&&!this.liveRuns.mayAccess(H.runId,$))return uQ();let K=H?this.liveRuns.get(H.runId):null;if(K)K.stop({reason:"superseded by a later turn on this thread"}),await Y3.get(K);return await Z()}finally{if(W(),hQ.get(Q)===G)hQ.delete(Q)}}async attach(Q=new zQ){let $=await p9(Q,K3);if($.error)return gQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:_1(Q,"threadId");if(!J)return x(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 uQ();if(!W)return x(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:N1(Q,Z);try{return F$(this.liveRuns.replay(W.runId,G))}catch(H){if(H instanceof r)return x(410,{code:H.code,message:H.message,oldestSeq:H.oldest});if(H instanceof KQ)return x(404,{code:H.code,message:H.message});throw H}}async stop(Q=new zQ){let $=await p9(Q,K3);if($.error)return gQ($);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=yQ.get(Z.clientRunId);if(G){if(G.owner!==null&&G.owner!==J)return uQ();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 uQ();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 GQ(this.attachments,this.attachmentStorage,J)}async upload(Q=new zQ){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=U1($.get("body")),G=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof G==="string"&&G.length>0?G:void 0,body:X});let H=j1(await this.attachmentLimits(Q),Z,J,W);if(H)throw new k3(H.code,H.message);let K=typeof G==="string"&&G.length>0&&await this.store.loadThread(G)!==null?G:void 0,V=await this.runOwner(Q),z=(N)=>this.fileOwners.record(N,{owner:V,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString()}),B=await this.attachmentDestination(Z,Q),Y=T1(B,$.get("destination")),D=await this.attachmentScope(Q,K,{body:X}),j=Y!=="provider"&&!D;if(j){if(Y==="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()`.');k1()}if(Y==="provider"||!D){let N=await B3(this.agent.provider,Z);await z(N);let v={fileId:N,name:J,mimeType:W,size:Z.size,destination:"provider"};if(j)v.downgraded="no_scope";return v}let U=rQ(),L=await this.attachmentStorage.put({name:eQ(U,J),body:Z,contentType:W}),F=Y==="both"?await B3(this.agent.provider,Z):void 0;if(F)await z(F);let S={id:U,scopeKey:D.key,fileId:F,objectName:L,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString(),destination:Y};return await this.attachments.put(D,S),{fileId:F,attachmentId:U,name:J,mimeType:W,size:Z.size,destination:Y}}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 S1()}return null}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}redactError(Q,$,Z){return o9(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(_3(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 V3($,(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 H;try{H=await Q.result()}catch(V){J?.close(),await J?.settled(),W=this.safely(()=>this.onError({code:"unknown",message:V instanceof Error?V.message:String(V),retryable:!1},$));return}let K=H.messages;if(J?.close(K),await J?.settled(),$.threadId&&K.length>0)try{await this.store.appendMessages($.threadId,K)}catch(V){this.reportHookFailure(V)}W=this.notifyRun(H,K,$)})(),G=X.then(()=>E1(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 d9=["turn","clientRunId","threadId","messages","regenerate"],D1=["text","files","toolResults"];function T3(Q,$=E3(Q)?d9:[...d9,...D1]){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 U1(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new l9("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new l9("The upload's `body` field must be a JSON object.");return T3($,d9)}class l9 extends cQ{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function B3(Q,$){try{return await Q.upload($)}catch(Z){if(Z instanceof h&&F1.has(Z.status))throw new A3(k(Z).message);throw Z}}var F1=new Set([400,413,415,422]);class k3 extends cQ{constructor(Q,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}function j1(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 ${D3($.size)}; the limit is ${D3(W)}.`};if(X&&X.length>0&&!X.some((G)=>L1(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 L1(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 D3(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 A3 extends cQ{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 p9(Q,$){let Z=Q?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!C1(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 U3($);let W;try{let G=await P1(Z,$);if(G===null)return U3($);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 C1(Q){return q3(Q)==="application/json"}async function P1(Q,$){if(!Number.isFinite($)||!Q.body)return await Q.text();let Z=Q.body.getReader(),J=[],W=0;for(;;){let{done:H,value:K}=await Z.read();if(H)break;if(W+=K.byteLength,W>$)return await Z.cancel().catch(M3),null;J.push(K)}let X=new Uint8Array(W),G=0;for(let H of J)X.set(H,G),G+=H.byteLength;return new TextDecoder().decode(X)}function U3(Q){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${Q} bytes).`}}function i9(Q,$,Z){return x(Q,{...mQ(O3(Q),Z,Q),code:$})}function gQ(Q){if(Q.status===413)return i9(413,Q.code??"body_too_large",Q.error??"");return x(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function E3(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function O1(Q){let $=E3(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let J=q1($.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;if(Object.keys(Z).length===0)return{};if($===Q.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:J}=$;if(typeof J!=="string")return{error:"turn.localId must be a string."};if(J.length>F3)return{error:`turn.localId is longer than ${F3} characters.`};Z.localId=J}return{turn:Z}}var F3=200;function q1(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 z of["fileId","attachmentId","name","mimeType"]){let B=J[z];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${W}.${z} must be a string.`;X[z]=B}let{fileId:G,attachmentId:H,name:K,mimeType:V}=X;if(G?.startsWith(f))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(H!==void 0&&!H.startsWith(f))return`${W}.attachmentId is not a gemi attachment id: it must start with "${f}".`;if(!G&&!H)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...G?{fileId:G}:{},...H?{attachmentId:H}:{},...K!==void 0?{name:K}:{},...V!==void 0?{mimeType:V}:{}})}return $}function N1(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 _1(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function M1(Q){let $=RQ(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 j3(){return x(409,{code:"stopped",message:"The turn was stopped before it started."})}function uQ(){return x(403,mQ("permission","This run belongs to someone else.",403))}function S1(){return x(403,mQ("permission","A file in this turn was uploaded by someone else.",403))}function R1(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 x(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function T1(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 L3=!1;function k1(){if(L3)return;L3=!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 A1=2147483647;function E1(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=A1))return Z;let J,W=new Promise((X)=>{J=setTimeout(X,$)});return Promise.race([Z,W]).finally(()=>clearTimeout(J))}var C3=!1;function x1(Q){if(C3||Bun.env.NODE_ENV!=="production")return;if(!(Q instanceof JQ))return;C3=!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{DZ as toAgentTools,e as supportsStrict,b1 as s,o9 as redactError,v9 as liveRuns,h3 as generate,rZ as evalChain,l as defaultNonceStore,f9 as defaultFileOwners,MQ as defaultAttachmentStore,u9 as defaultAgentStore,o as ToolNamespace,T as ToolError,H9 as Skill,GQ as ScopedAttachments,VQ as SKILLS_NAMESPACE,g9 as RedisReceiptStore,dQ as RedisNonceStore,u as PendingEscalation,E9 as OpenAIProvider,L9 as OpenAIImageProvider,y9 as MemoryReceiptStore,JQ as MemoryNonceStore,IQ as MemoryLiveRuns,vQ as MemoryFileOwners,bQ as MemoryCircuitStore,_Q as MemoryAttachmentStore,fQ as MemoryAgentStore,KQ as LiveRunNotFoundError,w1 as JSONSchemaError,i as InvalidAttachmentScopeError,EQ as ImageRequestError,xQ as ImageProvider,U9 as ImageModel,r as FrameCursorEvictedError,YQ as FallbackProvider,z9 as DEFAULT_MAX_RUN_DURATION_MS,x9 as AzureOpenAIProvider,C9 as AzureOpenAIImageProvider,XQ as AttachmentNotFoundError,c as AgentTool,ZQ as AgentRunError,a as AgentProvider,R3 as AgentController,B9 as Agent};
|
|
25
25
|
|
|
26
|
-
//# debugId=
|
|
26
|
+
//# debugId=EBB9D147B12F8B4F64756E2164756E21
|