gemi 0.239.0 → 0.241.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 +3 -3
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/client/conformance.d.ts.map +1 -1
- package/dist/ai/client/index.js +88 -40
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/client/reducer.d.ts +6 -6
- package/dist/ai/client/reducer.d.ts.map +1 -1
- package/dist/ai/index.js +12 -12
- package/dist/ai/index.js.map +3 -3
- package/dist/ai/providers/anthropicRequest.d.ts +2 -1
- package/dist/ai/providers/anthropicRequest.d.ts.map +1 -1
- package/dist/ai/providers/request.d.ts +11 -0
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/testing/index.js +1 -1
- package/dist/ai/useChat.d.ts.map +1 -1
- package/dist/{chunk-pkew0k7c.js → chunk-2f2t8j4j.js} +1 -1
- package/dist/{chunk-mmc5bbf4.js → chunk-4j0h4q8v.js} +27 -27
- package/dist/{chunk-mmc5bbf4.js.map → chunk-4j0h4q8v.js.map} +3 -3
- package/dist/chunk-8z16b2j2.js +5 -0
- package/dist/{chunk-j3zz8046.js.map → chunk-8z16b2j2.js.map} +3 -3
- package/dist/{chunk-7axcthef.js → chunk-bn2b57qq.js} +1 -1
- package/dist/{chunk-92zmwb33.js → chunk-cfpzhc8n.js} +2 -2
- package/dist/{chunk-92zmwb33.js.map → chunk-cfpzhc8n.js.map} +1 -1
- package/dist/chunk-gpngw61t.js +12 -0
- package/dist/{chunk-m0n0ddd2.js.map → chunk-gpngw61t.js.map} +4 -4
- package/dist/{chunk-sx2gadhs.js → chunk-n1phcznj.js} +1 -1
- package/dist/{chunk-q8pr18w6.js → chunk-n30y9dc5.js} +1 -1
- package/dist/chunks/{RealtimeClient-DRVodyn1.js → RealtimeClient-Di8ozsFv.js} +2 -2
- package/dist/chunks/{RealtimeClient-DRVodyn1.js.map → RealtimeClient-Di8ozsFv.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-1WtAS7dH.js → ThemeProvider-wwhaAveo.js} +28 -9
- package/dist/chunks/ThemeProvider-wwhaAveo.js.map +1 -0
- package/dist/chunks/{fetchFileRequest-CVCelZqS.js → fetchFileRequest-B3dlL_eX.js} +2 -2
- package/dist/chunks/{fetchFileRequest-CVCelZqS.js.map → fetchFileRequest-B3dlL_eX.js.map} +1 -1
- package/dist/chunks/{live-twEh9Qwt.js → live-DZBIdcg7.js} +3 -3
- package/dist/chunks/{live-twEh9Qwt.js.map → live-DZBIdcg7.js.map} +1 -1
- package/dist/chunks/{mutationExtras-CM77Ur-9.js → mutationExtras-CnzA8Ie-.js} +2 -2
- package/dist/chunks/{mutationExtras-CM77Ur-9.js.map → mutationExtras-CnzA8Ie-.js.map} +1 -1
- package/dist/chunks/{subscriptionStream-DQp1Krwi.js → subscriptionStream-DLA3izlS.js} +2 -2
- package/dist/chunks/{subscriptionStream-DQp1Krwi.js.map → subscriptionStream-DLA3izlS.js.map} +1 -1
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/index.js +24 -17
- package/dist/client/index.js.map +1 -1
- package/dist/client/useNavigate.d.ts +8 -0
- package/dist/client/useNavigate.d.ts.map +1 -1
- package/dist/facades/index.js +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/file-storage/drivers/FileSystemDriver.d.ts +55 -7
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
- package/dist/services/index.js +1 -1
- package/dist/testing/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-j3zz8046.js +0 -5
- package/dist/chunk-m0n0ddd2.js +0 -12
- package/dist/chunks/ThemeProvider-1WtAS7dH.js.map +0 -1
- /package/dist/{chunk-pkew0k7c.js.map → chunk-2f2t8j4j.js.map} +0 -0
- /package/dist/{chunk-7axcthef.js.map → chunk-bn2b57qq.js.map} +0 -0
- /package/dist/{chunk-sx2gadhs.js.map → chunk-n1phcznj.js.map} +0 -0
- /package/dist/{chunk-q8pr18w6.js.map → chunk-n30y9dc5.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ca as QZ,da as WZ,ea as XZ,fa as e6,ga as Q0,ha as J0,ia as W$,ja as $0,ka as Z0,la as RJ,ma as W0,na as X0,oa as K0,pa as G0}from"../chunk-
|
|
2
|
+
import{ca as QZ,da as WZ,ea as XZ,fa as e6,ga as Q0,ha as J0,ia as W$,ja as $0,ka as Z0,la as RJ,ma as W0,na as X0,oa as K0,pa as G0}from"../chunk-gpngw61t.js";import{$c as M8,Ac as i,Bc as fZ,Cc as qZ,Dc as B$,Fc as S$,Gc as T$,Hc as R$,Ic as E$,Jc as k$,Kc as j$,Lc as x$,Mc as I$,Nc as w$,Oc as f$,Pc as q$,Qc as b$,Sc as b6,Tc as v6,Uc as y6,Vc as h6,Wc as g6,Xc as OQ,Yc as c6,Zc as S8,_c as u6,ad as m6,bd as p6,cd as l6,dd as gQ,ed as UJ,fd as i6,gd as d6,hd as A8,id as n6,jc as Q$,jd as o6,kc as P8,kd as s6,lc as N8,ld as a6,mc as J$,md as t6,nd as R8,od as r6,pd as FJ,qc as r$,rc as e$,sc as d$,tc as FQ,uc as T6,vc as g,wc as _$,xc as O$,zc as L$}from"../chunk-4j0h4q8v.js";import{$d as XQ,Ed as o,Fd as $$,Id as F8,Jd as C8,Kd as U8,Ld as oQ,Md as _8,Nd as QJ,Od as sQ,Pd as nJ,Qd as O8,Rd as L8,Sd as JJ,Td as B8,Zd as KQ,ae as Z$,be as j6,ce as x6,de as I6,ee as w6,fe as f6,ge as q6,td as GZ,ud as S,vd as k}from"../chunk-samm4h7d.js";import{xe as H$}from"../chunk-w9v8bbp8.js";import"../chunk-6gek696n.js";import{Bj as z8,Cj as qJ,Vi as w,ti as K8,wi as V8}from"../chunk-8z16b2j2.js";import{Dj as G8,Fj as rQ,Gj as eQ}from"../chunk-2g1h9ktj.js";import{Jj as R6,Kj as E6,Lj as k6}from"../chunk-e4adgvd6.js";import{Yj as n}from"../chunk-0xmk4jyj.js";import"../chunk-768yza4f.js";import{dl as Y8,el as D8,fl as H8,gl as dJ}from"../chunk-0wa8ztk5.js";import"../chunk-6wv3k8ap.js";import{Cl as vQ,ml as ZQ,nl as WQ}from"../chunk-ccymw1ed.js";import{Pl as _Z}from"../chunk-aczp96k5.js";import"../chunk-x68jra5n.js";import{wm as BZ}from"../chunk-3mq0wmq7.js";import"../chunk-wgb26e02.js";import"../chunk-vqmy8jfr.js";import{Tm as XJ}from"../chunk-zsmwmg8x.js";import"../chunk-c7hbdsjv.js";import{existsSync as q8,readdirSync as z0,readFileSync as z$}from"fs";import{isAbsolute as b8,join as xQ,relative as v8,sep as y8}from"path";var Y$="prompts.json",h8=/\{\{>\s*([\w./-]+)\s*\}\}/g,K$=/\{\{(\w+)\}\}/g,g8=/^[\w-]+(\/[\w-]+)*$/,G$={dir:"app/agents",shared:"prompts"},wQ={},ZJ=new Map,IQ;function c8(){if(IQ===void 0){let Q=xQ(XJ(),"dist","server",Y$);IQ=q8(Q)?JSON.parse(z$(Q,"utf8")):null}return IQ??null}function u8(Q){return Q.replace(/\r?\n$/,"")}function V$(){return wQ.cache??Bun.env.NODE_ENV==="production"}function m8(Q,J){if(!g8.test(Q))throw Error(`"${Q}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let $=J.dir??wQ.dir??G$.dir,Z=b8($)?$:xQ(process.cwd(),$),W=Q.includes("/")?`${Q}.md`:xQ(J.shared??wQ.shared??G$.shared,`${Q}.md`);return xQ(Z,W)}function p8(Q,J){let $=m8(Q,J),Z=V$()?ZJ.get($):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let K=c8()?.[v8(XJ(),$).split(y8).join("/")];if(K!==void 0)return K}let X;try{X=u8(z$($,"utf8"))}catch(K){if(K.code==="ENOENT"){let G=W?` or in dist/server/${Y$}`:"";throw Error(`The prompt "${Q}" does not exist (looked for ${$}${G}).`)}throw K}if(V$())ZJ.set($,X);return X}function WJ(Q,J,$){if(J.includes(Q))throw Error(`The prompt "${Q}" includes itself: ${[...J,Q].join(" > ")}.`);return p8(Q,$).replace(h8,(Z,W)=>WJ(W,[...J,Q],$))}class D${static configure(Q){wQ={...Q},ZJ.clear(),IQ=void 0}static render(Q,J={},$={}){return WJ(Q,[],$).replace(K$,(Z,W)=>{if(!Object.hasOwn(J,W))throw Error(`The prompt "${Q}" has no value for {{${W}}}.`);return String(J[W])})}static placeholders(Q,J={}){let $=[...WJ(Q,[],J).matchAll(K$)].map((Z)=>Z[1]);return[...new Set($)]}}class KJ extends H${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await i.sweep({limit:100})===100);}}var qQ=20,l8=300,i8=200;function N$(Q,J){if(J<=0||Q.length===0)return null;let $=(X,K)=>K.createdAt-X.createdAt||(X.id<K.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...Q.filter((X)=>!g(X.state)).sort($),...Q.filter((X)=>g(X.state)).sort($)].slice(0,J).map((X)=>{let K=[`- ${X.id} (${X.toolName})`];if(X.state==="waiting")K.push(`waiting for ${(X.after??[]).join(", ")} since ${fQ(X.createdAt)}`);else if(X.state==="running")K.push(`running since ${fQ(X.createdAt)}`);else if(X.state==="ok")K.push(`finished at ${fQ(X.settledAt??X.updatedAt)}`);else{let G=X.error?`${X.error.code}: ${P$(X.error.message,i8)}`:"failed";K.push(`failed at ${fQ(X.settledAt??X.updatedAt)} (${G})`)}if(X.summary!==void 0)K.push(`summary: ${P$(JSON.stringify(X.summary),l8)}`);if(X.orphaned)K.push("its tool call was lost when the turn that started it was cut short");return K.join("; ")}),"</jobs>"].join(`
|
|
3
3
|
`)}function fQ(Q){return new Date(Q).toISOString().replace(/\.\d{3}Z$/,"Z")}function P$(Q,J){return Q.length<=J?Q:`${Q.slice(0,J-1)}\u2026`}var F$=["after_jobs","batch_key","queued","inbox","job_checkpoint"],C$=20;class GJ{table;sql;dialect;connection;later;constructor(Q,J={}){let $=J.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The agent jobs table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);this.table=$,this.sql=Q.sql,this.dialect=Q.dialect,this.connection=Q.name}async createTable(){for(let Q of d8(this.dialect,this.table))await this.sql.unsafe(Q)}async transaction(Q){if(this.connection===void 0||this.joinable())return Q();return vQ(this.sql,()=>Q(),{connection:this.connection,dialect:this.dialect})}async create(Q){let J=Q.after!==void 0||Q.batch!==void 0||Q.queued!==void 0;if(J)await this.requireLaterColumns("A job with `after` or `batch`");let $=this.q(),Z=this.clock($),W=Q.state??"running";if(J)await $`
|
|
4
4
|
INSERT INTO ${this.name($)}
|
|
5
5
|
(id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
|
|
@@ -177,8 +177,8 @@ import{ca as QZ,da as WZ,ea as XZ,fa as e6,ga as Q0,ha as J0,ia as W$,ja as $0,k
|
|
|
177
177
|
"updated_at" BIGINT NOT NULL,
|
|
178
178
|
"last_used_at" BIGINT,
|
|
179
179
|
"expires_at" BIGINT${Z}
|
|
180
|
-
)`,`CREATE INDEX IF NOT EXISTS "${J}_scope_kind_created_at_idx" ON "${J}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${J}_expires_at_idx" ON "${J}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${J}_scope_key_key" ON "${J}"("scope", "key")`]}var y$={n:0,mean:0,stddev:0,low:null,high:null};function d(Q){let J=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if(Q<0.5)return Math.log(Math.PI/Math.sin(Math.PI*Q))-d(1-Q);Q-=1;let $=J[0],Z=Q+7.5;for(let W=1;W<9;W++)$+=J[W]/(Q+W);return 0.5*Math.log(2*Math.PI)+(Q+0.5)*Math.log(Z)-Z+Math.log($)}function v$(Q,J,$){let W=1,X=1-(Q+J)*$/(Q+1);if(Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;X=1/X;let K=X;for(let G=1;G<=300;G++){let z=2*G,V=G*(J-G)*$/((Q+z-1)*(Q+z));if(X=1+V*X,Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+V/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(X=1/X,K*=X*W,V=-(Q+G)*(Q+J+G)*$/((Q+z)*(Q+z+1)),X=1+V*X,Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+V/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;X=1/X;let Y=X*W;if(K*=Y,Math.abs(Y-1)<0.00000000000001)break}return K}function o8(Q,J,$){if(Q<=0)return 0;if(Q>=1)return 1;let Z=Math.exp(d(J+$)-d(J)-d($)+J*Math.log(Q)+$*Math.log(1-Q));return Q<(J+1)/(J+$+2)?Z*v$(J,$,Q)/J:1-Z*v$($,J,1-Q)/$}function YJ(Q,J){return o8(J/(J+Q*Q),J/2,0.5)}function s8(Q){if(!(Q>0))return Number.POSITIVE_INFINITY;let J=1.959964,$=2;while(YJ($,Q)>0.05)$*=2;for(let Z=0;Z<100;Z++){let W=(J+$)/2;if(YJ(W,Q)>0.05)J=W;else $=W}return(J+$)/2}function a8(Q,J,$,Z){let W=Q+$,X=J+Z,K=(Y,D)=>d(Y+1)-d(D+1)-d(Y-D+1),G=(Y)=>Math.exp(K(J,Y)+K(Z,W-Y)-K(X,W)),z=G(Q),V=0;for(let Y=Math.max(0,W-Z);Y<=Math.min(J,W);Y++){let D=G(Y);if(D<=z*1.0000001)V+=D}return Math.min(1,V)}function h$(Q,J){if(Q.length<2)return 0;let $=Q.reduce((W,X)=>W+(X-J)**2,0),Z=Math.sqrt($/(Q.length-1));return Z<0.000000000001*Math.max(1,Math.abs(J))?0:Z}function DJ(Q){let J=Q.length;if(J===0)return y$;let $=Q.map((G)=>G?1:0),Z=$.reduce((G,z)=>G+z,0)/J,W=3.841458881296,X=(Z+W/(2*J))/(1+W/J),K=1.959964*Math.sqrt(Z*(1-Z)/J+W/(4*J*J))/(1+W/J);return{n:J,mean:Z,stddev:h$($,Z),low:Math.max(0,X-K),high:Math.min(1,X+K)}}function HJ(Q){let J=Q.length;if(J===0)return y$;let $=Q.reduce((X,K)=>X+K,0)/J,Z=h$(Q,$);if(J<2||Z===0)return{n:J,mean:$,stddev:Z,low:null,high:null};let W=s8(J-1)*Z/Math.sqrt(J);return{n:J,mean:$,stddev:Z,low:$-W,high:$+W}}function PQ(Q,J,$){return{before:Q.mean,after:J.mean,delta:J.mean-Q.mean,p:$,pAdjusted:$,significant:!1}}function g$(Q,J){if(Q.n===0||J.n===0)return PQ(Q,J,null);let $=(Z)=>Math.round(Z.mean*Z.n);return PQ(Q,J,a8($(Q),Q.n,$(J),J.n))}function c$(Q,J){if(Q.n<2||J.n<2)return PQ(Q,J,null);let $=Q.stddev**2/Q.n,Z=J.stddev**2/J.n,W=Math.sqrt($+Z);if(W===0)return PQ(Q,J,null);let X=($+Z)**2/($**2/(Q.n-1)+Z**2/(J.n-1));return PQ(Q,J,YJ((J.mean-Q.mean)/W,X))}function u$(Q,J,$){if($==="holm"){let Z=Q.filter((X)=>X.p!==null).sort((X,K)=>X.p-K.p),W=0;Z.forEach((X,K)=>{W=Math.max(W,Math.min(1,X.p*(Z.length-K))),X.pAdjusted=W})}else for(let Z of Q)Z.pAdjusted=Z.p;for(let Z of Q)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<J&&Z.delta!==0}class hQ{name;cases;runs;concurrency;graders;pricing;task;constructor(Q){this.name=Q.name,this.cases=Q.cases,this.runs=Q.runs??1,this.concurrency=Q.concurrency??1,this.task=Q.task,this.graders=typeof Q.graders==="function"?Q.graders({judge:(J)=>hQ.judge(J)}):Q.graders,this.pricing=Q.pricing}static create(Q){let J=`The eval "${Q.name}"`;NQ(Q.runs,J,"runs"),NQ(Q.concurrency,J,"concurrency");let $=new Set;for(let W of Q.cases){if($.has(W.id))throw Error(`${J} has two cases with the id "${W.id}".`);$.add(W.id)}let Z=new hQ(Q);for(let[W,X]of Object.entries(Z.graders))if(typeof X!=="function"&&X.kind==="judge")NQ(X.samples,`${J}'s judge "${W}"`,"samples");return Z}static judge(Q){return{...Q,kind:"judge"}}static compare(Q,J,$={}){return n$(Q,J,$)}static format(Q,J={}){return Q9(Q,J)}async run(Q={}){let J=`${this.name}.run`;NQ(Q.runs,J,"runs"),NQ(Q.concurrency,J,"concurrency");let $=Q.only?new Set(Q.only):null;if($){let P=[...$].filter((C)=>!this.cases.some((F)=>F.id===C));if(P.length>0)throw Error(`The eval "${this.name}" has no case ${P.map((C)=>`"${C}"`).join(", ")}.`)}let Z=Q.runs??this.runs,W=Date.now(),X=new AbortController,K=Q.signal?AbortSignal.any([Q.signal,X.signal]):X.signal,G=this.cases.filter((P)=>!$||$.has(P.id)),z={};for(let[P,C]of Object.entries(this.graders)){if(K.aborted)break;if(typeof C==="function"||C.kind!=="judge"||!C.calibration)continue;z[P]=await this.calibrate(C,K)}let V=G.flatMap((P)=>Array.from({length:Z},(C,F)=>({test:P,run:F+1}))),Y=Array.from({length:V.length}),D=0,N,H=async()=>{while(D<V.length&&!K.aborted){let P=D++,C=V[P],F=await this.sample(C.test,C.run,K,Q.keepOutputs??!1);Y[P]=F;try{Q.onSample?.(F)}catch(L){N??={error:L},X.abort(L)}}},U=Math.min(Q.concurrency??this.concurrency,V.length);if(await Promise.all(Array.from({length:U},H)),N)throw N.error;let _=Y.filter((P)=>P!==void 0);return this.report(_,z,Z,new Date(W).toISOString(),Date.now()-W,{aborted:K.aborted||_.length<V.length,planned:G.map((P)=>P.id)})}async sample(Q,J,$,Z){let W=Date.now(),X,K,G=await FQ(async()=>{try{X=await this.task(Q.input,{case:Q,run:J,signal:$})}catch(U){K=s$(U)}}),z={},V=!1,Y=await FQ(async()=>{if(K!==void 0)return;let U={case:Q,input:Q.input,run:J};for(let[_,P]of Object.entries(this.graders)){if(Q.skip?.includes(_))continue;let C=await m$(P,X,U,$);if(!C)continue;if(z[_]=C,!C.pass&&typeof P!=="function"&&P.gate)V=!0}}),D=Object.values(z).map((U)=>U.score),N=K===void 0&&D.length===0,H=this.pricing?PJ(this.pricing,G.byModel).cost+PJ(this.pricing,Y.byModel).cost:void 0;return{case:Q.id,run:J,pass:K===void 0&&!N&&Object.values(z).every((U)=>U.pass),excluded:V||N,...N?{ungraded:!0}:{},score:K!==void 0||N?0:o$(D),grades:z,...K!==void 0?{error:K}:{},...Z&&K===void 0?{output:X}:{},usage:G.usage,byModel:r8(G.byModel,Y.byModel),judgeUsage:Y.usage,...H!==void 0?{cost:H}:{},durationMs:Date.now()-W}}async calibrate(Q,J){let $=Q.calibration,Z=[],W=0,X=await FQ(async()=>{for(let[z,V]of $.examples.entries()){if(J.aborted)break;let Y=V.id??`example-${z+1}`,D={case:{id:Y,input:V.input},input:V.input,run:0},N=await m$(Q,V.output,D,J),H=N?.pass??!1;if(H===V.expected)W++;else Z.push({id:Y,expected:V.expected,got:H,...N?.note?{note:N.note}:{}})}}),K=$.examples.length,G=K===0?1:W/K;return{n:K,agreement:G,ok:G>=($.minAgreement??0.8),disagreements:Z,usage:X.usage}}report(Q,J,$,Z,W,X){let K=new Set(Object.entries(this.graders).filter(([,N])=>typeof N!=="function"&&N.gate).map(([N])=>N)),G={};for(let N of this.cases){let H=Q.filter((U)=>U.case===N.id);if(H.length===0)continue;G[N.id]={...p$(H),graders:l$(H,K)}}let z=S(),V=S(),Y={};for(let N of Q){z=k(z,N.usage),V=k(V,N.judgeUsage);for(let[H,U]of Object.entries(N.byModel))Y[H]=k(Y[H]??S(),U)}let D=this.pricing?PJ(this.pricing,Y):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:$,aborted:X.aborted,planned:X.planned,samples:Q,cases:G,graders:l$(Q,K),calibration:J,totals:{...p$(Q),usage:z,judgeUsage:V,byModel:Y,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(Y)}}}}async function m$(Q,J,$,Z){let W=typeof Q==="function"?0.5:Q.threshold??0.5;try{if(typeof Q==="function")return NJ(await Q(J,$),W);if(Q.kind!=="judge")return NJ(await Q.check(J,$),W);return await t8(Q,J,$,W,Z)}catch(X){return{pass:!1,score:0,error:s$(X)}}}async function t8(Q,J,$,Z,W){let X=await Q.prompt(J,$),K=typeof X==="string"?{prompt:X}:X,G=[];for(let D=0;D<(Q.samples??1)&&!W.aborted;D++){let N=await FJ({signal:W,provider:Q.provider,...Q.instructions!==void 0?{instructions:Q.instructions}:{},...K,output:Q.output,...Q.reasoning!==void 0?{reasoning:Q.reasoning}:{},...Q.maxOutputTokens!==void 0?{maxOutputTokens:Q.maxOutputTokens}:{},...Q.temperature!==void 0?{temperature:Q.temperature}:{},logErrors:!1});if(!N.ok){G.push({pass:!1,score:0,error:`The judge failed: ${N.error.message}`});continue}let H=NJ(Q.verdict(N.output,$),Z);if(H)G.push(H)}if(G.length===0)return null;if(G.length===1)return G[0];let z=G.filter((D)=>D.pass).length,V=G.map((D)=>D.note??D.error).filter(Boolean),Y=G.map((D)=>D.error).filter(Boolean);return{pass:z*2>G.length,score:o$(G.map((D)=>D.score)),...V.length>0?{note:V.join(" | ")}:{},...Y.length===G.length?{error:Y.join(" | ")}:{}}}function NJ(Q,J){if(Q===null||Q===void 0)return null;if(typeof Q==="boolean")return{pass:Q,score:Q?1:0};if(typeof Q==="number"){if(!Number.isFinite(Q))throw Error(`A grader answered the score ${Q}.`);let $=i$(Q);return{pass:$>=J,score:$}}return{pass:Q.pass,score:Q.score===void 0?Q.pass?1:0:i$(Q.score),...Q.note!==void 0?{note:Q.note}:{}}}function p$(Q){let J=Q.filter(($)=>!$.excluded);return{samples:Q.length,kept:J.length,passed:J.filter(($)=>$.pass).length,errors:Q.filter(($)=>$.error!==void 0).length,passRate:DJ(J.map(($)=>$.pass)),score:HJ(J.map(($)=>$.score))}}function l$(Q,J){let $=Q.filter((W)=>!W.excluded),Z=[...new Set(Q.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let K=(J.has(W)?Q:$).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:DJ(K.map((G)=>G.pass)),score:HJ(K.map((G)=>G.score))}]}))}function PJ(Q,J){let $=0,Z=[];for(let[W,X]of Object.entries(J)){let K=d$(Q,W,X);if(K===void 0){Z.push(W);continue}$+=K}return{cost:$,unpriced:Z}}function r8(...Q){let J={};for(let $ of Q)for(let[Z,W]of Object.entries($))J[Z]=k(J[Z]??S(),W);return J}function n$(Q,J,$){for(let[P,C]of[["baseline",Q],["current report",J]])if(C.aborted)throw Error(`Eval.compare: the ${P} for "${C.name}" was aborted (${C.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`);let Z=$.alpha??0.05,W=$.adjust??"holm",X=[],K=(P,C,F)=>{let L={label:P,passRate:g$(C.passRate,F.passRate),score:c$(C.score,F.score)};return X.push(L),{passRate:L.passRate,score:L.score}},G=(P,C,F)=>Object.fromEntries(Object.keys(F).filter((L)=>(L in C)).map((L)=>[L,K(`${P} ${L}`,C[L],F[L])])),z=(P,C)=>({fromCurrent:P.filter((F)=>!C.includes(F)),fromBaseline:C.filter((F)=>!P.includes(F))}),V=K("total",Q.totals,J.totals),Y=G("case",Q.cases,J.cases),D=G("grader",Q.graders,J.graders),N=X.flatMap((P)=>[P.passRate,P.score]);u$(N,Z,W);let H={cases:z([...new Set([...Q.planned??[],...Object.keys(Q.cases)])],[...new Set([...J.planned??[],...Object.keys(J.cases)])]),graders:z(Object.keys(Q.graders),Object.keys(J.graders))},U=[...H.cases.fromCurrent.map((P)=>`case ${P}: in the baseline, missing from this report`),...H.graders.fromCurrent.map((P)=>`grader ${P}: in the baseline, missing from this report`)],_=[];for(let P of X)for(let[C,F]of[["pass rate",P.passRate],["score",P.score]]){if(!F.significant)continue;let L=`${P.label}: ${C} ${F.before.toFixed(2)} \u2192 ${F.after.toFixed(2)} (p = ${e8(F.pAdjusted)})`;(F.delta<0?U:_).push(L)}return{totals:V,cases:Y,graders:D,missing:H,comparisons:N.filter((P)=>P.p!==null).length,alpha:Z,adjust:W,regressions:U,improvements:_}}function e8(Q){return Q<0.001?"<0.001":Q.toFixed(3)}function Q9(Q,J){let $=J.baseline&&!J.baseline.aborted&&!Q.aborted?n$(J.baseline,Q,J):void 0,{totals:Z}=Q,W=[];if(W.push(`eval ${Q.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(Q.durationMs/1000).toFixed(1)}s)`),Q.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let X=(V)=>{if(V.n===0)return"-";let Y=V.mean.toFixed(2);if(V.low===null||V.high===null)return`${Y} (${V.n===1?"n=1":"no spread"})`;return`${Y} [${V.low.toFixed(2)}, ${V.high.toFixed(2)}]`},K=(V)=>V?` ${V.delta>=0?"+":""}${V.delta.toFixed(2)}${V.significant?"*":""}`:"",G=(V,Y)=>{let D=[0,1,2,3].map((H)=>Math.max(...[[V,"n","pass rate","score"],...Y].map((U)=>U[H].length))),N=(H)=>H.map((U,_)=>U.padEnd(D[_])).join(" ").trimEnd();W.push("",N([V,"n","pass rate","score"]),...Y.map(N))};G("case",Object.entries(Q.cases).map(([V,Y])=>[V,`${Y.kept}/${Y.samples}`,X(Y.passRate)+K($?.cases[V]?.passRate),X(Y.score)+K($?.cases[V]?.score)])),G("grader",Object.entries(Q.graders).map(([V,Y])=>[V,String(Y.passRate.n),X(Y.passRate)+K($?.graders[V]?.passRate),X(Y.score)+K($?.graders[V]?.score)])),W.push("",`total pass rate ${X(Z.passRate)}${K($?.totals.passRate)} score ${X(Z.score)}${K($?.totals.score)}`);for(let[V,Y]of Object.entries(Q.calibration))W.push(`judge ${V}: agreement ${Y.agreement.toFixed(2)} on ${Y.n} examples${Y.ok?"":" (BELOW minAgreement)"}`);let z=(V)=>`${V.inputTokens} in, ${V.outputTokens} out`;if(W.push(`tokens: task ${z(Z.usage)}; judges ${z(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),$){W.push("",`* significant at ${$.alpha} over ${$.comparisons} tests (${$.adjust==="holm"?"Holm-adjusted":"unadjusted"}; Fisher's exact for pass rates, Welch's t for scores)`);for(let V of $.regressions)W.push(`regression: ${V}`);for(let V of $.improvements)W.push(`improvement: ${V}`)}return W.join(`
|
|
181
|
-
`)}function o$(Q){return Q.reduce((J,$)=>J+$,0)/Q.length}function i$(Q){return Math.min(1,Math.max(0,Q))}function s$(Q){return Q instanceof Error?Q.message:String(Q)}function NQ(Q,J,$){if(Q===void 0||Number.isInteger(Q)&&Q>=1)return;throw Error(`${J} sets \`${$}\` to ${String(Q)}, but it has to be a whole number of at least 1.`)}var J9=/^[A-Za-z0-9_-]{1,64}$/;function $9(Q,J){let $=Z9(J)?J:{filter:J},Z=$.deferred===!0,W=Q.descriptors($.filter);if(!$.namespaces)return W.map((Y)=>CJ(Q,Y,Z));let X=Object.entries($.namespaces),K=new Set(Q.descriptors().flatMap((Y)=>Y.tags));for(let[Y,D]of X){if(!J9.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 D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${Y}" needs a description. It is what the model reads to decide whether to look inside.`);if(!K.has(Y))throw Error(`toAgentTools: no tool is tagged "${Y}", so its namespace would be empty.`)}let G=new Map(X.map(([Y])=>[Y,[]])),z=[];for(let Y of W){let D=X.find(([N])=>Y.tags.includes(N))?.[0];if(D===void 0)z.push(CJ(Q,Y,Z));else G.get(D).push(CJ(Q,Y,!1))}let V=[];for(let[Y,D]of X){let N=G.get(Y);if(N.length===0)continue;V.push(UJ.create({name:Y,description:D.description,tools:N,deferred:D.deferred??Z}))}return[...V,...z]}function Z9(Q){return typeof Q==="object"&&Q!==null&&(("filter"in Q)||("namespaces"in Q)||("deferred"in Q))}function CJ(Q,J,$){if(J.kind==="tool")return W9(Q,J,$);return gQ.create({name:J.name,description:J.description,inputSchema:J.inputSchema,...J.outputSchema?{outputSchema:J.outputSchema}:{},requiresApproval:J.requiresApproval,deferred:$,execute:(Z,W)=>{let X=n.getStore()?.req;if(!X)throw new o(`"${J.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},J.name,Z,W)}})}function W9(Q,J,$){let Z=Q.nativeTool(J.name);return gQ.create({name:J.name,description:J.description,inputSchema:J.inputSchema,...J.outputSchema?{outputSchema:J.outputSchema}:{},requiresApproval:Q.nativeApproval(J.name),deferred:$,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,X)=>{let K=n.getStore()?.req;return Q.startNative(K?{kind:"local",req:K}:void 0,J.name,W,X)}})}function X9(Q){if(Q==="auto")return;let J=/^(\d+)x(\d+)$/.exec(Q);if(!J)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(Q)}.`);let $=Number(J[1]),Z=Number(J[2]);if($%16!==0||Z%16!==0)throw Error(`Image size ${Q} is not supported: width and height must both be divisible by 16.`);if(Math.max($/Z,Z/$)>3)throw Error(`Image size ${Q} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function a$(Q,J){if(Q.size!==void 0)try{X9(Q.size)}catch($){throw Error(`${J}: ${$.message}`)}if(Q.background==="transparent"&&Q.format==="jpeg")throw Error(`${J}: a transparent background needs "png"; JPEG has no alpha channel.`);if(Q.compression!==void 0){let $=Q.compression;if(!Number.isInteger($)||$<0||$>100)throw Error(`${J}: compression is an integer from 0 to 100; got ${$}.`)}}function t$(Q,J){if(Q instanceof File)return Q;let $=Q.type||"image/png",Z=$==="image/jpeg"?"jpg":$.split("/")[1]??"png";return new File([Q],`${J}.${Z}`,{type:$})}class _J{name;provider;settings;constructor(Q){let{name:J,provider:$,...Z}=Q;a$(Z,`ImageModel "${J}"`),this.name=J,this.provider=$,this.settings=Z}static create(Q){return new _J(Q)}async generate(Q){let J=this.merge(Q);return this.present(await this.provider.generate({prompt:Q.prompt,...J,signal:Q.signal}))}async edit(Q){let J=this.merge(Q);return this.present(await this.provider.edit({prompt:Q.prompt,...J,images:Q.images.map(($,Z)=>t$($,`image-${Z}`)),...Q.mask?{mask:t$(Q.mask,"mask")}:{},signal:Q.signal}))}present(Q){return r$(this.provider.model,Q.usage),K9({...Q,usage:e$(this.provider.model,Q.usage)})}merge(Q){let J={...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$(J,`ImageModel "${this.name}"`),J}}function K9(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}var LJ=300000;function OJ(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 cQ extends Error{code;retryable;retryAfter;constructor(Q,J={}){super(Q.message,J);if(this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable,Q.retryAfter!==void 0)this.retryAfter=Q.retryAfter}}var G9={png:"image/png",jpeg:"image/jpeg"};function V9(Q){let J=Number(Q?.input_tokens??0),$=Number(Q?.output_tokens??0),Z={inputTokens:J,outputTokens:$,totalTokens:Number(Q?.total_tokens??J+$)},W=Q?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let X=Q?.output_tokens_details?.image_tokens;if(typeof X==="number")Z.imageOutputTokens=X;return Z}function z9(Q){let J=atob(Q),$=new Uint8Array(J.length);for(let Z=0;Z<J.length;Z++)$[Z]=J.charCodeAt(Z);return $}function Y9(Q){let $=Q?.data?.[0]?.b64_json;if(typeof $!=="string"||$.length===0)throw new cQ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof Q.output_format==="string"?Q.output_format:"png";return{bytes:z9($),mimeType:G9[Z]??`image/${Z}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:V9(Q.usage)}}async function JZ(Q,J,$,Z){let W;try{W=await QZ(Q,J,{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(X){if(Z.signal?.aborted)throw X;throw new cQ(XQ(X),{cause:X})}return Y9(await W.json())}async function $Z(Q,J,$={}){return await JZ(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(J)},Q,$)}async function ZZ(Q,J,$={}){return await JZ(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:J},Q,$)}class uQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await $Z(this.endpoint(),this.body(Q),{signal:Q.signal})}async edit(Q){let J=new FormData;for(let[$,Z]of Object.entries(this.body(Q)))if(Z!==void 0)J.set($,String(Z));for(let $ of Q.images)J.append("image[]",$,$.name);if(Q.mask)J.set("mask",Q.mask,Q.mask.name);return await ZZ(this.endpoint(),J,{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 XQ(Q)}}var KZ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class BJ extends uQ{model;config;constructor(Q,J={}){super();this.model=Q,this.config=J}static model(Q,J){return new BJ(Q,J)}static models(){return KZ}endpoint(){return OJ(WZ(this.config,{timeoutMs:LJ}))}}class SJ extends uQ{model;config;constructor(Q,J={}){super();this.model=Q,this.config=J}static model(Q,J){return new SJ(Q,J)}static models(){return KZ}modelName(){return this.config.deployment??this.model}endpoint(){return OJ(XZ(this.config,{timeoutMs:LJ}))}}class mQ{now;entries=new Map;constructor(Q=Date.now){this.now=Q}allow(Q,J){let $=this.entries.get(Q);if($?.openUntil===void 0)return!0;let Z=this.now();if(Z<$.openUntil)return!1;if($.probeUntil!==void 0&&Z<$.probeUntil)return!1;return $.probeUntil=Z+J.cooldownMs,!0}record(Q,J,$){let Z=this.entries.get(Q)??{failures:0},W=Z.openUntil!==void 0;if(J==="success")return this.entries.delete(Q),W?"closed":void 0;if(J==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(Q,Z),W||Z.failures>=$.failures)return Z.openUntil=this.now()+$.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(Q){let J=this.entries.get(Q);if(J?.openUntil===void 0)return"closed";return this.now()<J.openUntil?"open":"half-open"}}var VZ=Symbol("timed-out");class CQ extends RJ{model;capabilities;entries;options;circuit;constructor(Q,J={}){super();if(Q.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of Q)if(Z.timeoutMs!==void 0&&!(Z.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${Z.provider.model} must be a positive number, got ${Z.timeoutMs}.`);this.entries=[...Q];let $=J.circuit;if($){let Z=$.failures??3,W=$.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let X=new Set;for(let G of Q){let z=MJ(G);if(X.has(z))throw Error(`FallbackProvider: two legs share the circuit key "${z}". Give one of them a \`circuitKey\`.`);X.add(z)}let K=$.store??new mQ;this.options={...J,circuit:{...$,store:K}},this.circuit={policy:{failures:Z,cooldownMs:W},store:K,...$.onStateChange?{onStateChange:$.onStateChange}:{}}}else this.options=J,this.circuit=void 0;this.model=Q[0].provider.model,this.capabilities=D9(Q.map((Z)=>Z.provider.capabilities))}static chain(Q,J){return new CQ(Q,J)}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 CQ(this.entries.slice(Q),this.options)}leg(Q){let J=this.from(Q).entries[0];return new CQ([J],this.options)}upload(Q){return this.entries[0].provider.upload(Q)}deleteFile(Q){let J=this.entries[0].provider;if(!J.deleteFile)return Promise.reject(Error(`${J.constructor.name} cannot delete provider files: it does not implement deleteFile().`));return J.deleteFile(Q)}cacheWriteFactor(Q){return(this.entries.find(($)=>$.provider.model===Q)??this.entries.find(($)=>Q.startsWith($.provider.model)))?.provider.cacheWriteFactor?.(Q)}normalizeError(Q){return this.entries[0].provider.normalizeError(Q)}stream(Q){return this.run(Q)}async*run(Q){let J,$={},Z=Q.signal,W=0;for(let X=0;X<this.entries.length;X++){let K=this.entries[X],G=X===this.entries.length-1,z=K.provider.model;if(this.circuit&&!G&&!await this.allow(K))continue;W+=1;let V=!1,Y=async(O)=>{if(V)return;V=!0,await this.record(X,K,O)},D=new AbortController,N=()=>D.abort(Z?.reason);if(Z?.aborted)D.abort(Z.reason);else Z?.addEventListener("abort",N,{once:!0});let H=[],U=!1,_=!1,P,C,F,L=!1,R,f=!1,x,I=(O)=>{x=O.usage;let A=O.model??z;if(!J)return{...O,model:A};let B={...$};return B[A]=k(k(S(),B[A]??S()),O.usage),{type:"usage",usage:k(k(S(),J),O.usage),byModel:B}},h=(O)=>{if(!J)return O;let A=O.model??z,B={...$};B[A]=k(k(S(),B[A]??S()),O.usage);let q=k(k(S(),J),O.usage);J=void 0;for(let e of Object.keys($))delete $[e];let DQ=Object.entries(B).filter(([e,kQ])=>e===A||kQ.totalTokens>0);return DQ.length>1?{...O,usage:q,byModel:Object.fromEntries(DQ)}:{...O,usage:q}};try{R=K.provider.stream({...Q,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:D.signal})[Symbol.asyncIterator]();let O=K.timeoutMs!==void 0?Date.now()+K.timeoutMs:void 0;for(;;){let A=!U&&O!==void 0?await H9(R.next(),Math.max(0,O-Date.now())):await R.next();if(A===VZ){L=!0,F={error:{code:"provider_error",message:`${z} did not start answering within ${K.timeoutMs}ms.`,retryable:!0}};break}if(A.done){f=!0;break}let B=A.value;if(B.type==="finish"&&B.model)C=B.model;if(B.type==="retry"){yield B;continue}if(B.type==="usage"){yield I(B);continue}if(U){if(B.type==="finish")P=k(P??S(),B.usage),_=!0,yield h(B);else{if(B.type==="error")F={error:B.error};yield B}continue}if(GZ(B)){U=!0,await Y("success"),yield*H.splice(0),yield B;continue}if(B.type==="error")F={error:B.error,...KQ(B)};else if(B.type==="finish"){if(P=k(P??S(),B.usage),B.reason==="error"&&!F)F={error:{code:"provider_error",message:`${z} ended the call with an error and did not say which.`,retryable:!1}}}H.push(B)}}catch(O){let A=K.provider.normalizeError(O);if(U){if(A.code!=="aborted")yield{type:"error",error:A,...KQ(O)};this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:AJ(A),error:A}),yield h({type:"finish",reason:A.code==="aborted"?"aborted":"error",usage:S(),...C?{model:C}:{}});return}F={error:A,...KQ(O)}}finally{if(Z?.removeEventListener("abort",N),!f)D.abort(),R?.return?.()?.catch(()=>{})}if(U){if(!_&&J)yield{type:"finish",reason:F?"error":"stop",usage:J,byModel:{...$}},J=void 0;this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:F?AJ(F.error):"ok",...F?{error:F.error}:{}});return}if(Z?.aborted){await Y("none"),this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:"aborted"}),yield h({type:"finish",reason:"aborted",usage:P??S(),...C?{model:C}:{}});return}if(!F){await Y("success"),this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:"ok"});for(let O of H)yield O.type==="finish"?h(O):O;return}let r=!G&&F.error.code!=="aborted"&&this.shouldFallBack(F.error,{index:X,model:z,timedOut:L,...KQ(F)});if(await Y(r?"failure":"none"),this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:r?"fallback":AJ(F.error),error:F.error}),r){let O=P??x;if(O){J=k(J??S(),O);let A=C??z;$[A]=k($[A]??S(),O)}continue}let p=!1,l;for(let O of H){if(O.type==="finish"){l=O;continue}if(O.type==="error")p=!0;yield O}if(!p&&F.error.code!=="aborted")yield{type:"error",error:F.error,...KQ(F)};yield h({type:"finish",reason:F.error.code==="aborted"?"aborted":l?.reason??"error",usage:P??S(),...C?{model:C}:{}});return}}async allow(Q){if(!this.circuit)return!0;try{return await this.circuit.store.allow(MJ(Q),this.circuit.policy)}catch{return!0}}async record(Q,J,$){if(!this.circuit)return;let Z=MJ(J),W;try{W=await this.circuit.store.record(Z,$,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:Q,model:J.provider.model,key:Z,state:W})}catch{}}shouldFallBack(Q,J){let $=this.options.fallbackOn??((Z)=>Z.retryable);try{return $(Q,J)}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 MJ(Q){return Q.circuitKey??Q.provider.model}function AJ(Q){return Q.code==="aborted"?"aborted":"failed"}function D9(Q){return{reasoning:Q.every((J)=>J.reasoning),structuredOutput:Q.every((J)=>J.structuredOutput),fileInput:Q.every((J)=>J.fileInput),parallelToolCalls:Q.every((J)=>J.parallelToolCalls),toolSearch:Q.every((J)=>J.toolSearch),supportsForcedToolChoice:Q.every((J)=>J.supportsForcedToolChoice!==!1),trailingContext:Q.every((J)=>J.trailingContext===!0),allowedTools:Q.every((J)=>J.allowedTools===!0)}}function H9(Q,J){let $,Z=new Promise((W)=>{$=setTimeout(()=>W(VZ),J)});return Promise.race([Q,Z]).finally(()=>clearTimeout($))}async function P9(Q,J,$={}){let Z=$.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let X=0;X<Q.entries.length;X++){let K=Q.leg(X),G={index:X,model:K.model,results:[],errors:[]};for(let z=0;z<Z;z++)try{G.results.push(await J(K,{index:X,sample:z}))}catch(V){G.errors.push({sample:z,error:V})}W.push(G)}return W}class lQ extends Error{line;constructor(Q){super(Q??"Voice session ended by the app.");this.name="VoiceHangup",this.line=Q}}var _Q="ask_agent",N9={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},F9={maxDuration:"We've reached the time limit for this voice session. Tap the microphone to start again.",idle:"It's gone quiet, so I'll hang up. Tap the microphone when you want to talk again.",error:null};function UQ(Q={}){return[{name:Q.name??_Q,description:Q.description??"Hand one self-contained request to the agent that does the work, in the user's own words with references resolved. It can take minutes; the result comes back when it is done, so tell the user you are on it.",parameters:{type:"object",properties:{request:{type:"string",description:"What the user wants done."}},required:["request"],additionalProperties:!1}},{name:"stop_work",description:"Stop the work that is running, and drop any requests waiting behind it.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"work_status",description:"What the agent is doing right now, and what is waiting.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"answer_question",description:"Answer the question the agent asked (it came back from a request with status needs_input). For an approval, set approve.",parameters:{type:"object",properties:{answer:{type:"string",description:"The user's answer, in their words."},approve:{type:"boolean",description:"For an approval: whether the user approved."}},required:["answer"],additionalProperties:!1}}]}var pQ=new Map;class s{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=S();transcription={usage:S(),seconds:0};hooks=Promise.resolve();pendingCreate;transcript=[];requests=[];toolCalls=[];toolHandlers=new Map;toolsRunning=0;toolCallTimes=[];errors=[];running;queue=[];pending=[];lastProgress;lastNoteAt=0;noteTimer;responseActive=!1;responseWanted=!1;ending;timers=[];idleTimer;tickTimer;resolveEnded;closingWaiter;static start(Q){return new s(Q)}static get(Q){return pQ.get(Q)}static async endAll(Q){await Promise.all([...pQ.values()].map((J)=>J.end("hangup",Q)))}constructor(Q){this.params=Q,this.sessionId=Q.sessionId??crypto.randomUUID(),this.threadId=Q.threadId,this.body=Q.body??{},this.limits={...N9,...zZ(Q.limits)},this.lines={...F9,...zZ(Q.lines)},this.delegateName=Q.delegate?.name??_Q;let J=new Set(UQ(Q.delegate).map(($)=>$.name));for(let $ of Q.tools??[]){if(J.has($.tool.name)||this.toolHandlers.has($.tool.name))throw Error(`VoiceBridge: two tools are named "${$.tool.name}".`);this.toolHandlers.set($.tool.name,$)}if("realtime"in Q.call){let{realtime:$,callId:Z}=Q.call;this.callId=Z,this.sideband=$.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=Q.call.callId??Q.call.sideband.callId,this.sideband=Q.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise(($)=>this.resolveEnded=$),pQ.set(this.sessionId,this),this.timers.push(setTimeout(()=>void this.end("max_duration",this.lines.maxDuration),this.limits.maxDurationMs)),this.tickTimer=setInterval(()=>void this.tick(),this.limits.tickMs),this.touch(),this.listen()}setBody(Q){this.body=Q;let J=this.params.contextNote?.(Q);if(J)this.sideband.addNote(J)}end(Q="hangup",J){return this.ending??=this.finish(Q,J??null)}async listen(){for await(let Q of this.sideband){try{this.params.onEvent?.(Q)}catch{}this.closingWaiter?.(Q),await this.handle(Q)}}async handle(Q){switch(Q.type){case"input_audio_buffer.speech_started":this.touch();return;case"response.created":this.responseActive=!0,this.pendingCreate=void 0,this.touch();return;case"response.done":{if(this.responseActive=!1,this.responseWanted&&!this.ending)this.responseWanted=!1,this.createResponse();let J=Q.usage;if(J){this.usage=k(this.usage,J);let $=this.info();this.hook(()=>this.params.onUsage?.(J,$))}return}case"conversation.item.input_audio_transcription.completed":{let J=Q;if(this.say("user",String(J.transcript??"")),J.transcriptionUsage||J.transcriptionSeconds!==void 0){this.transcription={usage:J.transcriptionUsage?k(this.transcription.usage,J.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+(J.transcriptionSeconds??0)};let $=this.info(),Z={...J.transcriptionUsage?{usage:J.transcriptionUsage}:{},...J.transcriptionSeconds!==void 0?{seconds:J.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,$))}return}case"response.output_audio_transcript.done":this.say("assistant",String(Q.transcript??""));return;case"response.output_text.done":this.say("assistant",String(Q.text??""));return;case"response.function_call_arguments.done":{let J=Q;if(this.touch(),!this.ending)this.call(J.call_id,J.name,J.arguments);return}case"session.updated":if(this.tampered(Q.session))this.end("session_tampered",null);return;case"error":{let J=Q.error;if(this.errors.push({code:J?.code,message:String(J?.message??"")}),this.pendingCreate&&J?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,J.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let J=Q;if(!this.ending&&!J.byClient)this.end(J.code===1000?"call_ended":"sideband_lost",null);return}}}say(Q,J){if(J.trim())this.transcript.push({role:Q,text:J,at:Date.now()})}call(Q,J,$){let Z=C9($);if(J===this.delegateName){let X=typeof Z.request==="string"?Z.request.trim():"";if(!X)return this.answer(Q,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:X,status:"queued"},turn:{text:X},callId:Q})}let W=this.toolHandlers.get(J);if(W)return void this.runTool(Q,W,Z);switch(J){case"stop_work":{let X=this.running;if(X)X.stopRequested=!0,X.handle?.stop({reason:"Stopped by voice."});let K=this.dropQueue();return this.answer(Q,{stopped:Boolean(X),dropped:K})}case"work_status":return this.answer(Q,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((X)=>X.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(Q,{status:"error",message:"There is no open question."});let X=typeof Z.answer==="string"?Z.answer:"",K=typeof Z.approve==="boolean"?Z.approve:void 0,G=this.pending.map((z)=>U9(z,X,K));return this.pending=[],this.enqueue({record:{request:`(answer) ${X}`,status:"queued"},turn:{toolResults:G},callId:Q})}default:return this.answer(Q,{status:"error",message:`There is no tool called ${J}.`})}}enqueue(Q){if(!this.running){this.requests.push(Q.record),this.run(Q);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(Q.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(Q.record),this.queue.push(Q),this.answer(Q.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),Q.callId=void 0}async run(Q){this.running=Q,Q.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let J=new Set;await this.waitForThread(J);let $=await this.latestBody();while(!Q.stopRequested&&await this.waitForThread(J));if(Q.stopRequested||this.ending){Q.record.status="dropped",this.complete(Q,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:$,turn:Q.turn})}catch(X){Q.record.status="refused",this.complete(Q,{status:"refused",message:X instanceof Error?X.message:"The request could not be started."});return}Q.handle=Z,Q.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(Q.record.status="done",Q.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(Q,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(Q,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(Q,{status:"stopped",text:W.text});else this.complete(Q,{status:"done",text:W.text})}catch(J){Q.record.status="done",this.complete(Q,{status:"failed",message:J instanceof Error?J.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let J=this.queue.shift();if(J&&!this.ending)this.run(J);else this.touch()}}async runTool(Q,J,$){let Z=J.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(Q,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let X={name:Z,status:"running"};this.toolCalls.push(X),this.toolsRunning+=1,this.pauseIdle();let K=new AbortController,G=J.timeoutMs??this.limits.toolTimeoutMs,z,V;try{let D=await Promise.race([J.run($,{sessionId:this.sessionId,signal:K.signal}),new Promise((N,H)=>{z=setTimeout(()=>{H(new o(`"${Z}" took longer than ${Math.round(G/1000)} s.`)),K.abort()},G)})]);X.status="done",V={status:"done",output:this.clip(D)}}catch(D){if(D instanceof lQ){X.status="refused",X.message=D.message,this.end("usage",D.line??null);return}let N=D instanceof o?D.message:"The tool failed.";if(!(D instanceof o))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);X.status="failed",X.message=N,V={status:"failed",message:N}}finally{clearTimeout(z),X.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let Y=this.info();if(this.hook(()=>this.params.onToolCall?.({...X},Y)),!this.ending)this.answer(Q,V)}clip(Q){let J;try{J=JSON.stringify(Q)}catch{return String(Q)}if(J===void 0||J.length<=this.limits.toolOutputChars)return Q;return`${J.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${J.length} characters in all)`}async waitForThread(Q=new Set){let J=this.params.liveRuns;if(!J)return!1;let $=await J.find({threadId:this.threadId}),Z=$&&!Q.has($.runId)?J.get($.runId):null;if(!$||!Z)return!1;return Q.add($.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let Q=this.params.store;if(!Q)return this.body;let J=await Q.get(this.sessionId).catch(()=>null);if(J)this.body=J.body;return this.body}async follow(Q){let J=this.params.progress??_9();try{for await(let $ of Q.run){let Z=J($);if(Z)this.note(Z)}}catch{}}complete(Q,J){if(this.ending)return;if(Q.callId)this.sideband.functionOutput(Q.callId,J),Q.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${Q.record.request}": ${JSON.stringify(J)}`);this.respond()}answer(Q,J){this.sideband.functionOutput(Q,J),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let Q=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=Q,this.sideband.send({type:"response.create",event_id:Q})}questions(){return this.pending.map((Q)=>({kind:Q.kind,tool:String(Q.name),input:Q.input}))}dropQueue(){let Q=this.queue.splice(0);for(let J of Q)J.record.status="dropped";return Q.length}note(Q){if(Q===this.lastProgress)return;this.lastProgress=Q;let J=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if(J<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),J)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let Q=this.info();this.hook(()=>this.params.onTick?.(Q))}hook(Q){this.hooks=this.hooks.then(async()=>{try{await Q()}catch(J){if(J instanceof lQ)this.end("usage",J.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",J),this.end("error",this.lines.error)}})}tampered(Q){let J=this.params.session;if(!J||!Q)return!1;if(J.instructions!==void 0&&Q.instructions!==void 0&&Q.instructions!==J.instructions)return!0;if(Array.isArray(Q.tools)){let $=new Set([...UQ(this.params.delegate),...J.tools??[]].map((W)=>W.name)),Z=new Set(Q.tools.map((W)=>String(W?.name)));if($.size!==Z.size||[...$].some((W)=>!Z.has(W)))return!0}return!1}async finish(Q,J){for(let K of this.timers)clearTimeout(K);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),J&&(Q!=="call_ended"&&Q!=="sideband_lost"))await this.closingLine(J);if(Q!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,X={sessionId:this.sessionId,...this.callId?{callId:this.callId}:{},threadId:this.threadId,reason:Q,startedAt:this.startedAt,endedAt:Z,durationMs:W,seconds:Math.ceil(W/1000),usage:this.usage,transcription:this.transcription,transcript:this.transcript,requests:this.requests,toolCalls:this.toolCalls,errors:this.errors};pQ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:Q}).catch(()=>{return});try{await this.params.onEnd?.(X)}catch(K){console.error("[gemi/ai] a voice session's onEnd threw.",K)}return this.resolveEnded(X),X}async hangUp(){try{await this.hangupCall()}catch(Q){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",Q),this.errors.push({code:"hangup_failed",message:Q instanceof Error?Q.message:String(Q)});let J;await Promise.race([this.sideband.closed,new Promise(($)=>J=setTimeout($,this.limits.hangupGraceMs))]),clearTimeout(J),this.sideband.close()}}async closingLine(Q){await new Promise((J)=>{let $=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",X,K=setTimeout(G,this.limits.closingLineMs);function G(){clearTimeout(K),J()}let z=()=>{W="asked",this.sideband.send({type:"response.create",event_id:$,response:{instructions:`Say exactly this to the user, and nothing else: "${Q}"`,tool_choice:"none"}})};if(this.closingWaiter=(V)=>{let Y=V;if(Y.type==="sideband.closed")return G();if(W==="cancelling"){if(Y.type==="response.done"||Y.type==="error"&&Y.error?.event_id===Z)z();return}if(Y.type==="error"&&Y.error?.event_id===$)return G();if(Y.type==="response.created"&&!X){X=Y.response?.id;return}let D=(N)=>!X||!N||N===X;if(Y.type==="response.done"&&D(Y.response?.id))W="playing";else if(Y.type==="output_audio_buffer.stopped"&&W==="playing"&&D(Y.response_id))G()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else z()}),this.closingWaiter=void 0}}function zZ(Q){if(!Q)return{};return Object.fromEntries(Object.entries(Q).filter(([,J])=>J!==void 0))}function C9(Q){try{let J=JSON.parse(Q);return J&&typeof J==="object"&&!Array.isArray(J)?J:{}}catch{return{}}}function U9(Q,J,$){let Z={toolCallId:Q.toolCallId,signature:Q.signature,...Q.path?{path:Q.path}:{}};if(Q.kind==="question")return{...Z,output:J};if(Q.kind==="approval")return{...Z,approve:$===!0,...J?{reason:J}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function _9(){let Q=new Set;return(J)=>{if(J.type==="tool-call"){if(J.part.partial||J.resent||Q.has(J.part.toolCallId))return;return Q.add(J.part.toolCallId),`running ${String(J.part.name)}`}if(J.type==="tool-progress"){let $=J.data;if(typeof $==="string")return $;if($&&typeof $==="object")for(let Z of["message","label","title"]){let W=$[Z];if(typeof W==="string"&&W)return W}}return}}var YZ="http://gemi.internal/__gemi__/voice/mcp";async function EJ(Q,J){if(!J.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:$}=Q,Z=Q.scopes??$.scopes().map((K)=>K.name),W=(K)=>({kind:"remote",req:K,principal:{user:J.user,via:"voice",id:`voice:${J.sessionId}`,scopes:Z}});return(await $.available(W(DZ()),Q.filter)).filter((K)=>!K.requiresApproval).map((K)=>({tool:{name:K.name,description:K.description,parameters:K.inputSchema},...Q.timeoutMs!==void 0?{timeoutMs:Q.timeoutMs}:{},run:(G,z)=>{let V=DZ();return n.run(V,async()=>{return await Q.authorize?.({name:K.name,input:G,sessionId:z.sessionId}),$.execute(W(V),K.name,G,void 0,{signal:z.signal})},{user:J.user})}}))}function DZ(){return new w(new Request(YZ,{method:"POST"}),{},"api",new URL(YZ).pathname)}class kJ{records=new Map;retainEndedMs;constructor(Q={}){this.retainEndedMs=Q.retainEndedMs??600000}async create(Q){this.sweep(),this.records.set(Q.id,structuredClone(Q))}async get(Q){let J=this.records.get(Q);return J?structuredClone(J):null}async update(Q,J){let $=this.records.get(Q);if(!$)return;this.records.set(Q,{...$,...structuredClone(J),id:Q})}sweep(){let Q=Date.now()-this.retainEndedMs;for(let[J,$]of this.records)if($.endedAt!==void 0&&$.endedAt<Q)this.records.delete(J)}}var TJ=new kJ;var HZ=100;class jJ{threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(Q,J={}){if(this.threadsTable=PZ(J.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=PZ(J.messagesTable??"gemi_agent_messages","messages"),this.sql=Q.sql,this.dialect=Q.dialect,this.connection=Q.name,this.options=J,J.ttlMs!==void 0)UZ(J.ttlMs,"ttlMs")}get expires(){return this.options.ttlMs!==void 0}forScope(Q){if(typeof Q!=="string"||Q==="")throw TypeError("A DatabaseAgentStore scope is a non-empty string.");let J=new jJ({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return J.scope=Q,J}async createTable(){let Q=B9(this.dialect,this.threadsTable,this.messagesTable);for(let J of Q)await this.sql.unsafe(J);await this.addScopeColumns(),await this.addExpiryColumns()}async addExpiryColumns(){if(await this.hasColumn(this.threadsTable,"expires_at"))return;for(let Q of M9(this.dialect,this.threadsTable))await this.sql.unsafe(Q)}async addScopeColumns(){let Q=S9(this.dialect,this.threadsTable,this.messagesTable);for(let[J,$]of Q){if(await this.hasColumn(J,"scope"))continue;for(let Z of $)await this.sql.unsafe(Z)}}async hasColumn(Q,J){try{return await this.sql.unsafe(`SELECT ${J} FROM ${this.quote(Q)} WHERE 1 = 0`),!0}catch{return!1}}async createThread(Q={}){let J=crypto.randomUUID(),$=Q.userId===void 0||Q.userId===null?null:String(Q.userId),Z=this.expiryOf(Q);return await this.run(async(W)=>{let X=this.clock(W);if(Z){let K=Z.at!==void 0?this.ms(W,Z.at):Z.ttlMs===null?null:W`${X} + ${this.ms(W,Z.ttlMs)}`,G=Z.slides&&Z.ttlMs!==null?this.ms(W,Z.ttlMs):null;if(this.scope===null)await W`
|
|
180
|
+
)`,`CREATE INDEX IF NOT EXISTS "${J}_scope_kind_created_at_idx" ON "${J}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${J}_expires_at_idx" ON "${J}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${J}_scope_key_key" ON "${J}"("scope", "key")`]}var y$={n:0,mean:0,stddev:0,low:null,high:null};function d(Q){let J=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if(Q<0.5)return Math.log(Math.PI/Math.sin(Math.PI*Q))-d(1-Q);Q-=1;let $=J[0],Z=Q+7.5;for(let W=1;W<9;W++)$+=J[W]/(Q+W);return 0.5*Math.log(2*Math.PI)+(Q+0.5)*Math.log(Z)-Z+Math.log($)}function v$(Q,J,$){let W=1,X=1-(Q+J)*$/(Q+1);if(Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;X=1/X;let K=X;for(let G=1;G<=300;G++){let z=2*G,V=G*(J-G)*$/((Q+z-1)*(Q+z));if(X=1+V*X,Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+V/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(X=1/X,K*=X*W,V=-(Q+G)*(Q+J+G)*$/((Q+z)*(Q+z+1)),X=1+V*X,Math.abs(X)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)X=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+V/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;X=1/X;let Y=X*W;if(K*=Y,Math.abs(Y-1)<0.00000000000001)break}return K}function o8(Q,J,$){if(Q<=0)return 0;if(Q>=1)return 1;let Z=Math.exp(d(J+$)-d(J)-d($)+J*Math.log(Q)+$*Math.log(1-Q));return Q<(J+1)/(J+$+2)?Z*v$(J,$,Q)/J:1-Z*v$($,J,1-Q)/$}function YJ(Q,J){return o8(J/(J+Q*Q),J/2,0.5)}function s8(Q){if(!(Q>0))return Number.POSITIVE_INFINITY;let J=1.959964,$=2;while(YJ($,Q)>0.05)$*=2;for(let Z=0;Z<100;Z++){let W=(J+$)/2;if(YJ(W,Q)>0.05)J=W;else $=W}return(J+$)/2}function a8(Q,J,$,Z){let W=Q+$,X=J+Z,K=(Y,D)=>d(Y+1)-d(D+1)-d(Y-D+1),G=(Y)=>Math.exp(K(J,Y)+K(Z,W-Y)-K(X,W)),z=G(Q),V=0;for(let Y=Math.max(0,W-Z);Y<=Math.min(J,W);Y++){let D=G(Y);if(D<=z*1.0000001)V+=D}return Math.min(1,V)}function h$(Q,J){if(Q.length<2)return 0;let $=Q.reduce((W,X)=>W+(X-J)**2,0),Z=Math.sqrt($/(Q.length-1));return Z<0.000000000001*Math.max(1,Math.abs(J))?0:Z}function DJ(Q){let J=Q.length;if(J===0)return y$;let $=Q.map((G)=>G?1:0),Z=$.reduce((G,z)=>G+z,0)/J,W=3.841458881296,X=(Z+W/(2*J))/(1+W/J),K=1.959964*Math.sqrt(Z*(1-Z)/J+W/(4*J*J))/(1+W/J);return{n:J,mean:Z,stddev:h$($,Z),low:Math.max(0,X-K),high:Math.min(1,X+K)}}function HJ(Q){let J=Q.length;if(J===0)return y$;let $=Q.reduce((X,K)=>X+K,0)/J,Z=h$(Q,$);if(J<2||Z===0)return{n:J,mean:$,stddev:Z,low:null,high:null};let W=s8(J-1)*Z/Math.sqrt(J);return{n:J,mean:$,stddev:Z,low:$-W,high:$+W}}function PQ(Q,J,$){return{before:Q.mean,after:J.mean,delta:J.mean-Q.mean,p:$,pAdjusted:$,significant:!1}}function g$(Q,J){if(Q.n===0||J.n===0)return PQ(Q,J,null);let $=(Z)=>Math.round(Z.mean*Z.n);return PQ(Q,J,a8($(Q),Q.n,$(J),J.n))}function c$(Q,J){if(Q.n<2||J.n<2)return PQ(Q,J,null);let $=Q.stddev**2/Q.n,Z=J.stddev**2/J.n,W=Math.sqrt($+Z);if(W===0)return PQ(Q,J,null);let X=($+Z)**2/($**2/(Q.n-1)+Z**2/(J.n-1));return PQ(Q,J,YJ((J.mean-Q.mean)/W,X))}function u$(Q,J,$){if($==="holm"){let Z=Q.filter((X)=>X.p!==null).sort((X,K)=>X.p-K.p),W=0;Z.forEach((X,K)=>{W=Math.max(W,Math.min(1,X.p*(Z.length-K))),X.pAdjusted=W})}else for(let Z of Q)Z.pAdjusted=Z.p;for(let Z of Q)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<J&&Z.delta!==0}class hQ{name;cases;runs;concurrency;graders;pricing;task;constructor(Q){this.name=Q.name,this.cases=Q.cases,this.runs=Q.runs??1,this.concurrency=Q.concurrency??1,this.task=Q.task,this.graders=typeof Q.graders==="function"?Q.graders({judge:(J)=>hQ.judge(J)}):Q.graders,this.pricing=Q.pricing}static create(Q){let J=`The eval "${Q.name}"`;NQ(Q.runs,J,"runs"),NQ(Q.concurrency,J,"concurrency");let $=new Set;for(let W of Q.cases){if($.has(W.id))throw Error(`${J} has two cases with the id "${W.id}".`);$.add(W.id)}let Z=new hQ(Q);for(let[W,X]of Object.entries(Z.graders))if(typeof X!=="function"&&X.kind==="judge")NQ(X.samples,`${J}'s judge "${W}"`,"samples");return Z}static judge(Q){return{...Q,kind:"judge"}}static compare(Q,J,$={}){return n$(Q,J,$)}static format(Q,J={}){return Q9(Q,J)}async run(Q={}){let J=`${this.name}.run`;NQ(Q.runs,J,"runs"),NQ(Q.concurrency,J,"concurrency");let $=Q.only?new Set(Q.only):null;if($){let P=[...$].filter((C)=>!this.cases.some((F)=>F.id===C));if(P.length>0)throw Error(`The eval "${this.name}" has no case ${P.map((C)=>`"${C}"`).join(", ")}.`)}let Z=Q.runs??this.runs,W=Date.now(),X=new AbortController,K=Q.signal?AbortSignal.any([Q.signal,X.signal]):X.signal,G=this.cases.filter((P)=>!$||$.has(P.id)),z={};for(let[P,C]of Object.entries(this.graders)){if(K.aborted)break;if(typeof C==="function"||C.kind!=="judge"||!C.calibration)continue;z[P]=await this.calibrate(C,K)}let V=G.flatMap((P)=>Array.from({length:Z},(C,F)=>({test:P,run:F+1}))),Y=Array.from({length:V.length}),D=0,N,H=async()=>{while(D<V.length&&!K.aborted){let P=D++,C=V[P],F=await this.sample(C.test,C.run,K,Q.keepOutputs??!1);Y[P]=F;try{Q.onSample?.(F)}catch(O){N??={error:O},X.abort(O)}}},U=Math.min(Q.concurrency??this.concurrency,V.length);if(await Promise.all(Array.from({length:U},H)),N)throw N.error;let _=Y.filter((P)=>P!==void 0);return this.report(_,z,Z,new Date(W).toISOString(),Date.now()-W,{aborted:K.aborted||_.length<V.length,planned:G.map((P)=>P.id)})}async sample(Q,J,$,Z){let W=Date.now(),X,K,G=await FQ(async()=>{try{X=await this.task(Q.input,{case:Q,run:J,signal:$})}catch(U){K=s$(U)}}),z={},V=!1,Y=await FQ(async()=>{if(K!==void 0)return;let U={case:Q,input:Q.input,run:J};for(let[_,P]of Object.entries(this.graders)){if(Q.skip?.includes(_))continue;let C=await m$(P,X,U,$);if(!C)continue;if(z[_]=C,!C.pass&&typeof P!=="function"&&P.gate)V=!0}}),D=Object.values(z).map((U)=>U.score),N=K===void 0&&D.length===0,H=this.pricing?PJ(this.pricing,G.byModel).cost+PJ(this.pricing,Y.byModel).cost:void 0;return{case:Q.id,run:J,pass:K===void 0&&!N&&Object.values(z).every((U)=>U.pass),excluded:V||N,...N?{ungraded:!0}:{},score:K!==void 0||N?0:o$(D),grades:z,...K!==void 0?{error:K}:{},...Z&&K===void 0?{output:X}:{},usage:G.usage,byModel:r8(G.byModel,Y.byModel),judgeUsage:Y.usage,...H!==void 0?{cost:H}:{},durationMs:Date.now()-W}}async calibrate(Q,J){let $=Q.calibration,Z=[],W=0,X=await FQ(async()=>{for(let[z,V]of $.examples.entries()){if(J.aborted)break;let Y=V.id??`example-${z+1}`,D={case:{id:Y,input:V.input},input:V.input,run:0},N=await m$(Q,V.output,D,J),H=N?.pass??!1;if(H===V.expected)W++;else Z.push({id:Y,expected:V.expected,got:H,...N?.note?{note:N.note}:{}})}}),K=$.examples.length,G=K===0?1:W/K;return{n:K,agreement:G,ok:G>=($.minAgreement??0.8),disagreements:Z,usage:X.usage}}report(Q,J,$,Z,W,X){let K=new Set(Object.entries(this.graders).filter(([,N])=>typeof N!=="function"&&N.gate).map(([N])=>N)),G={};for(let N of this.cases){let H=Q.filter((U)=>U.case===N.id);if(H.length===0)continue;G[N.id]={...p$(H),graders:l$(H,K)}}let z=S(),V=S(),Y={};for(let N of Q){z=k(z,N.usage),V=k(V,N.judgeUsage);for(let[H,U]of Object.entries(N.byModel))Y[H]=k(Y[H]??S(),U)}let D=this.pricing?PJ(this.pricing,Y):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:$,aborted:X.aborted,planned:X.planned,samples:Q,cases:G,graders:l$(Q,K),calibration:J,totals:{...p$(Q),usage:z,judgeUsage:V,byModel:Y,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(Y)}}}}async function m$(Q,J,$,Z){let W=typeof Q==="function"?0.5:Q.threshold??0.5;try{if(typeof Q==="function")return NJ(await Q(J,$),W);if(Q.kind!=="judge")return NJ(await Q.check(J,$),W);return await t8(Q,J,$,W,Z)}catch(X){return{pass:!1,score:0,error:s$(X)}}}async function t8(Q,J,$,Z,W){let X=await Q.prompt(J,$),K=typeof X==="string"?{prompt:X}:X,G=[];for(let D=0;D<(Q.samples??1)&&!W.aborted;D++){let N=await FJ({signal:W,provider:Q.provider,...Q.instructions!==void 0?{instructions:Q.instructions}:{},...K,output:Q.output,...Q.reasoning!==void 0?{reasoning:Q.reasoning}:{},...Q.maxOutputTokens!==void 0?{maxOutputTokens:Q.maxOutputTokens}:{},...Q.temperature!==void 0?{temperature:Q.temperature}:{},logErrors:!1});if(!N.ok){G.push({pass:!1,score:0,error:`The judge failed: ${N.error.message}`});continue}let H=NJ(Q.verdict(N.output,$),Z);if(H)G.push(H)}if(G.length===0)return null;if(G.length===1)return G[0];let z=G.filter((D)=>D.pass).length,V=G.map((D)=>D.note??D.error).filter(Boolean),Y=G.map((D)=>D.error).filter(Boolean);return{pass:z*2>G.length,score:o$(G.map((D)=>D.score)),...V.length>0?{note:V.join(" | ")}:{},...Y.length===G.length?{error:Y.join(" | ")}:{}}}function NJ(Q,J){if(Q===null||Q===void 0)return null;if(typeof Q==="boolean")return{pass:Q,score:Q?1:0};if(typeof Q==="number"){if(!Number.isFinite(Q))throw Error(`A grader answered the score ${Q}.`);let $=i$(Q);return{pass:$>=J,score:$}}return{pass:Q.pass,score:Q.score===void 0?Q.pass?1:0:i$(Q.score),...Q.note!==void 0?{note:Q.note}:{}}}function p$(Q){let J=Q.filter(($)=>!$.excluded);return{samples:Q.length,kept:J.length,passed:J.filter(($)=>$.pass).length,errors:Q.filter(($)=>$.error!==void 0).length,passRate:DJ(J.map(($)=>$.pass)),score:HJ(J.map(($)=>$.score))}}function l$(Q,J){let $=Q.filter((W)=>!W.excluded),Z=[...new Set(Q.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let K=(J.has(W)?Q:$).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:DJ(K.map((G)=>G.pass)),score:HJ(K.map((G)=>G.score))}]}))}function PJ(Q,J){let $=0,Z=[];for(let[W,X]of Object.entries(J)){let K=d$(Q,W,X);if(K===void 0){Z.push(W);continue}$+=K}return{cost:$,unpriced:Z}}function r8(...Q){let J={};for(let $ of Q)for(let[Z,W]of Object.entries($))J[Z]=k(J[Z]??S(),W);return J}function n$(Q,J,$){for(let[P,C]of[["baseline",Q],["current report",J]])if(C.aborted)throw Error(`Eval.compare: the ${P} for "${C.name}" was aborted (${C.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`);let Z=$.alpha??0.05,W=$.adjust??"holm",X=[],K=(P,C,F)=>{let O={label:P,passRate:g$(C.passRate,F.passRate),score:c$(C.score,F.score)};return X.push(O),{passRate:O.passRate,score:O.score}},G=(P,C,F)=>Object.fromEntries(Object.keys(F).filter((O)=>(O in C)).map((O)=>[O,K(`${P} ${O}`,C[O],F[O])])),z=(P,C)=>({fromCurrent:P.filter((F)=>!C.includes(F)),fromBaseline:C.filter((F)=>!P.includes(F))}),V=K("total",Q.totals,J.totals),Y=G("case",Q.cases,J.cases),D=G("grader",Q.graders,J.graders),N=X.flatMap((P)=>[P.passRate,P.score]);u$(N,Z,W);let H={cases:z([...new Set([...Q.planned??[],...Object.keys(Q.cases)])],[...new Set([...J.planned??[],...Object.keys(J.cases)])]),graders:z(Object.keys(Q.graders),Object.keys(J.graders))},U=[...H.cases.fromCurrent.map((P)=>`case ${P}: in the baseline, missing from this report`),...H.graders.fromCurrent.map((P)=>`grader ${P}: in the baseline, missing from this report`)],_=[];for(let P of X)for(let[C,F]of[["pass rate",P.passRate],["score",P.score]]){if(!F.significant)continue;let O=`${P.label}: ${C} ${F.before.toFixed(2)} \u2192 ${F.after.toFixed(2)} (p = ${e8(F.pAdjusted)})`;(F.delta<0?U:_).push(O)}return{totals:V,cases:Y,graders:D,missing:H,comparisons:N.filter((P)=>P.p!==null).length,alpha:Z,adjust:W,regressions:U,improvements:_}}function e8(Q){return Q<0.001?"<0.001":Q.toFixed(3)}function Q9(Q,J){let $=J.baseline&&!J.baseline.aborted&&!Q.aborted?n$(J.baseline,Q,J):void 0,{totals:Z}=Q,W=[];if(W.push(`eval ${Q.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(Q.durationMs/1000).toFixed(1)}s)`),Q.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let X=(V)=>{if(V.n===0)return"-";let Y=V.mean.toFixed(2);if(V.low===null||V.high===null)return`${Y} (${V.n===1?"n=1":"no spread"})`;return`${Y} [${V.low.toFixed(2)}, ${V.high.toFixed(2)}]`},K=(V)=>V?` ${V.delta>=0?"+":""}${V.delta.toFixed(2)}${V.significant?"*":""}`:"",G=(V,Y)=>{let D=[0,1,2,3].map((H)=>Math.max(...[[V,"n","pass rate","score"],...Y].map((U)=>U[H].length))),N=(H)=>H.map((U,_)=>U.padEnd(D[_])).join(" ").trimEnd();W.push("",N([V,"n","pass rate","score"]),...Y.map(N))};G("case",Object.entries(Q.cases).map(([V,Y])=>[V,`${Y.kept}/${Y.samples}`,X(Y.passRate)+K($?.cases[V]?.passRate),X(Y.score)+K($?.cases[V]?.score)])),G("grader",Object.entries(Q.graders).map(([V,Y])=>[V,String(Y.passRate.n),X(Y.passRate)+K($?.graders[V]?.passRate),X(Y.score)+K($?.graders[V]?.score)])),W.push("",`total pass rate ${X(Z.passRate)}${K($?.totals.passRate)} score ${X(Z.score)}${K($?.totals.score)}`);for(let[V,Y]of Object.entries(Q.calibration))W.push(`judge ${V}: agreement ${Y.agreement.toFixed(2)} on ${Y.n} examples${Y.ok?"":" (BELOW minAgreement)"}`);let z=(V)=>`${V.inputTokens} in, ${V.outputTokens} out`;if(W.push(`tokens: task ${z(Z.usage)}; judges ${z(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),$){W.push("",`* significant at ${$.alpha} over ${$.comparisons} tests (${$.adjust==="holm"?"Holm-adjusted":"unadjusted"}; Fisher's exact for pass rates, Welch's t for scores)`);for(let V of $.regressions)W.push(`regression: ${V}`);for(let V of $.improvements)W.push(`improvement: ${V}`)}return W.join(`
|
|
181
|
+
`)}function o$(Q){return Q.reduce((J,$)=>J+$,0)/Q.length}function i$(Q){return Math.min(1,Math.max(0,Q))}function s$(Q){return Q instanceof Error?Q.message:String(Q)}function NQ(Q,J,$){if(Q===void 0||Number.isInteger(Q)&&Q>=1)return;throw Error(`${J} sets \`${$}\` to ${String(Q)}, but it has to be a whole number of at least 1.`)}var J9=/^[A-Za-z0-9_-]{1,64}$/;function $9(Q,J){let $=Z9(J)?J:{filter:J},Z=$.deferred===!0,W=Q.descriptors($.filter);if(!$.namespaces)return W.map((Y)=>CJ(Q,Y,Z));let X=Object.entries($.namespaces),K=new Set(Q.descriptors().flatMap((Y)=>Y.tags));for(let[Y,D]of X){if(!J9.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 D?.description!=="string"||D.description.trim()==="")throw Error(`toAgentTools: the namespace "${Y}" needs a description. It is what the model reads to decide whether to look inside.`);if(!K.has(Y))throw Error(`toAgentTools: no tool is tagged "${Y}", so its namespace would be empty.`)}let G=new Map(X.map(([Y])=>[Y,[]])),z=[];for(let Y of W){let D=X.find(([N])=>Y.tags.includes(N))?.[0];if(D===void 0)z.push(CJ(Q,Y,Z));else G.get(D).push(CJ(Q,Y,!1))}let V=[];for(let[Y,D]of X){let N=G.get(Y);if(N.length===0)continue;V.push(UJ.create({name:Y,description:D.description,tools:N,deferred:D.deferred??Z}))}return[...V,...z]}function Z9(Q){return typeof Q==="object"&&Q!==null&&(("filter"in Q)||("namespaces"in Q)||("deferred"in Q))}function CJ(Q,J,$){if(J.kind==="tool")return W9(Q,J,$);return gQ.create({name:J.name,description:J.description,inputSchema:J.inputSchema,...J.outputSchema?{outputSchema:J.outputSchema}:{},requiresApproval:J.requiresApproval,deferred:$,execute:(Z,W)=>{let X=n.getStore()?.req;if(!X)throw new o(`"${J.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},J.name,Z,W)}})}function W9(Q,J,$){let Z=Q.nativeTool(J.name);return gQ.create({name:J.name,description:J.description,inputSchema:J.inputSchema,...J.outputSchema?{outputSchema:J.outputSchema}:{},requiresApproval:Q.nativeApproval(J.name),deferred:$,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,X)=>{let K=n.getStore()?.req;return Q.startNative(K?{kind:"local",req:K}:void 0,J.name,W,X)}})}function X9(Q){if(Q==="auto")return;let J=/^(\d+)x(\d+)$/.exec(Q);if(!J)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(Q)}.`);let $=Number(J[1]),Z=Number(J[2]);if($%16!==0||Z%16!==0)throw Error(`Image size ${Q} is not supported: width and height must both be divisible by 16.`);if(Math.max($/Z,Z/$)>3)throw Error(`Image size ${Q} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function a$(Q,J){if(Q.size!==void 0)try{X9(Q.size)}catch($){throw Error(`${J}: ${$.message}`)}if(Q.background==="transparent"&&Q.format==="jpeg")throw Error(`${J}: a transparent background needs "png"; JPEG has no alpha channel.`);if(Q.compression!==void 0){let $=Q.compression;if(!Number.isInteger($)||$<0||$>100)throw Error(`${J}: compression is an integer from 0 to 100; got ${$}.`)}}function t$(Q,J){if(Q instanceof File)return Q;let $=Q.type||"image/png",Z=$==="image/jpeg"?"jpg":$.split("/")[1]??"png";return new File([Q],`${J}.${Z}`,{type:$})}class _J{name;provider;settings;constructor(Q){let{name:J,provider:$,...Z}=Q;a$(Z,`ImageModel "${J}"`),this.name=J,this.provider=$,this.settings=Z}static create(Q){return new _J(Q)}async generate(Q){let J=this.merge(Q);return this.present(await this.provider.generate({prompt:Q.prompt,...J,signal:Q.signal}))}async edit(Q){let J=this.merge(Q);return this.present(await this.provider.edit({prompt:Q.prompt,...J,images:Q.images.map(($,Z)=>t$($,`image-${Z}`)),...Q.mask?{mask:t$(Q.mask,"mask")}:{},signal:Q.signal}))}present(Q){return r$(this.provider.model,Q.usage),K9({...Q,usage:e$(this.provider.model,Q.usage)})}merge(Q){let J={...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$(J,`ImageModel "${this.name}"`),J}}function K9(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}var OJ=300000;function LJ(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 cQ extends Error{code;retryable;retryAfter;constructor(Q,J={}){super(Q.message,J);if(this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable,Q.retryAfter!==void 0)this.retryAfter=Q.retryAfter}}var G9={png:"image/png",jpeg:"image/jpeg"};function V9(Q){let J=Number(Q?.input_tokens??0),$=Number(Q?.output_tokens??0),Z={inputTokens:J,outputTokens:$,totalTokens:Number(Q?.total_tokens??J+$)},W=Q?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let X=Q?.output_tokens_details?.image_tokens;if(typeof X==="number")Z.imageOutputTokens=X;return Z}function z9(Q){let J=atob(Q),$=new Uint8Array(J.length);for(let Z=0;Z<J.length;Z++)$[Z]=J.charCodeAt(Z);return $}function Y9(Q){let $=Q?.data?.[0]?.b64_json;if(typeof $!=="string"||$.length===0)throw new cQ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof Q.output_format==="string"?Q.output_format:"png";return{bytes:z9($),mimeType:G9[Z]??`image/${Z}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:V9(Q.usage)}}async function JZ(Q,J,$,Z){let W;try{W=await QZ(Q,J,{maxRetries:$.maxRetries,timeoutMs:$.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:$.fetchImpl})}catch(X){if(Z.signal?.aborted)throw X;throw new cQ(XQ(X),{cause:X})}return Y9(await W.json())}async function $Z(Q,J,$={}){return await JZ(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(J)},Q,$)}async function ZZ(Q,J,$={}){return await JZ(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:J},Q,$)}class uQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await $Z(this.endpoint(),this.body(Q),{signal:Q.signal})}async edit(Q){let J=new FormData;for(let[$,Z]of Object.entries(this.body(Q)))if(Z!==void 0)J.set($,String(Z));for(let $ of Q.images)J.append("image[]",$,$.name);if(Q.mask)J.set("mask",Q.mask,Q.mask.name);return await ZZ(this.endpoint(),J,{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 XQ(Q)}}var KZ=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class BJ extends uQ{model;config;constructor(Q,J={}){super();this.model=Q,this.config=J}static model(Q,J){return new BJ(Q,J)}static models(){return KZ}endpoint(){return LJ(WZ(this.config,{timeoutMs:OJ}))}}class SJ extends uQ{model;config;constructor(Q,J={}){super();this.model=Q,this.config=J}static model(Q,J){return new SJ(Q,J)}static models(){return KZ}modelName(){return this.config.deployment??this.model}endpoint(){return LJ(XZ(this.config,{timeoutMs:OJ}))}}class mQ{now;entries=new Map;constructor(Q=Date.now){this.now=Q}allow(Q,J){let $=this.entries.get(Q);if($?.openUntil===void 0)return!0;let Z=this.now();if(Z<$.openUntil)return!1;if($.probeUntil!==void 0&&Z<$.probeUntil)return!1;return $.probeUntil=Z+J.cooldownMs,!0}record(Q,J,$){let Z=this.entries.get(Q)??{failures:0},W=Z.openUntil!==void 0;if(J==="success")return this.entries.delete(Q),W?"closed":void 0;if(J==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(Q,Z),W||Z.failures>=$.failures)return Z.openUntil=this.now()+$.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(Q){let J=this.entries.get(Q);if(J?.openUntil===void 0)return"closed";return this.now()<J.openUntil?"open":"half-open"}}var VZ=Symbol("timed-out");class CQ extends RJ{model;capabilities;entries;options;circuit;constructor(Q,J={}){super();if(Q.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of Q)if(Z.timeoutMs!==void 0&&!(Z.timeoutMs>0))throw Error(`FallbackProvider: timeoutMs for ${Z.provider.model} must be a positive number, got ${Z.timeoutMs}.`);this.entries=[...Q];let $=J.circuit;if($){let Z=$.failures??3,W=$.cooldownMs??30000;if(!Number.isInteger(Z)||Z<1)throw Error(`FallbackProvider: circuit.failures must be a positive integer, got ${Z}.`);if(!(W>0))throw Error(`FallbackProvider: circuit.cooldownMs must be a positive number, got ${W}.`);let X=new Set;for(let G of Q){let z=MJ(G);if(X.has(z))throw Error(`FallbackProvider: two legs share the circuit key "${z}". Give one of them a \`circuitKey\`.`);X.add(z)}let K=$.store??new mQ;this.options={...J,circuit:{...$,store:K}},this.circuit={policy:{failures:Z,cooldownMs:W},store:K,...$.onStateChange?{onStateChange:$.onStateChange}:{}}}else this.options=J,this.circuit=void 0;this.model=Q[0].provider.model,this.capabilities=D9(Q.map((Z)=>Z.provider.capabilities))}static chain(Q,J){return new CQ(Q,J)}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 CQ(this.entries.slice(Q),this.options)}leg(Q){let J=this.from(Q).entries[0];return new CQ([J],this.options)}upload(Q){return this.entries[0].provider.upload(Q)}deleteFile(Q){let J=this.entries[0].provider;if(!J.deleteFile)return Promise.reject(Error(`${J.constructor.name} cannot delete provider files: it does not implement deleteFile().`));return J.deleteFile(Q)}cacheWriteFactor(Q){return(this.entries.find(($)=>$.provider.model===Q)??this.entries.find(($)=>Q.startsWith($.provider.model)))?.provider.cacheWriteFactor?.(Q)}normalizeError(Q){return this.entries[0].provider.normalizeError(Q)}stream(Q){return this.run(Q)}async*run(Q){let J,$={},Z=Q.signal,W=0;for(let X=0;X<this.entries.length;X++){let K=this.entries[X],G=X===this.entries.length-1,z=K.provider.model;if(this.circuit&&!G&&!await this.allow(K))continue;W+=1;let V=!1,Y=async(L)=>{if(V)return;V=!0,await this.record(X,K,L)},D=new AbortController,N=()=>D.abort(Z?.reason);if(Z?.aborted)D.abort(Z.reason);else Z?.addEventListener("abort",N,{once:!0});let H=[],U=!1,_=!1,P,C,F,O=!1,R,f=!1,x,I=(L)=>{x=L.usage;let A=L.model??z;if(!J)return{...L,model:A};let B={...$};return B[A]=k(k(S(),B[A]??S()),L.usage),{type:"usage",usage:k(k(S(),J),L.usage),byModel:B}},h=(L)=>{if(!J)return L;let A=L.model??z,B={...$};B[A]=k(k(S(),B[A]??S()),L.usage);let q=k(k(S(),J),L.usage);J=void 0;for(let e of Object.keys($))delete $[e];let DQ=Object.entries(B).filter(([e,kQ])=>e===A||kQ.totalTokens>0);return DQ.length>1?{...L,usage:q,byModel:Object.fromEntries(DQ)}:{...L,usage:q}};try{R=K.provider.stream({...Q,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:D.signal})[Symbol.asyncIterator]();let L=K.timeoutMs!==void 0?Date.now()+K.timeoutMs:void 0;for(;;){let A=!U&&L!==void 0?await H9(R.next(),Math.max(0,L-Date.now())):await R.next();if(A===VZ){O=!0,F={error:{code:"provider_error",message:`${z} did not start answering within ${K.timeoutMs}ms.`,retryable:!0}};break}if(A.done){f=!0;break}let B=A.value;if(B.type==="finish"&&B.model)C=B.model;if(B.type==="retry"){yield B;continue}if(B.type==="usage"){yield I(B);continue}if(U){if(B.type==="finish")P=k(P??S(),B.usage),_=!0,yield h(B);else{if(B.type==="error")F={error:B.error};yield B}continue}if(GZ(B)){U=!0,await Y("success"),yield*H.splice(0),yield B;continue}if(B.type==="error")F={error:B.error,...KQ(B)};else if(B.type==="finish"){if(P=k(P??S(),B.usage),B.reason==="error"&&!F)F={error:{code:"provider_error",message:`${z} ended the call with an error and did not say which.`,retryable:!1}}}H.push(B)}}catch(L){let A=K.provider.normalizeError(L);if(U){if(A.code!=="aborted")yield{type:"error",error:A,...KQ(L)};this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:AJ(A),error:A}),yield h({type:"finish",reason:A.code==="aborted"?"aborted":"error",usage:S(),...C?{model:C}:{}});return}F={error:A,...KQ(L)}}finally{if(Z?.removeEventListener("abort",N),!f)D.abort(),R?.return?.()?.catch(()=>{})}if(U){if(!_&&J)yield{type:"finish",reason:F?"error":"stop",usage:J,byModel:{...$}},J=void 0;this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:F?AJ(F.error):"ok",...F?{error:F.error}:{}});return}if(Z?.aborted){await Y("none"),this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:"aborted"}),yield h({type:"finish",reason:"aborted",usage:P??S(),...C?{model:C}:{}});return}if(!F){await Y("success"),this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:"ok"});for(let L of H)yield L.type==="finish"?h(L):L;return}let r=!G&&F.error.code!=="aborted"&&this.shouldFallBack(F.error,{index:X,model:z,timedOut:O,...KQ(F)});if(await Y(r?"failure":"none"),this.report({index:X,model:z,responseModel:C,attempt:W,usage:P,outcome:r?"fallback":AJ(F.error),error:F.error}),r){let L=P??x;if(L){J=k(J??S(),L);let A=C??z;$[A]=k($[A]??S(),L)}continue}let p=!1,l;for(let L of H){if(L.type==="finish"){l=L;continue}if(L.type==="error")p=!0;yield L}if(!p&&F.error.code!=="aborted")yield{type:"error",error:F.error,...KQ(F)};yield h({type:"finish",reason:F.error.code==="aborted"?"aborted":l?.reason??"error",usage:P??S(),...C?{model:C}:{}});return}}async allow(Q){if(!this.circuit)return!0;try{return await this.circuit.store.allow(MJ(Q),this.circuit.policy)}catch{return!0}}async record(Q,J,$){if(!this.circuit)return;let Z=MJ(J),W;try{W=await this.circuit.store.record(Z,$,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:Q,model:J.provider.model,key:Z,state:W})}catch{}}shouldFallBack(Q,J){let $=this.options.fallbackOn??((Z)=>Z.retryable);try{return $(Q,J)}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 MJ(Q){return Q.circuitKey??Q.provider.model}function AJ(Q){return Q.code==="aborted"?"aborted":"failed"}function D9(Q){return{reasoning:Q.every((J)=>J.reasoning),structuredOutput:Q.every((J)=>J.structuredOutput),fileInput:Q.every((J)=>J.fileInput),parallelToolCalls:Q.every((J)=>J.parallelToolCalls),toolSearch:Q.every((J)=>J.toolSearch),supportsForcedToolChoice:Q.every((J)=>J.supportsForcedToolChoice!==!1),trailingContext:Q.every((J)=>J.trailingContext===!0),allowedTools:Q.every((J)=>J.allowedTools===!0)}}function H9(Q,J){let $,Z=new Promise((W)=>{$=setTimeout(()=>W(VZ),J)});return Promise.race([Q,Z]).finally(()=>clearTimeout($))}async function P9(Q,J,$={}){let Z=$.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let X=0;X<Q.entries.length;X++){let K=Q.leg(X),G={index:X,model:K.model,results:[],errors:[]};for(let z=0;z<Z;z++)try{G.results.push(await J(K,{index:X,sample:z}))}catch(V){G.errors.push({sample:z,error:V})}W.push(G)}return W}class lQ extends Error{line;constructor(Q){super(Q??"Voice session ended by the app.");this.name="VoiceHangup",this.line=Q}}var _Q="ask_agent",N9={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},F9={maxDuration:"We've reached the time limit for this voice session. Tap the microphone to start again.",idle:"It's gone quiet, so I'll hang up. Tap the microphone when you want to talk again.",error:null};function UQ(Q={}){return[{name:Q.name??_Q,description:Q.description??"Hand one self-contained request to the agent that does the work, in the user's own words with references resolved. It can take minutes; the result comes back when it is done, so tell the user you are on it.",parameters:{type:"object",properties:{request:{type:"string",description:"What the user wants done."}},required:["request"],additionalProperties:!1}},{name:"stop_work",description:"Stop the work that is running, and drop any requests waiting behind it.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"work_status",description:"What the agent is doing right now, and what is waiting.",parameters:{type:"object",properties:{},additionalProperties:!1}},{name:"answer_question",description:"Answer the question the agent asked (it came back from a request with status needs_input). For an approval, set approve.",parameters:{type:"object",properties:{answer:{type:"string",description:"The user's answer, in their words."},approve:{type:"boolean",description:"For an approval: whether the user approved."}},required:["answer"],additionalProperties:!1}}]}var pQ=new Map;class s{sessionId;threadId;callId;ended;params;sideband;hangupCall;limits;lines;delegateName;startedAt=Date.now();body;usage=S();transcription={usage:S(),seconds:0};hooks=Promise.resolve();pendingCreate;transcript=[];requests=[];toolCalls=[];toolHandlers=new Map;toolsRunning=0;toolCallTimes=[];errors=[];running;queue=[];pending=[];lastProgress;lastNoteAt=0;noteTimer;responseActive=!1;responseWanted=!1;ending;timers=[];idleTimer;tickTimer;resolveEnded;closingWaiter;static start(Q){return new s(Q)}static get(Q){return pQ.get(Q)}static async endAll(Q){await Promise.all([...pQ.values()].map((J)=>J.end("hangup",Q)))}constructor(Q){this.params=Q,this.sessionId=Q.sessionId??crypto.randomUUID(),this.threadId=Q.threadId,this.body=Q.body??{},this.limits={...N9,...zZ(Q.limits)},this.lines={...F9,...zZ(Q.lines)},this.delegateName=Q.delegate?.name??_Q;let J=new Set(UQ(Q.delegate).map(($)=>$.name));for(let $ of Q.tools??[]){if(J.has($.tool.name)||this.toolHandlers.has($.tool.name))throw Error(`VoiceBridge: two tools are named "${$.tool.name}".`);this.toolHandlers.set($.tool.name,$)}if("realtime"in Q.call){let{realtime:$,callId:Z}=Q.call;this.callId=Z,this.sideband=$.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=Q.call.callId??Q.call.sideband.callId,this.sideband=Q.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise(($)=>this.resolveEnded=$),pQ.set(this.sessionId,this),this.timers.push(setTimeout(()=>void this.end("max_duration",this.lines.maxDuration),this.limits.maxDurationMs)),this.tickTimer=setInterval(()=>void this.tick(),this.limits.tickMs),this.touch(),this.listen()}setBody(Q){this.body=Q;let J=this.params.contextNote?.(Q);if(J)this.sideband.addNote(J)}end(Q="hangup",J){return this.ending??=this.finish(Q,J??null)}async listen(){for await(let Q of this.sideband){try{this.params.onEvent?.(Q)}catch{}this.closingWaiter?.(Q),await this.handle(Q)}}async handle(Q){switch(Q.type){case"input_audio_buffer.speech_started":this.touch();return;case"response.created":this.responseActive=!0,this.pendingCreate=void 0,this.touch();return;case"response.done":{if(this.responseActive=!1,this.responseWanted&&!this.ending)this.responseWanted=!1,this.createResponse();let J=Q.usage;if(J){this.usage=k(this.usage,J);let $=this.info();this.hook(()=>this.params.onUsage?.(J,$))}return}case"conversation.item.input_audio_transcription.completed":{let J=Q;if(this.say("user",String(J.transcript??"")),J.transcriptionUsage||J.transcriptionSeconds!==void 0){this.transcription={usage:J.transcriptionUsage?k(this.transcription.usage,J.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+(J.transcriptionSeconds??0)};let $=this.info(),Z={...J.transcriptionUsage?{usage:J.transcriptionUsage}:{},...J.transcriptionSeconds!==void 0?{seconds:J.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,$))}return}case"response.output_audio_transcript.done":this.say("assistant",String(Q.transcript??""));return;case"response.output_text.done":this.say("assistant",String(Q.text??""));return;case"response.function_call_arguments.done":{let J=Q;if(this.touch(),!this.ending)this.call(J.call_id,J.name,J.arguments);return}case"session.updated":if(this.tampered(Q.session))this.end("session_tampered",null);return;case"error":{let J=Q.error;if(this.errors.push({code:J?.code,message:String(J?.message??"")}),this.pendingCreate&&J?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,J.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let J=Q;if(!this.ending&&!J.byClient)this.end(J.code===1000?"call_ended":"sideband_lost",null);return}}}say(Q,J){if(J.trim())this.transcript.push({role:Q,text:J,at:Date.now()})}call(Q,J,$){let Z=C9($);if(J===this.delegateName){let X=typeof Z.request==="string"?Z.request.trim():"";if(!X)return this.answer(Q,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:X,status:"queued"},turn:{text:X},callId:Q})}let W=this.toolHandlers.get(J);if(W)return void this.runTool(Q,W,Z);switch(J){case"stop_work":{let X=this.running;if(X)X.stopRequested=!0,X.handle?.stop({reason:"Stopped by voice."});let K=this.dropQueue();return this.answer(Q,{stopped:Boolean(X),dropped:K})}case"work_status":return this.answer(Q,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((X)=>X.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(Q,{status:"error",message:"There is no open question."});let X=typeof Z.answer==="string"?Z.answer:"",K=typeof Z.approve==="boolean"?Z.approve:void 0,G=this.pending.map((z)=>U9(z,X,K));return this.pending=[],this.enqueue({record:{request:`(answer) ${X}`,status:"queued"},turn:{toolResults:G},callId:Q})}default:return this.answer(Q,{status:"error",message:`There is no tool called ${J}.`})}}enqueue(Q){if(!this.running){this.requests.push(Q.record),this.run(Q);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(Q.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(Q.record),this.queue.push(Q),this.answer(Q.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),Q.callId=void 0}async run(Q){this.running=Q,Q.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let J=new Set;await this.waitForThread(J);let $=await this.latestBody();while(!Q.stopRequested&&await this.waitForThread(J));if(Q.stopRequested||this.ending){Q.record.status="dropped",this.complete(Q,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:$,turn:Q.turn})}catch(X){Q.record.status="refused",this.complete(Q,{status:"refused",message:X instanceof Error?X.message:"The request could not be started."});return}Q.handle=Z,Q.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(Q.record.status="done",Q.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(Q,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(Q,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(Q,{status:"stopped",text:W.text});else this.complete(Q,{status:"done",text:W.text})}catch(J){Q.record.status="done",this.complete(Q,{status:"failed",message:J instanceof Error?J.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let J=this.queue.shift();if(J&&!this.ending)this.run(J);else this.touch()}}async runTool(Q,J,$){let Z=J.tool.name,W=Date.now();if(this.toolCallTimes=this.toolCallTimes.filter((D)=>W-D<60000),this.toolCallTimes.length>=this.limits.maxToolCallsPerMinute){let D={name:Z,status:"busy"};this.toolCalls.push(D),this.answer(Q,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let X={name:Z,status:"running"};this.toolCalls.push(X),this.toolsRunning+=1,this.pauseIdle();let K=new AbortController,G=J.timeoutMs??this.limits.toolTimeoutMs,z,V;try{let D=await Promise.race([J.run($,{sessionId:this.sessionId,signal:K.signal}),new Promise((N,H)=>{z=setTimeout(()=>{H(new o(`"${Z}" took longer than ${Math.round(G/1000)} s.`)),K.abort()},G)})]);X.status="done",V={status:"done",output:this.clip(D)}}catch(D){if(D instanceof lQ){X.status="refused",X.message=D.message,this.end("usage",D.line??null);return}let N=D instanceof o?D.message:"The tool failed.";if(!(D instanceof o))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);X.status="failed",X.message=N,V={status:"failed",message:N}}finally{clearTimeout(z),X.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let Y=this.info();if(this.hook(()=>this.params.onToolCall?.({...X},Y)),!this.ending)this.answer(Q,V)}clip(Q){let J;try{J=JSON.stringify(Q)}catch{return String(Q)}if(J===void 0||J.length<=this.limits.toolOutputChars)return Q;return`${J.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${J.length} characters in all)`}async waitForThread(Q=new Set){let J=this.params.liveRuns;if(!J)return!1;let $=await J.find({threadId:this.threadId}),Z=$&&!Q.has($.runId)?J.get($.runId):null;if(!$||!Z)return!1;return Q.add($.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let Q=this.params.store;if(!Q)return this.body;let J=await Q.get(this.sessionId).catch(()=>null);if(J)this.body=J.body;return this.body}async follow(Q){let J=this.params.progress??_9();try{for await(let $ of Q.run){let Z=J($);if(Z)this.note(Z)}}catch{}}complete(Q,J){if(this.ending)return;if(Q.callId)this.sideband.functionOutput(Q.callId,J),Q.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${Q.record.request}": ${JSON.stringify(J)}`);this.respond()}answer(Q,J){this.sideband.functionOutput(Q,J),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let Q=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=Q,this.sideband.send({type:"response.create",event_id:Q})}questions(){return this.pending.map((Q)=>({kind:Q.kind,tool:String(Q.name),input:Q.input}))}dropQueue(){let Q=this.queue.splice(0);for(let J of Q)J.record.status="dropped";return Q.length}note(Q){if(Q===this.lastProgress)return;this.lastProgress=Q;let J=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if(J<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),J)}flushNote(){if(this.noteTimer)clearTimeout(this.noteTimer);if(this.noteTimer=void 0,!this.lastProgress||this.ending||!this.running)return;this.lastNoteAt=Date.now(),this.sideband.addNote(`Progress on "${this.running.record.request}": ${this.lastProgress}`)}touch(){if(this.idleTimer)clearTimeout(this.idleTimer);if(this.idleTimer=void 0,this.running||this.toolsRunning>0||this.ending)return;this.idleTimer=setTimeout(()=>void this.end("idle",this.lines.idle),this.limits.idleTimeoutMs)}pauseIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=void 0}info(){return{sessionId:this.sessionId,total:this.usage,elapsedMs:Date.now()-this.startedAt,transcription:this.transcription}}tick(){if(this.ending)return;let Q=this.info();this.hook(()=>this.params.onTick?.(Q))}hook(Q){this.hooks=this.hooks.then(async()=>{try{await Q()}catch(J){if(J instanceof lQ)this.end("usage",J.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",J),this.end("error",this.lines.error)}})}tampered(Q){let J=this.params.session;if(!J||!Q)return!1;if(J.instructions!==void 0&&Q.instructions!==void 0&&Q.instructions!==J.instructions)return!0;if(Array.isArray(Q.tools)){let $=new Set([...UQ(this.params.delegate),...J.tools??[]].map((W)=>W.name)),Z=new Set(Q.tools.map((W)=>String(W?.name)));if($.size!==Z.size||[...$].some((W)=>!Z.has(W)))return!0}return!1}async finish(Q,J){for(let K of this.timers)clearTimeout(K);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),J&&(Q!=="call_ended"&&Q!=="sideband_lost"))await this.closingLine(J);if(Q!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,X={sessionId:this.sessionId,...this.callId?{callId:this.callId}:{},threadId:this.threadId,reason:Q,startedAt:this.startedAt,endedAt:Z,durationMs:W,seconds:Math.ceil(W/1000),usage:this.usage,transcription:this.transcription,transcript:this.transcript,requests:this.requests,toolCalls:this.toolCalls,errors:this.errors};pQ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:Q}).catch(()=>{return});try{await this.params.onEnd?.(X)}catch(K){console.error("[gemi/ai] a voice session's onEnd threw.",K)}return this.resolveEnded(X),X}async hangUp(){try{await this.hangupCall()}catch(Q){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",Q),this.errors.push({code:"hangup_failed",message:Q instanceof Error?Q.message:String(Q)});let J;await Promise.race([this.sideband.closed,new Promise(($)=>J=setTimeout($,this.limits.hangupGraceMs))]),clearTimeout(J),this.sideband.close()}}async closingLine(Q){await new Promise((J)=>{let $=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",X,K=setTimeout(G,this.limits.closingLineMs);function G(){clearTimeout(K),J()}let z=()=>{W="asked",this.sideband.send({type:"response.create",event_id:$,response:{instructions:`Say exactly this to the user, and nothing else: "${Q}"`,tool_choice:"none"}})};if(this.closingWaiter=(V)=>{let Y=V;if(Y.type==="sideband.closed")return G();if(W==="cancelling"){if(Y.type==="response.done"||Y.type==="error"&&Y.error?.event_id===Z)z();return}if(Y.type==="error"&&Y.error?.event_id===$)return G();if(Y.type==="response.created"&&!X){X=Y.response?.id;return}let D=(N)=>!X||!N||N===X;if(Y.type==="response.done"&&D(Y.response?.id))W="playing";else if(Y.type==="output_audio_buffer.stopped"&&W==="playing"&&D(Y.response_id))G()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else z()}),this.closingWaiter=void 0}}function zZ(Q){if(!Q)return{};return Object.fromEntries(Object.entries(Q).filter(([,J])=>J!==void 0))}function C9(Q){try{let J=JSON.parse(Q);return J&&typeof J==="object"&&!Array.isArray(J)?J:{}}catch{return{}}}function U9(Q,J,$){let Z={toolCallId:Q.toolCallId,signature:Q.signature,...Q.path?{path:Q.path}:{}};if(Q.kind==="question")return{...Z,output:J};if(Q.kind==="approval")return{...Z,approve:$===!0,...J?{reason:J}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function _9(){let Q=new Set;return(J)=>{if(J.type==="tool-call"){if(J.part.partial||J.resent||Q.has(J.part.toolCallId))return;return Q.add(J.part.toolCallId),`running ${String(J.part.name)}`}if(J.type==="tool-progress"){let $=J.data;if(typeof $==="string")return $;if($&&typeof $==="object")for(let Z of["message","label","title"]){let W=$[Z];if(typeof W==="string"&&W)return W}}return}}var YZ="http://gemi.internal/__gemi__/voice/mcp";async function EJ(Q,J){if(!J.user)throw Error("Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.");let{registry:$}=Q,Z=Q.scopes??$.scopes().map((K)=>K.name),W=(K)=>({kind:"remote",req:K,principal:{user:J.user,via:"voice",id:`voice:${J.sessionId}`,scopes:Z}});return(await $.available(W(DZ()),Q.filter)).filter((K)=>!K.requiresApproval).map((K)=>({tool:{name:K.name,description:K.description,parameters:K.inputSchema},...Q.timeoutMs!==void 0?{timeoutMs:Q.timeoutMs}:{},run:(G,z)=>{let V=DZ();return n.run(V,async()=>{return await Q.authorize?.({name:K.name,input:G,sessionId:z.sessionId}),$.execute(W(V),K.name,G,void 0,{signal:z.signal})},{user:J.user})}}))}function DZ(){return new w(new Request(YZ,{method:"POST"}),{},"api",new URL(YZ).pathname)}class kJ{records=new Map;retainEndedMs;constructor(Q={}){this.retainEndedMs=Q.retainEndedMs??600000}async create(Q){this.sweep(),this.records.set(Q.id,structuredClone(Q))}async get(Q){let J=this.records.get(Q);return J?structuredClone(J):null}async update(Q,J){let $=this.records.get(Q);if(!$)return;this.records.set(Q,{...$,...structuredClone(J),id:Q})}sweep(){let Q=Date.now()-this.retainEndedMs;for(let[J,$]of this.records)if($.endedAt!==void 0&&$.endedAt<Q)this.records.delete(J)}}var TJ=new kJ;var HZ=100;class jJ{threadsTable;messagesTable;scope=null;sql;dialect;connection;options;constructor(Q,J={}){if(this.threadsTable=PZ(J.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=PZ(J.messagesTable??"gemi_agent_messages","messages"),this.sql=Q.sql,this.dialect=Q.dialect,this.connection=Q.name,this.options=J,J.ttlMs!==void 0)UZ(J.ttlMs,"ttlMs")}get expires(){return this.options.ttlMs!==void 0}forScope(Q){if(typeof Q!=="string"||Q==="")throw TypeError("A DatabaseAgentStore scope is a non-empty string.");let J=new jJ({sql:this.sql,dialect:this.dialect,name:this.connection},this.options);return J.scope=Q,J}async createTable(){let Q=B9(this.dialect,this.threadsTable,this.messagesTable);for(let J of Q)await this.sql.unsafe(J);await this.addScopeColumns(),await this.addExpiryColumns()}async addExpiryColumns(){if(await this.hasColumn(this.threadsTable,"expires_at"))return;for(let Q of M9(this.dialect,this.threadsTable))await this.sql.unsafe(Q)}async addScopeColumns(){let Q=S9(this.dialect,this.threadsTable,this.messagesTable);for(let[J,$]of Q){if(await this.hasColumn(J,"scope"))continue;for(let Z of $)await this.sql.unsafe(Z)}}async hasColumn(Q,J){try{return await this.sql.unsafe(`SELECT ${J} FROM ${this.quote(Q)} WHERE 1 = 0`),!0}catch{return!1}}async createThread(Q={}){let J=crypto.randomUUID(),$=Q.userId===void 0||Q.userId===null?null:String(Q.userId),Z=this.expiryOf(Q);return await this.run(async(W)=>{let X=this.clock(W);if(Z){let K=Z.at!==void 0?this.ms(W,Z.at):Z.ttlMs===null?null:W`${X} + ${this.ms(W,Z.ttlMs)}`,G=Z.slides&&Z.ttlMs!==null?this.ms(W,Z.ttlMs):null;if(this.scope===null)await W`
|
|
182
182
|
INSERT INTO ${this.threads(W)} (id, user_id, created_at, updated_at, expires_at, ttl_ms)
|
|
183
183
|
VALUES (${J}, ${$}, ${X}, ${X}, ${K}, ${G})
|
|
184
184
|
`;else await W`
|
|
@@ -222,7 +222,7 @@ import{ca as QZ,da as WZ,ea as XZ,fa as e6,ga as Q0,ha as J0,ia as W$,ja as $0,k
|
|
|
222
222
|
`,K.add(V.id),z+=1;else await $`
|
|
223
223
|
INSERT INTO ${this.messages($)} (thread_id, scope, id, position, message, created_at)
|
|
224
224
|
VALUES (${Q}, ${this.scope}, ${V.id}, ${z}, ${Y}, ${this.clock($)})
|
|
225
|
-
`,K.add(V.id),z+=1}if(Z[0].title===null||Z[0].title===void 0){let V=
|
|
225
|
+
`,K.add(V.id),z+=1}if(Z[0].title===null||Z[0].title===void 0){let V=O9(J);if(V!==null)await $`
|
|
226
226
|
UPDATE ${this.threads($)} SET title = ${V}
|
|
227
227
|
WHERE id = ${Q} AND title IS NULL
|
|
228
228
|
`}})}async removeMessages(Q,J){if(J.length===0)return;await this.run(async($)=>{await $`
|
|
@@ -238,7 +238,7 @@ import{ca as QZ,da as WZ,ea as XZ,fa as e6,ga as Q0,ha as J0,ia as W$,ja as $0,k
|
|
|
238
238
|
`;let[Z]=await $`
|
|
239
239
|
SELECT summaries FROM ${this.threads($)}
|
|
240
240
|
WHERE id = ${Q} AND ${this.inScope($)} AND ${this.live($)}
|
|
241
|
-
`;if(!Z)return;let W=
|
|
241
|
+
`;if(!Z)return;let W=OQ(FZ(Z.summaries),J);await $`
|
|
242
242
|
UPDATE ${this.threads($)} SET summaries = ${JSON.stringify(W)}
|
|
243
243
|
WHERE id = ${Q}
|
|
244
244
|
`})}async lockSummary(Q,J,$){let Z=`${J}:${crypto.randomUUID()}`;if(!await this.run(async(X)=>{let K=this.clock(X),G=await X`
|
|
@@ -246,7 +246,7 @@ import{ca as QZ,da as WZ,ea as XZ,fa as e6,ga as Q0,ha as J0,ia as W$,ja as $0,k
|
|
|
246
246
|
SET summary_lock = ${Z}, summary_lock_until = ${K} + ${this.ms(X,$)}
|
|
247
247
|
WHERE id = ${Q} AND ${this.inScope(X)} AND ${this.live(X)}
|
|
248
248
|
AND (summary_lock_until IS NULL OR summary_lock_until <= ${K})
|
|
249
|
-
`;return
|
|
249
|
+
`;return L9(G)>0}))return null;return async()=>{await this.run(async(X)=>{await X`
|
|
250
250
|
UPDATE ${this.threads(X)} SET summary_lock = NULL, summary_lock_until = NULL
|
|
251
251
|
WHERE id = ${Q} AND ${this.inScope(X)} AND summary_lock = ${Z}
|
|
252
252
|
`})}}async getThread(Q){return this.run(async(J)=>{let[$]=await J`
|
|
@@ -265,7 +265,7 @@ import{ca as QZ,da as WZ,ea as XZ,fa as e6,ga as Q0,ha as J0,ia as W$,ja as $0,k
|
|
|
265
265
|
LIMIT ${J}
|
|
266
266
|
`;if(X.length===0)return{deleted:0};let K=X.map((V)=>String(V.id));await $`UPDATE ${this.threads($)} SET updated_at = updated_at WHERE id IN (${GQ($,K)})`;let G=await $`
|
|
267
267
|
SELECT id FROM ${this.threads($)} WHERE id IN (${GQ($,K)}) AND ${W}
|
|
268
|
-
`;if(G.length===0)return{deleted:0};let z=G.map((V)=>String(V.id));return await $`DELETE FROM ${this.messages($)} WHERE thread_id IN (${GQ($,z)})`,await $`DELETE FROM ${this.threads($)} WHERE id IN (${GQ($,z)})`,{deleted:z.length}})}atomically(Q){if(this.guard(),this.joinable())return vQ(this.sql,(W)=>Q(W),{connection:this.connection,dialect:this.dialect});let J=this.scope,$=this.options.beginScope,Z=()=>this.sql.begin(async(W)=>{if(J!==null&&$)await $(W,J);return Q(W)});if(this.dialect!=="sqlite")return Z();return _Z(this.sql,Z)}joinable(){if(this.connection===void 0)return;let Q=ZQ();if(Q===void 0||WQ()!==this.connection)return;return Q}run(Q){this.guard();let J=this.joinable();if(J)return Q(J);if(this.scope!==null&&this.options.beginScope)return this.atomically(Q);return Q(this.sql)}guard(){if(this.scope===null&&this.options.requireScope)throw Error("This DatabaseAgentStore requires a scope: call it through store.forScope(scope).")}inScope(Q){return this.scope===null?Q`1 = 1`:Q`scope = ${this.scope}`}live(Q){return this.expires?Q`(expires_at IS NULL OR expires_at > ${this.clock(Q)})`:Q`1 = 1`}recordColumns(Q){return this.expires?Q.unsafe("id, user_id, title, created_at, updated_at, expires_at"):Q.unsafe("id, user_id, title, created_at, updated_at")}expiryOf(Q){let J=Q.ttlMs!==void 0||Q.expiresAt!==void 0;if(!this.expires){if(J)throw Error("createThread({ ttlMs, expiresAt }) needs a store with `ttlMs`: set `new DatabaseAgentStore(connection, { ttlMs })`, which turns expiry on and reads the expiry columns.");return null}if(Q.expiresAt!==void 0){let Z=Q.expiresAt instanceof Date?Q.expiresAt.getTime():Q.expiresAt;if(!Number.isFinite(Z))throw TypeError("createThread: `expiresAt` is not a valid time.");return{at:Z,ttlMs:null,slides:!1}}let $=Q.ttlMs===void 0?this.options.ttlMs:Q.ttlMs;if($!==null)UZ($,"createThread: ttlMs");return{ttlMs:$,slides:this.options.slidingTtl===!0}}quote(Q){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${Q}\``:`"${Q}"`}threads(Q){return Q.unsafe(this.quote(this.threadsTable))}messages(Q){return Q.unsafe(this.quote(this.messagesTable))}clock(Q){switch(this.dialect){case"postgres":return Q`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return Q`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return Q`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(Q,J){let $=Math.max(0,Math.round(J));return this.dialect==="mysql"||this.dialect==="mariadb"?Q`CAST(${$} AS SIGNED)`:Q`CAST(${$} AS BIGINT)`}}function PZ(Q,J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent ${J} table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);return Q}function NZ(Q){return Error(`Thread ${Q} does not exist here, or has been deleted.`)}function GQ(Q,J){return J.map(($)=>Q`${$}`).reduce(($,Z)=>Q`${$}, ${Z}`)}function
|
|
268
|
+
`;if(G.length===0)return{deleted:0};let z=G.map((V)=>String(V.id));return await $`DELETE FROM ${this.messages($)} WHERE thread_id IN (${GQ($,z)})`,await $`DELETE FROM ${this.threads($)} WHERE id IN (${GQ($,z)})`,{deleted:z.length}})}atomically(Q){if(this.guard(),this.joinable())return vQ(this.sql,(W)=>Q(W),{connection:this.connection,dialect:this.dialect});let J=this.scope,$=this.options.beginScope,Z=()=>this.sql.begin(async(W)=>{if(J!==null&&$)await $(W,J);return Q(W)});if(this.dialect!=="sqlite")return Z();return _Z(this.sql,Z)}joinable(){if(this.connection===void 0)return;let Q=ZQ();if(Q===void 0||WQ()!==this.connection)return;return Q}run(Q){this.guard();let J=this.joinable();if(J)return Q(J);if(this.scope!==null&&this.options.beginScope)return this.atomically(Q);return Q(this.sql)}guard(){if(this.scope===null&&this.options.requireScope)throw Error("This DatabaseAgentStore requires a scope: call it through store.forScope(scope).")}inScope(Q){return this.scope===null?Q`1 = 1`:Q`scope = ${this.scope}`}live(Q){return this.expires?Q`(expires_at IS NULL OR expires_at > ${this.clock(Q)})`:Q`1 = 1`}recordColumns(Q){return this.expires?Q.unsafe("id, user_id, title, created_at, updated_at, expires_at"):Q.unsafe("id, user_id, title, created_at, updated_at")}expiryOf(Q){let J=Q.ttlMs!==void 0||Q.expiresAt!==void 0;if(!this.expires){if(J)throw Error("createThread({ ttlMs, expiresAt }) needs a store with `ttlMs`: set `new DatabaseAgentStore(connection, { ttlMs })`, which turns expiry on and reads the expiry columns.");return null}if(Q.expiresAt!==void 0){let Z=Q.expiresAt instanceof Date?Q.expiresAt.getTime():Q.expiresAt;if(!Number.isFinite(Z))throw TypeError("createThread: `expiresAt` is not a valid time.");return{at:Z,ttlMs:null,slides:!1}}let $=Q.ttlMs===void 0?this.options.ttlMs:Q.ttlMs;if($!==null)UZ($,"createThread: ttlMs");return{ttlMs:$,slides:this.options.slidingTtl===!0}}quote(Q){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${Q}\``:`"${Q}"`}threads(Q){return Q.unsafe(this.quote(this.threadsTable))}messages(Q){return Q.unsafe(this.quote(this.messagesTable))}clock(Q){switch(this.dialect){case"postgres":return Q`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return Q`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return Q`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(Q,J){let $=Math.max(0,Math.round(J));return this.dialect==="mysql"||this.dialect==="mariadb"?Q`CAST(${$} AS SIGNED)`:Q`CAST(${$} AS BIGINT)`}}function PZ(Q,J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent ${J} table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);return Q}function NZ(Q){return Error(`Thread ${Q} does not exist here, or has been deleted.`)}function GQ(Q,J){return J.map(($)=>Q`${$}`).reduce(($,Z)=>Q`${$}, ${Z}`)}function O9(Q){for(let J of Q){if(J.role!=="user"||J.event)continue;let $=J.content.map((Z)=>Z.type==="text"?Z.text:"").join(" ").replace(/\s+/g," ").trim();if($)return $.length>HZ?`${$.slice(0,HZ-1)}\u2026`:$}return null}function FZ(Q){if(Q===null||Q===void 0||Q==="")return[];let J=JSON.parse(String(Q));return Array.isArray(J)?J:[]}function CZ(Q){return{id:String(Q.id),userId:Q.user_id===null||Q.user_id===void 0?null:String(Q.user_id),title:Q.title===null||Q.title===void 0?null:String(Q.title),createdAt:Number(Q.created_at),updatedAt:Number(Q.updated_at),..."expires_at"in Q?{expiresAt:Q.expires_at===null||Q.expires_at===void 0?null:Number(Q.expires_at)}:{}}}function UZ(Q,J){if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=0)throw TypeError(`${J} must be a positive number of milliseconds.`)}function L9(Q){let J=Q;return Math.max(Number(J.count??0),Number(J.affectedRows??0))}function B9(Q,J,$){if(Q==="mysql"||Q==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${J}\` (
|
|
269
269
|
\`id\` VARCHAR(191) NOT NULL,
|
|
270
270
|
\`scope\` VARCHAR(191) NULL,
|
|
271
271
|
\`user_id\` VARCHAR(191) NULL,
|
|
@@ -315,13 +315,13 @@ import{ca as QZ,da as WZ,ea as XZ,fa as e6,ga as Q0,ha as J0,ia as W$,ja as $0,k
|
|
|
315
315
|
"created_at" BIGINT NOT NULL,
|
|
316
316
|
|
|
317
317
|
CONSTRAINT "${$}_pkey" PRIMARY KEY ("thread_id", "id")
|
|
318
|
-
)`,`CREATE UNIQUE INDEX IF NOT EXISTS "${$}_thread_id_position_key" ON "${$}"("thread_id", "position")`]}function S9(Q,J,$){if(Q==="mysql"||Q==="mariadb")return[[J,[`ALTER TABLE \`${J}\` ADD COLUMN \`scope\` VARCHAR(191) NULL, ADD INDEX \`${J}_scope_user_id_updated_at_idx\`(\`scope\`, \`user_id\`, \`updated_at\`)`]],[$,[`ALTER TABLE \`${$}\` ADD COLUMN \`scope\` VARCHAR(191) NULL`]]];return[[J,[`ALTER TABLE "${J}" ADD COLUMN "scope" TEXT`,`CREATE INDEX IF NOT EXISTS "${J}_scope_user_id_updated_at_idx" ON "${J}"("scope", "user_id", "updated_at")`]],[$,[`ALTER TABLE "${$}" ADD COLUMN "scope" TEXT`]]]}function M9(Q,J){if(Q==="mysql"||Q==="mariadb")return[`ALTER TABLE \`${J}\` ADD COLUMN \`expires_at\` BIGINT NULL, ADD COLUMN \`ttl_ms\` BIGINT NULL, ADD INDEX \`${J}_expires_at_idx\`(\`expires_at\`)`];return[`ALTER TABLE "${J}" ADD COLUMN "expires_at" BIGINT`,`ALTER TABLE "${J}" ADD COLUMN "ttl_ms" BIGINT`,`CREATE INDEX IF NOT EXISTS "${J}_expires_at_idx" ON "${J}"("expires_at")`]}class VQ extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,J,$){super(`Frame ${J} of run ${Q} has been evicted; the oldest frame still buffered is ${$}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=J;this.oldest=$}}class
|
|
318
|
+
)`,`CREATE UNIQUE INDEX IF NOT EXISTS "${$}_thread_id_position_key" ON "${$}"("thread_id", "position")`]}function S9(Q,J,$){if(Q==="mysql"||Q==="mariadb")return[[J,[`ALTER TABLE \`${J}\` ADD COLUMN \`scope\` VARCHAR(191) NULL, ADD INDEX \`${J}_scope_user_id_updated_at_idx\`(\`scope\`, \`user_id\`, \`updated_at\`)`]],[$,[`ALTER TABLE \`${$}\` ADD COLUMN \`scope\` VARCHAR(191) NULL`]]];return[[J,[`ALTER TABLE "${J}" ADD COLUMN "scope" TEXT`,`CREATE INDEX IF NOT EXISTS "${J}_scope_user_id_updated_at_idx" ON "${J}"("scope", "user_id", "updated_at")`]],[$,[`ALTER TABLE "${$}" ADD COLUMN "scope" TEXT`]]]}function M9(Q,J){if(Q==="mysql"||Q==="mariadb")return[`ALTER TABLE \`${J}\` ADD COLUMN \`expires_at\` BIGINT NULL, ADD COLUMN \`ttl_ms\` BIGINT NULL, ADD INDEX \`${J}_expires_at_idx\`(\`expires_at\`)`];return[`ALTER TABLE "${J}" ADD COLUMN "expires_at" BIGINT`,`ALTER TABLE "${J}" ADD COLUMN "ttl_ms" BIGINT`,`CREATE INDEX IF NOT EXISTS "${J}_expires_at_idx" ON "${J}"("expires_at")`]}class VQ extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,J,$){super(`Frame ${J} of run ${Q} has been evicted; the oldest frame still buffered is ${$}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=J;this.oldest=$}}class LQ 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;threadRuns=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,J={}){let $={run:Q,threadId:J.threadId,startedAt:Date.now(),owner:J.owner??null,clientRunId:J.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,$),J.threadId){this.byThread.set(J.threadId,Q.runId);let Z=this.threadRuns.get(J.threadId);if(!Z)Z=new Set,this.threadRuns.set(J.threadId,Z);Z.add(Q.runId)}if(J.clientRunId)this.byClientRun.set(J.clientRunId,Q.runId);return this.scheduleExpiry($,J.maxRunDurationMs),this.pump($,J)}findByClientRunId(Q){let J=this.byClientRun.get(Q);return J&&this.runs.has(J)?J:null}async find(Q){let J=this.byThread.get(Q.threadId);if(!J)return null;let $=this.runs.get(J);if(!$)return null;return{runId:J,seq:$.lastSeq}}running(Q){let J=[];for(let $ of this.threadRuns.get(Q.threadId)??[]){let Z=this.runs.get($);if(!Z||Z.ended||Z.evicted)continue;J.push({runId:$,seq:Z.lastSeq,startedAt:Z.startedAt})}return J}threadOf(Q){return this.runs.get(Q)?.threadId}get(Q){return this.runs.get(Q)?.run??null}ownerOf(Q){return this.runs.get(Q)?.owner??null}mayAccess(Q,J){let $=this.ownerOf(Q);return $===null||$===J}isRunning(Q){let J=this.runs.get(Q);return!!J&&!J.ended&&!J.evicted}replay(Q,J){let $=this.runs.get(Q);if(!$)throw new LQ(Q);if(J!==void 0&&J<$.lostBefore)throw new VQ(Q,J,$.lostBefore);let Z=$.frames[0]?.seq;return this.drain($,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.threadRuns.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(Q,J){let $=Promise.resolve();try{for await(let Z of Q.run.frames()){if(Q.evicted){let X=J.onEvent;if(X)$=$.then(()=>X(Z.event)).catch((K)=>xJ(J,K));continue}if(Q.frames.push(Z),Q.lastSeq=Z.seq,Q.frames.length>this.maxFrames){let X=Q.frames.shift();if(X)Q.lostBefore=X.seq+1}this.notify(Q);let W=J.onEvent;if(W)$=$.then(()=>W(Z.event)).catch((X)=>xJ(J,X))}}catch(Z){xJ(J,Z)}finally{if(Q.ended=!0,Q.expireAt)clearTimeout(Q.expireAt),Q.expireAt=null;this.notify(Q),this.scheduleEviction(Q),await $}}async*drain(Q,J,$){let Z=$;while(!0){let W=Q.version;for(;;){if(Z<Q.lostBefore)throw new VQ(J,Z,Q.lostBefore);let X=Q.frames,K=X[0]?.seq;if(K===void 0)break;let G=Math.max(0,Z-K);if(G>=X.length)break;let z=X[G];yield z,Z=z.seq+1}if(Q.ended&&Z>Q.lastSeq||Q.evicted)return;await this.wait(Q,W)}}wait(Q,J){if(Q.version!==J)return Promise.resolve();return new Promise(($)=>Q.wake.add($))}notify(Q){Q.version++;let J=Array.from(Q.wake);Q.wake.clear();for(let $ of J)$()}scheduleEviction(Q){if(Q.evictAt)return;let J=setTimeout(()=>{let $=Q.run.runId;if(!Q.ended)Q.evicted=!0,Q.frames=[];if(this.runs.get($)===Q)this.runs.delete($);if(Q.threadId&&this.byThread.get(Q.threadId)===$)this.byThread.delete(Q.threadId);if(Q.threadId){let Z=this.threadRuns.get(Q.threadId);if(Z?.delete($),Z?.size===0)this.threadRuns.delete(Q.threadId)}if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===$)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);J.unref?.(),Q.evictAt=J}scheduleExpiry(Q,J){if(this.maxAgeMs===null||J===null)return;let $=J===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,J+this.ttlMs);if(!Number.isFinite($)||$>2147483647)return;let Z=setTimeout(()=>{if(Q.expireAt=null,Q.ended)return;try{Q.run.stop({reason:`The run was still going ${Math.round($/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(Q)},$);Z.unref?.(),Q.expireAt=Z}}var IJ=new iQ;function xJ(Q,J){try{Q.onInternalError?.(J)}catch{}}class dQ{maxEntries;records=new Map;constructor(Q=1e5){this.maxEntries=Q}async record(Q,J){if(this.records.has(Q))return;this.records.set(Q,{...J});while(this.records.size>this.maxEntries){let $=this.records.keys().next().value;if($===void 0)break;this.records.delete($)}}async get(Q){let J=this.records.get(Q);return J?{...J}:null}async delete(Q){this.records.delete(Q)}async expired(Q,J){let $=[];for(let[Z,W]of this.records){if($.length>=J)break;if(W.expiresAt&&Date.parse(W.expiresAt)<=Q.getTime())$.push(Z)}return $}}var wJ=new dQ;class bJ{now;receipts=new Map;sweepAt=1024;constructor(Q=Date.now){this.now=Q}async claim(Q,J){let $=this.now();if(this.receipts.size>=this.sweepAt)this.sweep($);let Z=this.receipts.get(Q);if(Z&&Z.expiresAt>$)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(Q,{expiresAt:J}),{status:"claimed"}}async complete(Q,J,$){this.receipts.set(Q,{result:structuredClone(J),expiresAt:$})}async release(Q){let J=this.receipts.get(Q);if(J&&!J.result)this.receipts.delete(Q)}get size(){return this.receipts.size}sweep(Q){for(let[J,$]of this.receipts)if($.expiresAt<=Q)this.receipts.delete(J);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var OZ="pending",fJ="done:",A9=`
|
|
319
319
|
if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
|
|
320
320
|
local held = redis.call('GET', KEYS[1])
|
|
321
321
|
if not held then return ARGV[1] end
|
|
322
322
|
return held`,R9=`
|
|
323
323
|
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
324
|
-
return 0`;class vJ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:receipt"}async claim(Q,J){let $=await this.client.send("EVAL",[A9,"1",this.key(Q),LZ
|
|
324
|
+
return 0`;class vJ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:receipt"}async claim(Q,J){let $=await this.client.send("EVAL",[A9,"1",this.key(Q),OZ,LZ(J)]);if($==="claimed")return{status:"claimed"};let Z=String($??"");if(Z.startsWith(fJ))return{status:"replay",result:JSON.parse(Z.slice(fJ.length))};return{status:"blocked"}}async complete(Q,J,$){await this.client.send("SET",[this.key(Q),fJ+JSON.stringify(J),"PX",LZ($)])}async release(Q){await this.client.send("EVAL",[R9,"1",this.key(Q),OZ])}key(Q){return`${this.prefix}:${Q}`}get client(){if(this.injectedClient)return this.injectedClient;let Q=BZ(),J=Q.bound(qJ)?Q.make(qJ).client:void 0;if(!J)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return J}}function LZ(Q){return String(Math.max(1,Math.ceil(Q-Date.now())))}var E9=86400000,k9=60000;class BQ{ttlMs;slidingTtl;clientOwnedIds;scope=null;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??E9,this.slidingTtl=Q.slidingTtl??!0,this.clientOwnedIds=Q.clientOwnedIds??!1}forScope(Q){if(typeof Q!=="string"||Q==="")throw TypeError("A MemoryAgentStore scope is a non-empty string.");let J=new BQ({ttlMs:this.ttlMs,slidingTtl:this.slidingTtl,clientOwnedIds:this.clientOwnedIds});return J.threads=this.threads,J.scope=Q,J}visible(Q,J=Date.now()){let $=this.threads.get(Q);if($&&yJ($,J)){this.threads.delete(Q);return}if(!$||this.scope===null||$.scope===this.scope)return $;return}fresh(Q={}){let J=Date.now(),$,Z=null;if(Q.expiresAt!==void 0){if($=Q.expiresAt instanceof Date?Q.expiresAt.getTime():Q.expiresAt,!Number.isFinite($))throw TypeError("createThread: `expiresAt` is not a valid time.")}else{let W=Q.ttlMs===void 0?this.ttlMs:Q.ttlMs;if(W!==null&&!(typeof W==="number"&&W>0))throw TypeError("createThread: ttlMs must be a positive number of milliseconds.");$=W===null?null:J+W,Z=this.slidingTtl?W:null}return{messages:[],expiresAt:$,slideMs:Z,...this.scope!==null?{scope:this.scope}:{}}}touch(Q){if(Q.slideMs!==null)Q.expiresAt=Date.now()+Q.slideMs}async createThread(Q={}){let J=crypto.randomUUID();return this.threads.set(J,this.fresh(Q)),this.sweep(),{threadId:J}}async loadThread(Q){this.sweep();let J=this.visible(Q);if(!J){if(this.threads.has(Q))return null;return this.clientOwnedIds?[]:null}return this.touch(J),J.messages.slice()}async appendMessages(Q,J){this.sweep();let $=this.visible(Q);if(!$){if(!this.clientOwnedIds||this.threads.has(Q))throw Error(`Thread ${Q} does not exist here, or has expired.`);$=this.fresh(),this.threads.set(Q,$)}for(let Z of J){let W=JSON.parse(JSON.stringify(Z)),X=$.messages.findIndex((K)=>K.id===W.id);if(X===-1)$.messages.push(W);else $.messages[X]=W}this.touch($)}async removeMessages(Q,J){this.sweep();let $=this.visible(Q);if(!$)return;let Z=new Set(J);$.messages=$.messages.filter((W)=>!Z.has(W.id)),this.touch($)}async loadSummaries(Q){return this.visible(Q)?.summaries?.slice()??[]}async saveSummary(Q,J){let $=this.visible(Q);if(!$)return;$.summaries=OQ($.summaries??[],J)}delete(Q){if(this.visible(Q))this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<k9)return;this.lastSweep=Q;for(let[J,$]of this.threads)if(yJ($,Q))this.threads.delete(J)}async sweepExpired(Q={}){let J=Q.now??Date.now(),$=Math.max(0,Math.floor(Q.limit??500)),Z=0;for(let[W,X]of this.threads){if($===0)break;if(this.scope!==null&&X.scope!==this.scope)continue;if(yJ(X,J))this.threads.delete(W),Z+=1,$-=1}return{deleted:Z}}}function yJ(Q,J){return Q.expiresAt!==null&&J>=Q.expiresAt}var hJ=new BQ;class SZ{buffer="";textDecoder=new TextDecoder;pendingCR=!1;lastSeq=-1;get cursor(){return this.lastSeq}push(Q){return this.append(typeof Q==="string"?Q:this.textDecoder.decode(Q,{stream:!0})),this.drain()}flush(){this.append(this.textDecoder.decode());let Q=this.drain();return this.buffer="",this.pendingCR=!1,Q}append(Q){if(Q==="")return;let J=Q;if(this.pendingCR){if(this.buffer+=`
|
|
325
325
|
`,this.pendingCR=!1,J.startsWith(`
|
|
326
326
|
`))J=J.slice(1)}if(J.endsWith("\r"))J=J.slice(0,-1),this.pendingCR=!0;this.buffer+=J.replace(/\r\n/g,`
|
|
327
327
|
`).replace(/\r/g,`
|
|
@@ -331,8 +331,8 @@ return 0`;class vJ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q
|
|
|
331
331
|
|
|
332
332
|
`)}return Q}parse(Q){let J,$=[];for(let K of Q.split(`
|
|
333
333
|
`)){if(K===""||K.startsWith(":"))continue;let G=K.indexOf(":"),z=G===-1?K:K.slice(0,G),V=G===-1?"":K.slice(G+1);if(V.startsWith(" "))V=V.slice(1);if(z==="data")$.push(V);else if(z==="id")J=V}if($.length===0)return null;let Z;try{Z=JSON.parse($.join(`
|
|
334
|
-
`))}catch{return null}let W=J===void 0||J===""?Number.NaN:Number(J),X=Number.isFinite(W)?W:this.lastSeq+1;return this.lastSeq=X,{seq:X,event:Z}}}async function*MZ(Q){if(!Q)return;let J=Q.getReader(),$=new SZ;try{while(!0){let{done:Z,value:W}=await J.read();if(Z){yield*$.flush();return}if(W)yield*$.push(W)}}finally{try{await J.cancel()}catch{}}}function kZ(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 T9(Q){let J=new Map;for(let $ of Q)for(let Z of $.content)if(Z.type==="tool-call")J.set(Z.toolCallId,$.turn);return J}var j9=(Q)=>Q.path?.[0]??Q.toolCallId;function x9(Q,J,$){if(J.length===0)return[];let Z=T9(Q),W=(G)=>G.turn??Z.get(j9(G)),X=new Set($.map(W));if(X.has(void 0)||X.size===0)return[];let K=new Set($.map((G)=>G.toolCallId));return J.filter((G)=>{let z=W(G);return z!==void 0&&!X.has(z)&&!K.has(G.toolCallId)})}function TZ(Q,J,$=new Date().toISOString()){if(!(J.event.type==="run-start"&&J.event.runId!==Q.cursorRunId)&&J.seq<=Q.seq)return Q;return{...jZ(Q,J.event,$),seq:J.seq}}function jZ(Q,J,$){switch(J.type){case"run-start":return{...Q,messages:I9(Q.messages,J.runId),runId:J.runId,cursorRunId:J.runId,threadId:J.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return u(Q,J.messageId,$,(Z)=>({...Z,role:J.role,...J.turn&&Z.turn===void 0?{turn:J.turn}:{}}));case"text-delta":if(RZ(Q,J.messageId))return Q;return u(Q,J.messageId,$,(Z)=>({...Z,content:v9(Z.content,J.delta)}));case"reasoning-delta":if(RZ(Q,J.messageId))return Q;return u(Q,J.messageId,$,(Z)=>({...Z,content:y9(Z.content,J.delta,J.id,J.providerMetadata)}));case"output-delta":return u(Q,J.messageId,$,(Z)=>({...Z,content:EZ(Z.content,{type:"output",value:J.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return u(Q,J.messageId,$,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===J.part.toolCallId),X=W===-1?void 0:Z.content[W],K=J.part.progress??X?.progress,G=J.part.nested??X?.nested,z=J.part.attachments??X?.attachments,V={...J.part,...K?{progress:K}:{},...G?{nested:G}:{},...z?{attachments:z}:{}},Y=Z.content.slice();if(W===-1)Y.push(V);else Y[W]=V;return{...Z,content:Y}});case"tool-call-discard":return u(Q,J.messageId,$,(Z)=>{let W=Z.content.filter((X)=>!(X.type==="tool-call"&&X.partial&&J.toolCallIds.includes(X.toolCallId)));return W.length===Z.content.length?Z:{...Z,content:W}});case"tool-search":{let Z=J.loaded.filter((W)=>!Q.loadedTools.includes(W));if(Z.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...Z]}}case"tool-progress":return AZ(Q,J.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],J.data]}));case"nested-event":{let Z=J;return AZ(Q,J.toolCallId,(W)=>{let X=W.nested??[],K=X.findIndex((Y)=>Y.runId===Z.runId),G=X[K]??{runId:Z.runId,agent:Z.agent,messages:[]},z=q9(G,Z,$),V=K===-1?[...X,z]:X.map((Y,D)=>D===K?z:Y);return{...W,nested:V}})}case"tool-result":{let Z=u(Q,J.messageId,$,(W)=>({...W,content:EZ(W.content,J.part,(X)=>X.type==="tool-result"&&X.toolCallId===J.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==J.part.toolCallId)}}case"message":{let Z=Q.messages.findIndex((K)=>K.id===J.message.id),W=Q.messages.slice();if(Z===-1)W.push(J.message);else W[Z]=J.message;let X=Q.runMessageIds.includes(J.message.id)?Q.runMessageIds:[...Q.runMessageIds,J.message.id];return{...Q,messages:W,runMessageIds:X}}case"message-id":{let Z=Q.messages.findIndex((G)=>G.id===J.localId);if(Z===-1){if(!J.message||Q.messages.some((G)=>G.id===J.messageId))return Q;return{...Q,messages:[...Q.messages,J.message]}}let W=Q.messages[Z],X={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},K=Q.messages.some((G)=>G.id===J.messageId)?Q.messages.filter((G,z)=>z!==Z).map((G)=>G.id===J.messageId?{...G,...X}:G):Q.messages.map((G,z)=>z===Z?{...G,...X,id:J.messageId}:G);return{...Q,messages:K}}case"awaiting-input":return{...Q,runId:J.runId,pending:[...x9(Q.messages,Q.pending,J.pending),...J.pending]};case"message-end":return u(Q,J.messageId,$,(Z)=>({...Z,finishReason:J.finishReason,...J.outputTruncated?{outputTruncated:!0}:{},...J.usage?{usage:J.usage}:{},content:J.outputTruncated||J.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...Q,usage:J.usage};case"retry":return Q;case"error":return{...Q,error:J.error,pending:Q.pending.filter((Z)=>Z.turn!==void 0)};case"run-end":return{...Q,runId:void 0,finishReason:J.finishReason,messages:xZ(Q,J.finishReason)};default:return Q}}function I9(Q,J){if(!Q.some(($)=>$.runId===J&&$.finishReason===void 0))return Q;return Q.map(($)=>{if($.runId!==J||$.finishReason!==void 0)return $;let{runId:Z,...W}=$;return{...W,content:[]}})}function xZ(Q,J){return Q.messages.map(($)=>$.role==="assistant"&&Q.runMessageIds.includes($.id)?w9($,J):$)}function w9(Q,J){let $=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?f9(X,J):X)}:W);if(Q.finishReason===void 0)return{...Q,finishReason:J,content:$};return $.some((W,X)=>W!==Q.content[X])?{...Q,content:$}:Q}function f9(Q,J){let $={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((Z)=>Z.id),loadedTools:[]};return{...Q,finishReason:J,messages:xZ($,J)}}function AZ(Q,J,$){for(let Z=Q.messages.length-1;Z>=0;Z--){let W=Q.messages[Z],X=W.content.findIndex((V)=>V.type==="tool-call"&&V.toolCallId===J);if(X===-1)continue;if(W.finishReason!==void 0&&!b9(Q,W,J))return Q;let K=W.content.slice();K[X]=$(K[X]);let G=Q.messages.slice();G[Z]={...W,content:K};let z=Q.runMessageIds.includes(W.id)?Q.runMessageIds:[...Q.runMessageIds,W.id];return{...Q,runMessageIds:z,messages:G}}return Q}function q9(Q,J,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((X)=>X.id),loadedTools:[],finishReason:Q.finishReason},W=jZ(Z,J.event,$);return{...Q,...J.label!==void 0?{label:J.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function b9(Q,J,$){if(J.finishReason!=="awaiting-input")return!1;return!Q.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===$))}function RZ(Q,J){let $=Q.messages.find((Z)=>Z.id===J);return $!==void 0&&$.finishReason!==void 0}function u(Q,J,$,Z){let W=Q.messages.findIndex((G)=>G.id===J),X=Q.runMessageIds.includes(J)?Q.runMessageIds:[...Q.runMessageIds,J];if(W===-1){let G={id:J,role:"assistant",content:[],createdAt:$};return{...Q,runMessageIds:X,messages:[...Q.messages,Z(G)]}}let K=Q.messages.slice();return K[W]=Z(K[W]),{...Q,runMessageIds:X,messages:K}}function v9(Q,J){let $=Q[Q.length-1];if($&&$.type==="text")return[...Q.slice(0,-1),{type:"text",text:$.text+J}];return[...Q,{type:"text",text:J}]}function y9(Q,J,$,Z){let W=Q[Q.length-1];if(W&&W.type==="reasoning"&&W.id===$&&!W.providerMetadata)return[...Q.slice(0,-1),{...W,text:(W.text??"")+J,...Z?{providerMetadata:Z}:{}}];return[...Q,{type:"reasoning",...$?{id:$}:{},text:J,...Z?{providerMetadata:Z}:{}}]}function EZ(Q,J,$){let Z=Q.findIndex($);if(Z===-1)return[...Q,J];let W=Q.slice();return W[Z]=J,W}class cJ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(Q,J,$,Z){this.store=Q;this.threadId=J;this.report=Z;this.state=kZ({messages:$})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[gJ(Q)])}frame(Q){if(this.closed)return;let J=Q.event;if(J.type==="run-start")this.runId=J.runId;switch(this.state=TZ(this.state,Q),J.type){case"message":this.write(()=>[gJ(J.message)]);return;case"tool-call":if(J.part.partial)return;this.checkpoint(J.messageId);return;case"message-start":case"tool-result":this.checkpoint(J.messageId);return;default:return}}close(Q=[]){this.closed=!0;for(let J of Q)this.done.add(J.id)}settled(){return this.chain}checkpoint(Q){if(this.done.has(Q))return;let J=this.state.messages.find((Z)=>Z.id===Q);if(!J)return;let $=this.runId;this.write(()=>{let Z=gJ(J);if(Z.finishReason===void 0&&$)Z.runId=$;return[Z]})}write(Q){let J;try{J=Q()}catch($){this.report($);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,J)).catch(($)=>this.report($))}}function gJ(Q){return structuredClone(Q)}async function IZ(Q,J){let $=[],Z=null,W=Q.slice();for(let X=0;X<W.length;X++){let K=W[X];if(K.role!=="assistant"||K.finishReason!==void 0)continue;if(K.runId&&await J(K.runId))continue;Z??=new Set(Q.flatMap((V)=>V.content.flatMap((Y)=>Y.type==="tool-result"?[Y.toolCallId]:[])));let G=K.content.map((V)=>V.type==="tool-call"?wZ(V):V);for(let V of K.content){if(V.type!=="tool-call"||Z.has(V.toolCallId))continue;let Y={type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"interrupted"};G.push(Y)}let z={...K,content:G,finishReason:"interrupted"};W[X]=z,$.push(z)}return{messages:W,settled:$}}function wZ(Q){let{partial:J,...$}=Q;if(!$.nested?.some((Z)=>Z.finishReason===void 0))return $;return{...$,nested:$.nested.map(h9)}}function h9(Q){if(Q.finishReason!==void 0)return Q;return{...Q,finishReason:"interrupted",messages:Q.messages.map((J)=>J.role==="assistant"&&J.finishReason===void 0?{...J,finishReason:"interrupted",content:J.content.map(($)=>$.type==="tool-call"?wZ($):$)}:J)}}var g9=50,c9=["waiting","running","ok","error"];async function bZ(Q,J){let{store:$,threadId:Z}=J,W=Math.max(g9,J.scan??0),X=await $.listForThread(Z,{limit:W}),K,G=async(H)=>{if(H.state!=="running")return H;if(K??=await fZ($),H.deadlineAt>K)return H;return await qZ($,H),await $.get(H.id)??H};for(let H=0;H<X.length;H++)X[H]=await G(X[H]);let z=new Map(X.map((H)=>[H.id,H])),V=Q.slice(),Y=[],D=new Set;for(let H=0;H<V.length;H++){let U=V[H],_=null;for(let P=0;P<U.content.length;P++){let C=U.content[P];if(C.type==="tool-call")D.add(C.toolCallId);if(C.type!=="tool-result"||C.status!=="running")continue;let F=C.job?.id,L=F?z.get(F):void 0;if(F&&L===void 0){let R=await $.get(F);if(L=R?await G(R):void 0,L)z.set(F,L)}if(L&&!g(L.state))continue;_??=U.content.slice(),_[P]=u9(C,L,J.outputSchemaFor,J.modelOutputFor)}if(_){let P={...U,content:_};V[H]=P,Y.push(P)}}let N=[];for(let H of X){if(H.orphaned||H.toolCallId===""||D.has(H.toolCallId))continue;if(await J.isRunLive(H.runId))continue;N.push(H)}return{messages:V,settled:Y,orphans:N,jobs:X}}async function vZ(Q,J,$){for(let Z of J)try{await Q.transition(Z.id,c9,{orphaned:!0})}catch(W){$(W)}}function u9(Q,J,$,Z){let W={type:"tool-result",toolCallId:Q.toolCallId,name:Q.name},X=(z,V)=>{let Y=Z?.(String(Q.name),z);return{...W,status:"ok",job:V,output:z,...Y!==void 0?{modelOutput:Y}:{}}};if(!J)return{...W,status:"error",job:Q.job,error:{code:"tool_error",message:`The background job for "${String(Q.name)}" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,toolCallId:Q.toolCallId,retryable:!0}};let K={id:J.id,...J.summary!==void 0?{summary:J.summary}:{},...J.usage?{usage:J.usage}:{}};if(J.state==="error")return{...W,status:"error",job:K,error:J.error??{code:"tool_error",message:`The background job for "${String(Q.name)}" failed.`,toolCallId:Q.toolCallId,retryable:!0}};let G=$?.(String(Q.name));if(G){let z=G.safeParse(J.output);if(z.ok===!1)return{...W,status:"error",job:K,error:{code:"invalid_tool_result",message:`The background job for "${String(Q.name)}" finished with an output that does not match the tool's output schema: ${z.errors.join(", ")}`,toolCallId:Q.toolCallId,retryable:!0}};return X(z.value,K)}return X(J.output,K)}var m9=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;class YQ extends Error{status;code;kind;constructor(Q,J){super(Q);this.name="AgentTurnError",this.status=J.status,this.code=J.code,this.kind=J.kind}static async from(Q){let J={};try{let Z=await Q.json();if(Z?.error&&typeof Z.error==="object")J=Z.error}catch{}let $=(Z)=>typeof J[Z]==="string"?J[Z]:void 0;return new YQ($("message")??`The agent turn was refused with status ${Q.status}.`,{status:Q.status,code:$("code"),kind:$("kind")})}}function p9(Q){for(let J=Q.length-1;J>=0;J--){let $=Q[J];if($.role!=="assistant")continue;return $.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}function oJ(Q,J,$,Z=!1){let W=[],X=(async()=>{for await(let G of J)if(G.type==="awaiting-input")W=G.pending})().catch(T),K;return{runId:J.runId,threadId:Q,run:J,joined:Z,stop:(G)=>EQ(J,G),result:()=>K??=(async()=>{let G=await J.result();await Promise.all([$,X]);let z=G.messages;return{...G,threadId:Q,text:p9(z),pending:G.finishReason==="awaiting-input"?W:[]}})()}}function l9(Q,J){let $=oJ(Q,J.run,t.get(J.run)??J.run.result().then(T,T),!0),Z;return{...$,stop:(W)=>{EQ(J.run,W),J.answer.then((X)=>{if("run"in X)EQ(X.run,W)},T)},result:()=>Z??=(async()=>{let W=await J.answer;if(W.kind==="refused")throw await $.result(),W.error;if(W.kind==="dropped"||W.run===J.run)return $.result();return oJ(Q,W.run,W.hooks).result()})()}}var yZ=["supersede","queue","join","parallel","skip"];function i9(Q,J){if(J)return{event:{name:J.name,...J.text!==void 0?{text:J.text}:{},...J.data!==void 0?{data:J.data}:{}}};if(!Q||Q.toolResults&&Q.toolResults.length>0)return null;if(!Q.text&&!(Q.files&&Q.files.length>0))return null;return{...Q.text?{text:Q.text}:{},...Q.files&&Q.files.length>0?{files:Q.files}:{},...Q.localId?{localId:Q.localId}:{}}}function hZ(Q){if(!Q)return{};let J="event"in Q?Q.event:void 0,$=J?J.text:Q.text;return{...$?{text:$}:{},...!J&&Q.files&&Q.files.length>0?{files:Q.files}:{},...J?{event:{name:J.name}}:{}}}var d9=["supersede","queue","join","parallel"],n9=K8,SQ=new Map,t=new WeakMap,y=new WeakMap,gZ=new WeakMap,cZ=new WeakMap;function o9(Q){return Q.headers.get("Content-Type")?.startsWith("text/event-stream")??!1}var uJ=new WeakMap,mJ=new WeakMap,uZ=new WeakMap,mZ=new WeakMap,pJ={parallel:!1},s9=5000,pZ=new WeakMap,lJ=new WeakMap,lZ=new WeakMap,sJ=new WeakSet;function EQ(Q,J){sJ.add(Q),Q.stop(J)}function iZ(Q,J){let $=pZ.get(Q);if($)return $;let Z=(async()=>{for await(let X of Q.frames()){let K=X.event.type;if(K==="message-start"||K==="awaiting-input"||K==="run-end")return}})().catch(T),W={done:!1,promise:Promise.resolve()};return W.promise=Promise.race([Z,Q.result().then(T,T)]).then(()=>J?.settled()).then(T,T).then(()=>{W.done=!0}),pZ.set(Q,W),W}var MQ=new WeakMap,E8="thread_busy",dZ="http://gemi.internal/__gemi/agent-turn",nQ=new Map,a9=4194304,t9=1000,r9=5;function e9(Q){let{max:J,overflow:$}=typeof Q==="number"?{max:Q,overflow:"reject"}:Q??{};if(!(J===1/0||Number.isInteger(J)&&J>0)||$!=="queue"&&$!=="reject")throw TypeError(`AgentController.maxThreadRuns answers a positive whole number (or Infinity), or { max, overflow: "queue" | "reject" }; got ${JSON.stringify(Q)}.`);return{max:J,overflow:$}}var Q6=3,AQ=65536,T=()=>{};class k8{byKey=new Map;take(Q,J,$){let Z=this.byKey.get(Q);if(!Z?.has(J)&&(Z?.size??0)>=$)return null;if(!Z)Z=new Map,this.byKey.set(Q,Z);Z.set(J,(Z.get(J)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let X=this.byKey.get(Q),K=(X?.get(J)??1)-1;if(!X)return;if(K>0)X.set(J,K);else if(X.delete(J),X.size===0)this.byKey.delete(Q)}}}var nZ=new WeakMap,aJ=new WeakMap;function J6(Q){let J=aJ.get(Q);if(!J)J=new Map,aJ.set(Q,J);return J}function $6(Q,J,$){let Z=aJ.get(Q)?.get(J);if(!Z)return;for(let W of[...Z])try{W($)}catch{}}function oZ(Q){let J=nZ.get(Q);if(!J)J=new k8,nZ.set(Q,J);return J}function Z6(Q){return Q}class tQ extends n9{static kind="agent-controller";hooks;store=hJ;storeScope(Q,J){return null}boundScope=void 0;async threadInScope(Q,J){if(await this.scopeStore(Q,{}),this.boundScope===null)return!0;return await this.store.loadThread(J)!==null}async scopeStore(Q,J){let Z=gZ.get(Q)??await this.storeScope(Q,{body:J})??null;if(this.boundScope!==void 0){if(this.boundScope!==Z)throw Error("This AgentController instance already served a request in another store scope. Build a controller per request (the router and startTurn do).");return}if(Z!==null)this.store=W8(this.store,Z);this.boundScope=Z}liveRuns=IJ;voice;voiceStore=TJ;attachments=JJ;attachmentStorage=z8;turnAttachmentMaxAgeMs=3600000;fileOwners=wJ;nonces=J$;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(Q,J){return this.hooks?.instructions?.(Q,J)}reasoning(Q,J){return this.hooks?.reasoning?.(Q,J)}skills(Q,J){return this.hooks?.skills?.(Q,J)}runTools(Q,J){return this.hooks?.runTools?.(Q,J)}trailingContext(Q,J){return this.hooks?.trailingContext?.(Q,J)}usageLimits(Q,J){return this.hooks?.usageLimits?.(Q,J)}context(Q,J){let $=this.hooks?.context;if($)return $(Q,J);return{}}memoryScopes(Q,J){let $=this.hooks?.memoryScopes;if($)return $(Q,J);return{}}memoryMaxTokens=void 0;requireThread=!1;maxBodyBytes=a9;maxHistoryMessages=t9;contextWindow=void 0;prepareStep(Q,J){return this.hooks?.prepareStep?.(Q,J)}maxConcurrentRuns=r9;maxThreadRuns(Q,J){let $=this.hooks?.maxThreadRuns;if($)return $(Q,J);return Q6}busyPolicy(Q,J){let $=this.hooks?.busyPolicy;if($)return $(Q,J);return J.requested??"supersede"}runLimitKey(Q,J){let $=this.hooks?.runLimitKey;if($)return $(Q,J);return J.owner}authorizeRequest(Q,J){let $=this.hooks?.authorizeRequest;if($)return $(Q,J);return this.resource?.authorize(Q,J)}resource;runOwner(Q){let J=this.hooks?.runOwner;if(J)return J(Q);let $=Q.ctx?.()?.user,Z=$?.id??$?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(Q){let{threadId:J}=Q;if(typeof J!=="string"||J==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let $=Q.ifBusy;if($!==void 0&&!yZ.includes($))throw TypeError(`AgentController.startTurn's \`ifBusy\` is "supersede", "queue", "join", "parallel" or "skip"; got ${JSON.stringify(Q.ifBusy)}.`);let Z=Q.event===void 0?void 0:F6(Q),W={...Q.turn,...Q.text!==void 0?{text:Q.text}:{}},X={...Q.body,threadId:J,turn:W},K=new w(new Request(dZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}),{},"api",new URL(dZ).pathname),G=new this;if(y.set(K,null),Q.scope!==void 0)gZ.set(K,Q.scope);if($!==void 0)cZ.set(K,$);if(Z)MQ.set(K,Z);let z=await n.run(K,()=>G.stream(K),{user:Q.user??null}),V=lJ.get(K),Y=y.get(K);if(!Y&&!V){let H=await YQ.from(z);if($==="skip"&&H.code===E8)return{skipped:!0,threadId:J};throw H}if(y.delete(K),lJ.delete(K),z.body?.cancel().catch(T),V)return l9(J,V);let{run:D,hooks:N}=Y;return oJ(J,D,N)}async stream(Q=new w){let J=await zQ(Q,this.maxBodyBytes);if(J.error)return m(J);let $=J.body,Z=typeof $.threadId==="string"?$.threadId:void 0,W=D6($);if(W.error)return m({body:{},error:W.error});let X=W.turn,K=Z!==void 0&&$.regenerate===!0,G=typeof $.clientRunId==="string"?$.clientRunId:void 0,z=cZ.get(Q);if(!y.has(Q)&&$.ifBusy!==void 0){if(!d9.includes($.ifBusy))return m({body:{},error:`\`ifBusy\` is "supersede", "queue", "join" or "parallel"; got ${JSON.stringify($.ifBusy)}.`});z=$.ifBusy}let V=aQ($);if(this.requireThread&&!Z)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(await this.scopeStore(Q,V),K&&!this.store.removeMessages)return M(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!Z&&Array.isArray($.messages)&&$.messages.length>this.maxHistoryMessages)return RQ(413,"history_too_long",`The conversation has ${$.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(Q),D=G?{cancelled:!1,owner:Y}:null;if(D)nQ.set(G,D);let N=null,H=[],U=async(P=pJ)=>{try{return await _(P)}finally{if(Z&&H.length>0&&N===null)await this.store.appendMessages(Z,H).catch((C)=>this.reportHookFailure(C));if(P.release&&N===null)P.release()}},_=async(P)=>{let C,F=null;if(Z){let E=await this.store.loadThread(Z);if(!E)return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let JQ=await this.settleThread(Z,E,{write:!0});if(C=JQ.messages.filter((b)=>!(b.role==="assistant"&&b.finishReason===void 0&&b.runId&&this.liveRuns.isRunning(b.runId))),F=this.jobsBlock(JQ.jobs),K){let b=N6(C);if(!b)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});H=C.slice(b.index),await this.store.removeMessages(Z,H.map((f8)=>f8.id)),C=C.slice(0,b.index),X=X?.localId?{...b.turn,localId:X.localId}:b.turn}}else C=Array.isArray($.messages)?$.messages:[],M6(this.nonces);let L=[await this.instructions(Q,{body:V})||void 0,F??void 0].filter(Boolean).join(`
|
|
334
|
+
`))}catch{return null}let W=J===void 0||J===""?Number.NaN:Number(J),X=Number.isFinite(W)?W:this.lastSeq+1;return this.lastSeq=X,{seq:X,event:Z}}}async function*MZ(Q){if(!Q)return;let J=Q.getReader(),$=new SZ;try{while(!0){let{done:Z,value:W}=await J.read();if(Z){yield*$.flush();return}if(W)yield*$.push(W)}}finally{try{await J.cancel()}catch{}}}function kZ(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 T9(Q){let J=new Map;for(let $ of Q)for(let Z of $.content)if(Z.type==="tool-call")J.set(Z.toolCallId,$.turn);return J}var j9=(Q)=>Q.path?.[0]??Q.toolCallId;function x9(Q,J,$){if(J.length===0)return[];let Z=T9(Q),W=(G)=>G.turn??Z.get(j9(G)),X=new Set($.map(W));if(X.has(void 0)||X.size===0)return[];let K=new Set($.map((G)=>G.toolCallId));return J.filter((G)=>{let z=W(G);return z!==void 0&&!X.has(z)&&!K.has(G.toolCallId)})}function TZ(Q,J,$=new Date().toISOString()){if(!(J.event.type==="run-start"&&J.event.runId!==Q.cursorRunId)&&J.seq<=Q.seq)return Q;return{...jZ(Q,J.event,$),seq:J.seq}}function jZ(Q,J,$){switch(J.type){case"run-start":return{...Q,messages:I9(Q.messages,J.runId),runId:J.runId,cursorRunId:J.runId,threadId:J.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return u(Q,J.messageId,$,(Z)=>({...Z,role:J.role,...J.turn&&Z.turn===void 0?{turn:J.turn}:{}}));case"text-delta":if(RZ(Q,J.messageId))return Q;return u(Q,J.messageId,$,(Z)=>({...Z,content:v9(Z.content,J.delta)}));case"reasoning-delta":if(RZ(Q,J.messageId))return Q;return u(Q,J.messageId,$,(Z)=>({...Z,content:y9(Z.content,J.delta,J.id,J.providerMetadata)}));case"output-delta":return u(Q,J.messageId,$,(Z)=>({...Z,content:EZ(Z.content,{type:"output",value:J.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return u(Q,J.messageId,$,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===J.part.toolCallId),X=W===-1?void 0:Z.content[W],K=J.part.progress??X?.progress,G=J.part.nested??X?.nested,z=J.part.attachments??X?.attachments,V={...J.part,...K?{progress:K}:{},...G?{nested:G}:{},...z?{attachments:z}:{}},Y=Z.content.slice();if(W===-1)Y.push(V);else Y[W]=V;return{...Z,content:Y}});case"tool-call-discard":return u(Q,J.messageId,$,(Z)=>{let W=Z.content.filter((X)=>!(X.type==="tool-call"&&X.partial&&J.toolCallIds.includes(X.toolCallId)));return W.length===Z.content.length?Z:{...Z,content:W}});case"tool-search":{let Z=J.loaded.filter((W)=>!Q.loadedTools.includes(W));if(Z.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...Z]}}case"tool-progress":return AZ(Q,J.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],J.data]}));case"nested-event":{let Z=J;return AZ(Q,J.toolCallId,(W)=>{let X=W.nested??[],K=X.findIndex((Y)=>Y.runId===Z.runId),G=X[K]??{runId:Z.runId,agent:Z.agent,messages:[]},z=q9(G,Z,$),V=K===-1?[...X,z]:X.map((Y,D)=>D===K?z:Y);return{...W,nested:V}})}case"tool-result":{let Z=u(Q,J.messageId,$,(W)=>({...W,content:EZ(W.content,J.part,(X)=>X.type==="tool-result"&&X.toolCallId===J.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==J.part.toolCallId)}}case"message":{let Z=Q.messages.findIndex((K)=>K.id===J.message.id),W=Q.messages.slice();if(Z===-1)W.push(J.message);else W[Z]=J.message;let X=Q.runMessageIds.includes(J.message.id)?Q.runMessageIds:[...Q.runMessageIds,J.message.id];return{...Q,messages:W,runMessageIds:X}}case"message-id":{let Z=Q.messages.findIndex((G)=>G.id===J.localId);if(Z===-1){if(!J.message||Q.messages.some((G)=>G.id===J.messageId))return Q;return{...Q,messages:[...Q.messages,J.message]}}let W=Q.messages[Z],X={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},K=Q.messages.some((G)=>G.id===J.messageId)?Q.messages.filter((G,z)=>z!==Z).map((G)=>G.id===J.messageId?{...G,...X}:G):Q.messages.map((G,z)=>z===Z?{...G,...X,id:J.messageId}:G);return{...Q,messages:K}}case"awaiting-input":return{...Q,runId:J.runId,pending:[...x9(Q.messages,Q.pending,J.pending),...J.pending]};case"message-end":return u(Q,J.messageId,$,(Z)=>({...Z,finishReason:J.finishReason,...J.outputTruncated?{outputTruncated:!0}:{},...J.usage?{usage:J.usage}:{},content:J.outputTruncated||J.finishReason==="length"?Z.content.filter((W)=>!(W.type==="output"&&W.partial)):Z.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...Q,usage:J.usage};case"retry":return Q;case"error":return{...Q,error:J.error,pending:Q.pending.filter((Z)=>Z.turn!==void 0)};case"run-end":return{...Q,runId:void 0,finishReason:J.finishReason,messages:xZ(Q,J.finishReason)};default:return Q}}function I9(Q,J){if(!Q.some(($)=>$.runId===J&&$.finishReason===void 0))return Q;return Q.map(($)=>{if($.runId!==J||$.finishReason!==void 0)return $;let{runId:Z,...W}=$;return{...W,content:[]}})}function xZ(Q,J){return Q.messages.map(($)=>$.role==="assistant"&&Q.runMessageIds.includes($.id)?w9($,J):$)}function w9(Q,J){let $=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?f9(X,J):X)}:W);if(Q.finishReason===void 0)return{...Q,finishReason:J,content:$};return $.some((W,X)=>W!==Q.content[X])?{...Q,content:$}:Q}function f9(Q,J){let $={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((Z)=>Z.id),loadedTools:[]};return{...Q,finishReason:J,messages:xZ($,J)}}function AZ(Q,J,$){for(let Z=Q.messages.length-1;Z>=0;Z--){let W=Q.messages[Z],X=W.content.findIndex((V)=>V.type==="tool-call"&&V.toolCallId===J);if(X===-1)continue;if(W.finishReason!==void 0&&!b9(Q,W,J))return Q;let K=W.content.slice();K[X]=$(K[X]);let G=Q.messages.slice();G[Z]={...W,content:K};let z=Q.runMessageIds.includes(W.id)?Q.runMessageIds:[...Q.runMessageIds,W.id];return{...Q,runMessageIds:z,messages:G}}return Q}function q9(Q,J,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((X)=>X.id),loadedTools:[],finishReason:Q.finishReason},W=jZ(Z,J.event,$);return{...Q,...J.label!==void 0?{label:J.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function b9(Q,J,$){if(J.finishReason!=="awaiting-input")return!1;return!Q.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===$))}function RZ(Q,J){let $=Q.messages.find((Z)=>Z.id===J);return $!==void 0&&$.finishReason!==void 0}function u(Q,J,$,Z){let W=Q.messages.findIndex((G)=>G.id===J),X=Q.runMessageIds.includes(J)?Q.runMessageIds:[...Q.runMessageIds,J];if(W===-1){let G={id:J,role:"assistant",content:[],createdAt:$};return{...Q,runMessageIds:X,messages:[...Q.messages,Z(G)]}}let K=Q.messages.slice();return K[W]=Z(K[W]),{...Q,runMessageIds:X,messages:K}}function v9(Q,J){let $=Q[Q.length-1];if($&&$.type==="text")return[...Q.slice(0,-1),{type:"text",text:$.text+J}];return[...Q,{type:"text",text:J}]}function y9(Q,J,$,Z){let W=Q[Q.length-1];if(W&&W.type==="reasoning"&&W.id===$&&!W.providerMetadata)return[...Q.slice(0,-1),{...W,text:(W.text??"")+J,...Z?{providerMetadata:Z}:{}}];return[...Q,{type:"reasoning",...$?{id:$}:{},text:J,...Z?{providerMetadata:Z}:{}}]}function EZ(Q,J,$){let Z=Q.findIndex($);if(Z===-1)return[...Q,J];let W=Q.slice();return W[Z]=J,W}class cJ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(Q,J,$,Z){this.store=Q;this.threadId=J;this.report=Z;this.state=kZ({messages:$})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[gJ(Q)])}frame(Q){if(this.closed)return;let J=Q.event;if(J.type==="run-start")this.runId=J.runId;switch(this.state=TZ(this.state,Q),J.type){case"message":this.write(()=>[gJ(J.message)]);return;case"tool-call":if(J.part.partial)return;this.checkpoint(J.messageId);return;case"message-start":case"tool-result":this.checkpoint(J.messageId);return;default:return}}close(Q=[]){this.closed=!0;for(let J of Q)this.done.add(J.id)}settled(){return this.chain}checkpoint(Q){if(this.done.has(Q))return;let J=this.state.messages.find((Z)=>Z.id===Q);if(!J)return;let $=this.runId;this.write(()=>{let Z=gJ(J);if(Z.finishReason===void 0&&$)Z.runId=$;return[Z]})}write(Q){let J;try{J=Q()}catch($){this.report($);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,J)).catch(($)=>this.report($))}}function gJ(Q){return structuredClone(Q)}async function IZ(Q,J){let $=[],Z=null,W=Q.slice();for(let X=0;X<W.length;X++){let K=W[X];if(K.role!=="assistant"||K.finishReason!==void 0)continue;if(K.runId&&await J(K.runId))continue;Z??=new Set(Q.flatMap((V)=>V.content.flatMap((Y)=>Y.type==="tool-result"?[Y.toolCallId]:[])));let G=K.content.map((V)=>V.type==="tool-call"?wZ(V):V);for(let V of K.content){if(V.type!=="tool-call"||Z.has(V.toolCallId))continue;let Y={type:"tool-result",toolCallId:V.toolCallId,name:V.name,status:"denied",cause:"interrupted"};G.push(Y)}let z={...K,content:G,finishReason:"interrupted"};W[X]=z,$.push(z)}return{messages:W,settled:$}}function wZ(Q){let{partial:J,...$}=Q;if(!$.nested?.some((Z)=>Z.finishReason===void 0))return $;return{...$,nested:$.nested.map(h9)}}function h9(Q){if(Q.finishReason!==void 0)return Q;return{...Q,finishReason:"interrupted",messages:Q.messages.map((J)=>J.role==="assistant"&&J.finishReason===void 0?{...J,finishReason:"interrupted",content:J.content.map(($)=>$.type==="tool-call"?wZ($):$)}:J)}}var g9=50,c9=["waiting","running","ok","error"];async function bZ(Q,J){let{store:$,threadId:Z}=J,W=Math.max(g9,J.scan??0),X=await $.listForThread(Z,{limit:W}),K,G=async(H)=>{if(H.state!=="running")return H;if(K??=await fZ($),H.deadlineAt>K)return H;return await qZ($,H),await $.get(H.id)??H};for(let H=0;H<X.length;H++)X[H]=await G(X[H]);let z=new Map(X.map((H)=>[H.id,H])),V=Q.slice(),Y=[],D=new Set;for(let H=0;H<V.length;H++){let U=V[H],_=null;for(let P=0;P<U.content.length;P++){let C=U.content[P];if(C.type==="tool-call")D.add(C.toolCallId);if(C.type!=="tool-result"||C.status!=="running")continue;let F=C.job?.id,O=F?z.get(F):void 0;if(F&&O===void 0){let R=await $.get(F);if(O=R?await G(R):void 0,O)z.set(F,O)}if(O&&!g(O.state))continue;_??=U.content.slice(),_[P]=u9(C,O,J.outputSchemaFor,J.modelOutputFor)}if(_){let P={...U,content:_};V[H]=P,Y.push(P)}}let N=[];for(let H of X){if(H.orphaned||H.toolCallId===""||D.has(H.toolCallId))continue;if(await J.isRunLive(H.runId))continue;N.push(H)}return{messages:V,settled:Y,orphans:N,jobs:X}}async function vZ(Q,J,$){for(let Z of J)try{await Q.transition(Z.id,c9,{orphaned:!0})}catch(W){$(W)}}function u9(Q,J,$,Z){let W={type:"tool-result",toolCallId:Q.toolCallId,name:Q.name},X=(z,V)=>{let Y=Z?.(String(Q.name),z);return{...W,status:"ok",job:V,output:z,...Y!==void 0?{modelOutput:Y}:{}}};if(!J)return{...W,status:"error",job:Q.job,error:{code:"tool_error",message:`The background job for "${String(Q.name)}" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,toolCallId:Q.toolCallId,retryable:!0}};let K={id:J.id,...J.summary!==void 0?{summary:J.summary}:{},...J.usage?{usage:J.usage}:{}};if(J.state==="error")return{...W,status:"error",job:K,error:J.error??{code:"tool_error",message:`The background job for "${String(Q.name)}" failed.`,toolCallId:Q.toolCallId,retryable:!0}};let G=$?.(String(Q.name));if(G){let z=G.safeParse(J.output);if(z.ok===!1)return{...W,status:"error",job:K,error:{code:"invalid_tool_result",message:`The background job for "${String(Q.name)}" finished with an output that does not match the tool's output schema: ${z.errors.join(", ")}`,toolCallId:Q.toolCallId,retryable:!0}};return X(z.value,K)}return X(J.output,K)}var m9=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;class YQ extends Error{status;code;kind;constructor(Q,J){super(Q);this.name="AgentTurnError",this.status=J.status,this.code=J.code,this.kind=J.kind}static async from(Q){let J={};try{let Z=await Q.json();if(Z?.error&&typeof Z.error==="object")J=Z.error}catch{}let $=(Z)=>typeof J[Z]==="string"?J[Z]:void 0;return new YQ($("message")??`The agent turn was refused with status ${Q.status}.`,{status:Q.status,code:$("code"),kind:$("kind")})}}function p9(Q){for(let J=Q.length-1;J>=0;J--){let $=Q[J];if($.role!=="assistant")continue;return $.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}function oJ(Q,J,$,Z=!1){let W=[],X=(async()=>{for await(let G of J)if(G.type==="awaiting-input")W=G.pending})().catch(T),K;return{runId:J.runId,threadId:Q,run:J,joined:Z,stop:(G)=>EQ(J,G),result:()=>K??=(async()=>{let G=await J.result();await Promise.all([$,X]);let z=G.messages;return{...G,threadId:Q,text:p9(z),pending:G.finishReason==="awaiting-input"?W:[]}})()}}function l9(Q,J){let $=oJ(Q,J.run,t.get(J.run)??J.run.result().then(T,T),!0),Z;return{...$,stop:(W)=>{EQ(J.run,W),J.answer.then((X)=>{if("run"in X)EQ(X.run,W)},T)},result:()=>Z??=(async()=>{let W=await J.answer;if(W.kind==="refused")throw await $.result(),W.error;if(W.kind==="dropped"||W.run===J.run)return $.result();return oJ(Q,W.run,W.hooks).result()})()}}var yZ=["supersede","queue","join","parallel","skip"];function i9(Q,J){if(J)return{event:{name:J.name,...J.text!==void 0?{text:J.text}:{},...J.data!==void 0?{data:J.data}:{}}};if(!Q||Q.toolResults&&Q.toolResults.length>0)return null;if(!Q.text&&!(Q.files&&Q.files.length>0))return null;return{...Q.text?{text:Q.text}:{},...Q.files&&Q.files.length>0?{files:Q.files}:{},...Q.localId?{localId:Q.localId}:{}}}function hZ(Q){if(!Q)return{};let J="event"in Q?Q.event:void 0,$=J?J.text:Q.text;return{...$?{text:$}:{},...!J&&Q.files&&Q.files.length>0?{files:Q.files}:{},...J?{event:{name:J.name}}:{}}}var d9=["supersede","queue","join","parallel"],n9=K8,SQ=new Map,t=new WeakMap,y=new WeakMap,gZ=new WeakMap,cZ=new WeakMap;function o9(Q){return Q.headers.get("Content-Type")?.startsWith("text/event-stream")??!1}var uJ=new WeakMap,mJ=new WeakMap,uZ=new WeakMap,mZ=new WeakMap,pJ={parallel:!1},s9=5000,pZ=new WeakMap,lJ=new WeakMap,lZ=new WeakMap,sJ=new WeakSet;function EQ(Q,J){sJ.add(Q),Q.stop(J)}function iZ(Q,J){let $=pZ.get(Q);if($)return $;let Z=(async()=>{for await(let X of Q.frames()){let K=X.event.type;if(K==="message-start"||K==="awaiting-input"||K==="run-end")return}})().catch(T),W={done:!1,promise:Promise.resolve()};return W.promise=Promise.race([Z,Q.result().then(T,T)]).then(()=>J?.settled()).then(T,T).then(()=>{W.done=!0}),pZ.set(Q,W),W}var MQ=new WeakMap,E8="thread_busy",dZ="http://gemi.internal/__gemi/agent-turn",nQ=new Map,a9=4194304,t9=1000,r9=5;function e9(Q){let{max:J,overflow:$}=typeof Q==="number"?{max:Q,overflow:"reject"}:Q??{};if(!(J===1/0||Number.isInteger(J)&&J>0)||$!=="queue"&&$!=="reject")throw TypeError(`AgentController.maxThreadRuns answers a positive whole number (or Infinity), or { max, overflow: "queue" | "reject" }; got ${JSON.stringify(Q)}.`);return{max:J,overflow:$}}var Q6=3,AQ=65536,T=()=>{};class k8{byKey=new Map;take(Q,J,$){let Z=this.byKey.get(Q);if(!Z?.has(J)&&(Z?.size??0)>=$)return null;if(!Z)Z=new Map,this.byKey.set(Q,Z);Z.set(J,(Z.get(J)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let X=this.byKey.get(Q),K=(X?.get(J)??1)-1;if(!X)return;if(K>0)X.set(J,K);else if(X.delete(J),X.size===0)this.byKey.delete(Q)}}}var nZ=new WeakMap,aJ=new WeakMap;function J6(Q){let J=aJ.get(Q);if(!J)J=new Map,aJ.set(Q,J);return J}function $6(Q,J,$){let Z=aJ.get(Q)?.get(J);if(!Z)return;for(let W of[...Z])try{W($)}catch{}}function oZ(Q){let J=nZ.get(Q);if(!J)J=new k8,nZ.set(Q,J);return J}function Z6(Q){return Q}class tQ extends n9{static kind="agent-controller";hooks;store=hJ;storeScope(Q,J){return null}boundScope=void 0;async threadInScope(Q,J){if(await this.scopeStore(Q,{}),this.boundScope===null)return!0;return await this.store.loadThread(J)!==null}async scopeStore(Q,J){let Z=gZ.get(Q)??await this.storeScope(Q,{body:J})??null;if(this.boundScope!==void 0){if(this.boundScope!==Z)throw Error("This AgentController instance already served a request in another store scope. Build a controller per request (the router and startTurn do).");return}if(Z!==null)this.store=W8(this.store,Z);this.boundScope=Z}liveRuns=IJ;voice;voiceStore=TJ;attachments=JJ;attachmentStorage=z8;turnAttachmentMaxAgeMs=3600000;fileOwners=wJ;nonces=J$;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(Q,J){return this.hooks?.instructions?.(Q,J)}reasoning(Q,J){return this.hooks?.reasoning?.(Q,J)}skills(Q,J){return this.hooks?.skills?.(Q,J)}runTools(Q,J){return this.hooks?.runTools?.(Q,J)}trailingContext(Q,J){return this.hooks?.trailingContext?.(Q,J)}usageLimits(Q,J){return this.hooks?.usageLimits?.(Q,J)}context(Q,J){let $=this.hooks?.context;if($)return $(Q,J);return{}}memoryScopes(Q,J){let $=this.hooks?.memoryScopes;if($)return $(Q,J);return{}}memoryMaxTokens=void 0;requireThread=!1;maxBodyBytes=a9;maxHistoryMessages=t9;contextWindow=void 0;prepareStep(Q,J){return this.hooks?.prepareStep?.(Q,J)}maxConcurrentRuns=r9;maxThreadRuns(Q,J){let $=this.hooks?.maxThreadRuns;if($)return $(Q,J);return Q6}busyPolicy(Q,J){let $=this.hooks?.busyPolicy;if($)return $(Q,J);return J.requested??"supersede"}runLimitKey(Q,J){let $=this.hooks?.runLimitKey;if($)return $(Q,J);return J.owner}authorizeRequest(Q,J){let $=this.hooks?.authorizeRequest;if($)return $(Q,J);return this.resource?.authorize(Q,J)}resource;runOwner(Q){let J=this.hooks?.runOwner;if(J)return J(Q);let $=Q.ctx?.()?.user,Z=$?.id??$?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(Q){let{threadId:J}=Q;if(typeof J!=="string"||J==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let $=Q.ifBusy;if($!==void 0&&!yZ.includes($))throw TypeError(`AgentController.startTurn's \`ifBusy\` is "supersede", "queue", "join", "parallel" or "skip"; got ${JSON.stringify(Q.ifBusy)}.`);let Z=Q.event===void 0?void 0:F6(Q),W={...Q.turn,...Q.text!==void 0?{text:Q.text}:{}},X={...Q.body,threadId:J,turn:W},K=new w(new Request(dZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}),{},"api",new URL(dZ).pathname),G=new this;if(y.set(K,null),Q.scope!==void 0)gZ.set(K,Q.scope);if($!==void 0)cZ.set(K,$);if(Z)MQ.set(K,Z);let z=await n.run(K,()=>G.stream(K),{user:Q.user??null}),V=lJ.get(K),Y=y.get(K);if(!Y&&!V){let H=await YQ.from(z);if($==="skip"&&H.code===E8)return{skipped:!0,threadId:J};throw H}if(y.delete(K),lJ.delete(K),z.body?.cancel().catch(T),V)return l9(J,V);let{run:D,hooks:N}=Y;return oJ(J,D,N)}async stream(Q=new w){let J=await zQ(Q,this.maxBodyBytes);if(J.error)return m(J);let $=J.body,Z=typeof $.threadId==="string"?$.threadId:void 0,W=D6($);if(W.error)return m({body:{},error:W.error});let X=W.turn,K=Z!==void 0&&$.regenerate===!0,G=typeof $.clientRunId==="string"?$.clientRunId:void 0,z=cZ.get(Q);if(!y.has(Q)&&$.ifBusy!==void 0){if(!d9.includes($.ifBusy))return m({body:{},error:`\`ifBusy\` is "supersede", "queue", "join" or "parallel"; got ${JSON.stringify($.ifBusy)}.`});z=$.ifBusy}let V=aQ($);if(this.requireThread&&!Z)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(await this.scopeStore(Q,V),K&&!this.store.removeMessages)return M(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!Z&&Array.isArray($.messages)&&$.messages.length>this.maxHistoryMessages)return RQ(413,"history_too_long",`The conversation has ${$.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(Q),D=G?{cancelled:!1,owner:Y}:null;if(D)nQ.set(G,D);let N=null,H=[],U=async(P=pJ)=>{try{return await _(P)}finally{if(Z&&H.length>0&&N===null)await this.store.appendMessages(Z,H).catch((C)=>this.reportHookFailure(C));if(P.release&&N===null)P.release()}},_=async(P)=>{let C,F=null;if(Z){let E=await this.store.loadThread(Z);if(!E)return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let JQ=await this.settleThread(Z,E,{write:!0});if(C=JQ.messages.filter((b)=>!(b.role==="assistant"&&b.finishReason===void 0&&b.runId&&this.liveRuns.isRunning(b.runId))),F=this.jobsBlock(JQ.jobs),K){let b=N6(C);if(!b)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});H=C.slice(b.index),await this.store.removeMessages(Z,H.map((f8)=>f8.id)),C=C.slice(0,b.index),X=X?.localId?{...b.turn,localId:X.localId}:b.turn}}else C=Array.isArray($.messages)?$.messages:[],M6(this.nonces);let O=[await this.instructions(Q,{body:V})||void 0,F??void 0].filter(Boolean).join(`
|
|
335
335
|
|
|
336
|
-
`)||void 0,R=await this.context(Q,{body:V}),f=await this.reasoning(Q,{body:V})||void 0,x=await this.skills(Q,{body:V})||void 0,I=await this.runTools(Q,{body:V,context:R})||void 0,h=await this.usageLimits(Q,{body:V,context:R})||void 0,r=await this.trailingContext(Q,{body:V,context:R})||void 0,p=await this.attachmentsFor(Q,Z,{body:V}),l=await this.attachmentRetention(Q,{route:"stream",threadId:Z,body:V});sQ(l,this.turnAttachmentMaxAgeMs);let O=[],A=p&&l?p.withLifetime({next:()=>sQ(l,this.turnAttachmentMaxAgeMs),onPut:(E)=>O.push(E)}):p,B=this.agent.memory?await this.memoryScopes(Q,{body:V}):void 0;if(D?.cancelled)return Q8();let q=Z?new cJ(this.store,Z,C,(E)=>this.reportHookFailure(E)):null,DQ=`run_${crypto.randomUUID()}`,e=[],kQ,QQ={req:Q,runId:DQ,threadId:Z,get denials(){return e},get turn(){return kQ?.turn}},TQ={id:null,notified:Promise.resolve()},j=this.agent.stream({runId:DQ,messages:C,turn:X,threadId:Z,...P.parallel||z==="parallel"||y.has(Q)?{keepOtherTurnsOpen:!0}:{},...q?{onMessage:(E)=>q.finish(E)}:{},onTurn:(E)=>{if(TQ.id!==null)return;TQ.id=E.id;let JQ=q?q.settled():Promise.resolve();TQ.notified=JQ.then(()=>this.safely(()=>this.onMessage(E,QQ)))},instructions:L,...MQ.has(Q)?{event:MQ.get(Q)}:{},...y.has(Q)?{echoTurn:!0}:{},...f?{reasoning:f}:{},...x&&x.length>0?{skills:x}:{},...I?.tools&&I.tools.length>0?{tools:I.tools}:{},...I?.activeTools?{activeTools:I.activeTools}:{},...r?{trailingContext:r}:{},...h?{usageLimits:h}:{},context:R,attachments:A,body:V,redactError:(E,JQ)=>this.redactError(E,JQ,QQ),onProviderRetry:(E)=>this.onProviderRetry(E,QQ),nonces:this.nonces,receipts:this.receipts,subject:Y,...B?{memory:{scopes:B,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&S8(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==tQ.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(E)=>this.prepareStep(E,QQ)}:{}});e=j.denials,kQ=j;let x8=this.liveRuns.register(j,{threadId:Z,owner:Y,clientRunId:G,onEvent:(E)=>this.dispatchEvent(E,QQ),onInternalError:(E)=>this.reportHookFailure(E),maxRunDurationMs:this.agent.maxRunDurationMs});N=j;let jQ=MQ.get(Q);if(uJ.set(j,{startedAt:new Date,owner:Y,turn:jQ?{...jQ.text?{text:jQ.text}:{},event:{name:jQ.name}}:hZ(X),joined:[],body:V}),q)mJ.set(j,q),this.follow(j,q);if(Z)$6(this.liveRuns,Z,j.runId);let X$=X?.files??[],I8=this.definesRetention()&&(X$.length>0||l==="turn")?()=>this.expireTurn({scoped:p,files:X$,made:O,owner:Y}):null,{stored:w8,hooks:$J}=this.persistRun(j,QQ,x8,q,TQ,I8);if(t.set(j,w8),mZ.set(Q,{run:j,hooks:$J}),y.has(Q))y.set(Q,{run:j,hooks:$J});if(P.release)j.result().then(P.release,P.release);return Q.ctx?.()?.waitUntil($J),j.toResponse()};try{await this.authorizeRequest(Q,{route:"stream",threadId:Z,body:V});let P=await this.foreignFile([...X?.files??[],...Z?[]:U6($.messages)],Y);if(P)return P;if(D?.cancelled)return Q8();let C=await this.runLimitKey(Q,{owner:Y,threadId:Z}),F=C===null?T:oZ(this.liveRuns).take(C,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!F)return RQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);let L;try{return L=Z?await this.withThread(Z,Y,U,{req:Q,requested:K?"supersede":z,decide:!K,source:y.has(Q)?"server":"client",turn:X,body:V,limitKey:C}):await U(),L}finally{let R=N,f=L?uZ.get(L):void 0;if(R)R.result().then(F,F);else if(f)f.then(F,F);else F()}}finally{if(D&&nQ.get(G)===D)nQ.delete(G)}}async withThread(Q,J,$,Z){if(Z.requested==="skip"&&SQ.has(Q))return J8(Q);for(;;){let W=await this.underThreadLock(Q,J,$,Z);if(!("waitFor"in W))return W.response;await W.waitFor}}async underThreadLock(Q,J,$,Z){let W=SQ.get(Q)??Promise.resolve(),X,K=new Promise((z)=>{X=z}),G=W.then(()=>K);SQ.set(Q,G),await W;try{let z=this.liveRuns.running({threadId:Q}).map((D)=>({info:D,run:this.liveRuns.get(D.runId)})).filter((D)=>D.run!==null);if(z.length===0){let D=await this.liveRuns.find({threadId:Q}),N=D?this.liveRuns.get(D.runId):null;if(N)await t.get(N);return{response:await $(pJ)}}let V=Z.intake?.policy??(Z.decide?await this.decideBusy(Q,J,z,Z):Z.requested??"supersede"),Y=(D)=>(t.get(D)??D.result()).then(T,T);if(V==="skip")return{response:J8(Q)};if(V==="queue")return{waitFor:Promise.all(z.map(({run:D})=>Y(D)))};if(V==="join"){let D=z.filter(({info:_})=>this.liveRuns.mayAccess(_.runId,J));if(D.length===0)return{response:a()};let N=D[D.length-1],H=i9(Z.turn,MQ.get(Z.req)),U=H?N.run.join?.(H)??null:null;if(!U)return{waitFor:Y(N.run)};return uJ.get(N.run)?.joined.push(hZ(H)),{response:this.joinResponse(Q,J,N.run,U,H,$,Z)}}if(V==="parallel"){let D=Z.intake??={policy:V,waited:new WeakSet},N=z.filter(({run:P})=>!iZ(P,mJ.get(P)).done&&!D.waited.has(P));if(N.length>0){for(let{run:L}of N)D.waited.add(L);let P=Promise.all(N.map(({run:L})=>iZ(L,mJ.get(L)).promise)),C,F=new Promise((L)=>{C=setTimeout(L,s9)});return{waitFor:Promise.race([P,F]).finally(()=>clearTimeout(C))}}let{max:H,overflow:U}=e9(await this.maxThreadRuns(Z.req,{threadId:Q,owner:J,body:Z.body}));if(z.length>=H){if(U==="queue")return{waitFor:Promise.race(z.map(({run:P})=>Y(P)))};return{response:RQ(429,"too_many_runs",`This conversation already has ${z.length} answers going. Wait for one to finish, or stop it, and send again.`)}}let _=Z.limitKey===null?T:oZ(this.liveRuns).take(Z.limitKey,`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!_)return{response:RQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`)};return{response:await $({parallel:!0,release:_})}}if(z.some(({info:D})=>!this.liveRuns.mayAccess(D.runId,J)))return{response:a()};for(let{run:D}of z)D.stop({reason:"superseded by a later turn on this thread"});return await Promise.all(z.map(({run:D})=>t.get(D))),{response:await $(pJ)}}finally{if(X(),SQ.get(Q)===G)SQ.delete(Q)}}async decideBusy(Q,J,$,Z){let W=await this.busyPolicy(Z.req,{threadId:Q,owner:J,requested:Z.requested,source:Z.source,turn:Z.turn,body:Z.body,running:$.map(({info:X,run:K})=>{let G=uJ.get(K);return{runId:X.runId,startedAt:G?.startedAt??new Date(X.startedAt),owner:this.liveRuns.ownerOf(X.runId),turn:G?.turn??{},messageId:K.turn?.id,body:G?.body,joined:[...G?.joined??[]]}})});if(!yZ.includes(W))throw TypeError(`AgentController.busyPolicy answers "supersede", "queue", "join", "parallel" or "skip"; got ${JSON.stringify(W)}.`);return W}joinResponse(Q,J,$,Z,W,X,K){let G=(H)=>({kind:"answered",run:H,hooks:t.get(H)??H.result().then(T,T)}),z=Z.taken.then(async(H)=>{if(H||sJ.has($))return null;return this.withThread(Q,J,X,K)}),V=z.then(async(H)=>{if(!H)return sJ.has($)?{kind:"dropped"}:G($);let U=lZ.get(H);if(U)return U;let _=mZ.get(K.req);if(_&&o9(H))return{kind:"answered",..._};return{kind:"refused",error:await YQ.from(H),stored:await this.storeUnanswered(Q,$,W)}},async(H)=>{return this.reportHookFailure(H),{kind:"refused",error:new YQ("The turn started for a joined message failed.",{status:500}),stored:await this.storeUnanswered(Q,$,W)}});if(y.has(K.req))lJ.set(K.req,{run:$,answer:V});async function*Y(){let H=-1;for await(let P of $.frames())H=P.seq,yield P;let U=await z.catch(()=>null),_=await V;if(_.kind==="refused"){if(U?.body?.cancel().catch(T),_.stored&&W.localId)yield{seq:++H,event:{type:"message-id",localId:W.localId,messageId:_.stored.id,message:_.stored}};let P=_.error.status===429;yield{seq:++H,event:{type:"error",error:{code:P?"rate_limited":"unknown",message:`Your message was not answered: ${_.error.message}`,retryable:P}}};return}if(!U?.body)return;try{for await(let P of MZ(U.body))yield P}finally{U.body.cancel().catch(T)}}let D=(async()=>{await $.result().catch(T);let H=await V;if(H.kind==="answered")await H.run.result().catch(T)})(),N=dJ(Y());return uZ.set(N,D),lZ.set(N,V),N}async storeUnanswered(Q,J,$){await t.get(J);let Z=R8($.event?$.event.text:$.text,$.files,$.event);Z.turn=Z.id;try{return await this.store.appendMessages(Q,[Z]),Z}catch(W){return this.reportHookFailure(W),null}}async attach(Q=new w){let J=await zQ(Q,AQ);if(J.error)return m(J);let $=J.body,Z=typeof $.threadId==="string"?$.threadId:eZ(Q,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:Z});let W=$.emptyMiss===!0;if(!await this.threadInScope(Q,Z))return X8(Z,W);let X=typeof $.runId==="string"?$.runId:void 0,K=X&&this.liveRuns.isRunning(X)&&this.liveRuns.threadOf(X)===Z?{runId:X}:await this.liveRuns.find({threadId:Z});if(K&&!this.liveRuns.mayAccess(K.runId,await this.runOwner(Q)))return a();if(!K)return X8(Z,W);let G=typeof $.runId==="string"?$.runId:void 0,z=G&&G!==K.runId?void 0:P6(Q,$);try{return dJ(this.liveRuns.replay(K.runId,z))}catch(V){if(V instanceof VQ)return M(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof OQ)return M(404,{code:V.code,message:V.message});throw V}}async watch(Q=new w){let J=await zQ(Q,AQ);if(J.error)return m(J);let $=J.body,Z=typeof $.threadId==="string"?$.threadId:eZ(Q,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"watch needs a threadId: it is the thread whose runs are announced."});if(await this.authorizeRequest(Q,{route:"attach",threadId:Z}),!await this.threadInScope(Q,Z))return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let W=await this.runOwner(Q),X=this.liveRuns,K=J6(X),G=null,z=null,V=0,Y=()=>{if(z?.stop(),!G)return;let N=K.get(Z);if(N?.delete(G),N&&N.size===0)K.delete(Z);G=null},D=new ReadableStream({start(N){z=D8(N);let H=(_)=>{if(!X.mayAccess(_,W))return;try{N.enqueue(new TextEncoder().encode(Y8({seq:++V,event:{type:"run-start",runId:_,threadId:Z}}))),z?.touch()}catch{Y()}};G=H;let U=K.get(Z);if(!U)U=new Set,K.set(Z,U);U.add(H);for(let{runId:_}of X.running({threadId:Z}))H(_)},cancel(){Y()}});return Q.rawRequest?.signal?.addEventListener("abort",Y,{once:!0}),new Response(D,{status:200,headers:H8()})}async stop(Q=new w){let J=await zQ(Q,AQ);if(J.error)return m(J);let $=J.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof $.threadId==="string"?$.threadId:void 0});let Z=await this.runOwner(Q),W=typeof $.runId==="string"?$.runId:void 0;if(!W&&typeof $.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId($.clientRunId)??void 0,!W){let K=nQ.get($.clientRunId);if(K){if(K.owner!==null&&K.owner!==Z)return a();return K.cancelled=!0,{stopped:!0}}}}if(!W&&typeof $.threadId==="string"){let K=this.liveRuns.running({threadId:$.threadId});if(K.length>1){let G=K.filter((V)=>this.liveRuns.mayAccess(V.runId,Z));if(G.length===0)return a();let z=typeof $.reason==="string"?$.reason:void 0;for(let V of G){let Y=this.liveRuns.get(V.runId);if(Y)EQ(Y,{reason:z})}return{stopped:!0}}W=(await this.liveRuns.find({threadId:$.threadId}))?.runId}let X=W?this.liveRuns.get(W):null;if(!X)return{stopped:!1};if(!this.liveRuns.mayAccess(X.runId,Z))return a();return EQ(X,{reason:typeof $.reason==="string"?$.reason:void 0}),{stopped:!0}}attachmentScope(Q,J,$){let Z=this.hooks?.attachmentScope;if(Z)return Z(Q,J,$);let W=Q.ctx()?.user,X=W?.id??W?.publicId;if(X!==void 0&&X!==null&&String(X)!=="")return{key:`user:${String(X)}`};if(J)return{key:`thread:${J}`};return null}attachmentRetention(Q,J){return this.hooks?.attachmentRetention?.(Q,J)??null}definesRetention(){return this.attachmentRetention!==tQ.prototype.attachmentRetention||Boolean(this.hooks?.attachmentRetention)}async sweepAttachments(Q={}){let J=Q.now??new Date,$=Q.limit??500;if(!this.attachments.expired||!this.attachments.delete)throw Error("sweepAttachments() needs an attachment store with expired() and delete(). Implement both on the controller's `attachments` store.");let Z={deleted:0,failed:0},W=this.deletionTargets();for(let X of await this.attachments.expired(J,$))try{await nJ(X,W),Z.deleted++}catch(K){Z.failed++,this.reportHookFailure(K)}for(let X of await this.fileOwners.expired?.(J,$)??[])try{await this.deleteProviderFile(X),Z.deleted++}catch(K){Z.failed++,this.reportHookFailure(K)}return Z}deletionTargets(){return{store:this.attachments,storage:this.attachmentStorage,provider:this.agent.provider,fileOwners:this.fileOwners}}async deleteProviderFile(Q){let J=this.agent.provider;if(!J.deleteFile)throw Error(`Cannot delete provider file ${Q}: the agent's provider has no deleteFile().`);await J.deleteFile(Q),await this.fileOwners.delete?.(Q)}async expireTurn(Q){let J=this.deletionTargets(),$=new Set,Z=new Set,W=async(X)=>{if($.has(X.id))return;if($.add(X.id),X.fileId)Z.add(X.fileId);try{await nJ(X,J)}catch(K){this.reportHookFailure(K)}};for(let X of Q.made)if(X.deleteAfterTurn)await W(X);for(let X of Q.files){if(X.attachmentId&&Q.scoped){let K=await Q.scoped.get(X.attachmentId).catch(()=>null);if(K?.deleteAfterTurn)await W(K)}if(X.fileId&&!Z.has(X.fileId)){Z.add(X.fileId);let K=await this.fileOwners.get(X.fileId);if(K?.deleteAfterTurn&&K.owner===Q.owner)try{await this.deleteProviderFile(X.fileId)}catch(G){this.reportHookFailure(G)}}}}attachmentLimits(Q){let J=this.hooks?.attachmentLimits;if(J)return J(Q);return null}checkUpload(Q,J,$){return this.hooks?.checkUpload?.(Q,J,$)}attachmentDestination(Q,J,$){let Z=this.hooks?.attachmentDestination;if(Z)return Z(Q,J,$);return"both"}async attachmentsFor(Q,J,$={body:{}}){let Z=await this.attachmentScope(Q,J,$);if(!Z)return null;return new QJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(Q=new w){let J=this.voice;if(!J)return iJ();let $=await zQ(Q,AQ);if($.error)return m($);let{sdp:Z,threadId:W,pushToTalk:X}=$.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return M(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let K=aQ($.body,_6),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(Q,{route:"stream",threadId:G,body:K});let z=Q.ctx?.()?.user??null,V=await J.start({req:Q,body:K,threadId:G,user:z,pushToTalk:X===!0}),Y=Date.now(),D,N=async(F)=>{if(F!==void 0)console.error("[gemi/ai] a voice session could not start.",F);if(D)await J.realtime.hangup(D).catch((L)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",L)});try{await V.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:V.threadId??G??"",reason:"start_failed",startedAt:Y,endedAt:Date.now(),durationMs:0,seconds:0,usage:S(),transcription:{usage:S(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(L){console.error("[gemi/ai] a voice session's onEnd threw.",L)}},H=V.threadId??G;if(!H)return await N(void 0),M(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(H!==G)await this.authorizeRequest(Q,{route:"stream",threadId:H,body:K})}catch(F){throw await N(void 0),F}let U=crypto.randomUUID(),_=V.tools??[];try{if(V.mcp)_=[..._,...await EJ(V.mcp,{user:z,sessionId:U})]}catch(F){return await N(F),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...V.session,tools:[...UQ(J.delegate),...V.session?.tools??[],..._.map((F)=>F.tool)],...X===!0?{turnDetection:null}:{}},C;try{C=await J.realtime.createCall({sdp:Z,session:P,safetyIdentifier:V.safetyIdentifier})}catch(F){await N(F);let L=F instanceof W$&&F.code==="rate_limited";return M(L?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=C.callId;try{await this.voiceStore.create({id:U,callId:C.callId,threadId:H,owner:await this.runOwner(Q),body:K,startedAt:Y});let{threadId:F,session:L,safetyIdentifier:R,mcp:f,tools:x,...I}=V;return{sessionId:s.start({...I,tools:_,controller:this.constructor,threadId:H,user:z,body:K,call:{realtime:J.realtime,callId:C.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:J.delegate,session:P}).sessionId,sdp:C.sdpAnswer,threadId:H,delegate:J.delegate?.name??_Q,endsAt:Y+(V.limits?.maxDurationMs??900000)}}catch(F){return await N(F),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(Q=new w){if(!this.voice)return iJ();let J=await this.voiceSession(Q);if(J instanceof Response)return J;let $=await zQ(Q,AQ);if($.error)return m($);let Z=aQ($.body,[]);if(await this.authorizeRequest(Q,{route:"stream",threadId:J.threadId,body:Z}),J.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update(J.id,{body:Z}),s.get(J.id)?.setBody(Z),{updated:!0}}async voiceEnd(Q=new w){let J=this.voice;if(!J)return iJ();let $=await this.voiceSession(Q);if($ instanceof Response)return $;if(await this.authorizeRequest(Q,{route:"stream",threadId:$.threadId,body:$.body}),$.endedAt!==void 0)return{ended:!1};let Z=s.get($.id);if(Z)await Z.end("hangup");else await J.realtime.hangup($.callId),await this.voiceStore.update($.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(Q){let J=Q.params?.sessionId,$=typeof J==="string"&&J?await this.voiceStore.get(J):null;if(!$)return M(404,{code:"voice_not_found",message:"No such voice session."});if($.owner!==null&&$.owner!==await this.runOwner(Q))return a();return $}async upload(Q=new w){let J=await Q.rawRequest.formData(),$=J.get("file");if(!($ instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=$ instanceof File&&$.name?$.name:"upload",W=$.type||"application/octet-stream",X=X6(J.get("body")),K=J.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof K==="string"&&K.length>0?K:void 0,body:X});let G=G6(await this.attachmentLimits(Q),$,Z,W);if(G)throw new eJ(G.code,G.message);await this.scopeStore(Q,X);let z=typeof K==="string"&&K.length>0&&await this.store.loadThread(K)!==null?K:void 0,V=await this.runOwner(Q),Y=null,D=(x)=>this.fileOwners.record(x,{owner:V,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString(),...Y}),N={body:X,threadId:z},H=await this.checkUpload({name:Z,size:$.size,mimeType:W},Q,N);if(H)throw new eJ(H.code||"upload_refused",H.message);let U=await this.attachmentDestination($,Q,N),_=L6(U,J.get("destination")),P=await this.attachmentScope(Q,z,{body:X});Y=sQ(await this.attachmentRetention(Q,{route:"upload",threadId:z,body:X}),this.turnAttachmentMaxAgeMs);let C=_!=="provider"&&!P;if(C){if(_==="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()`.');O6()}if(_==="provider"||!P){let x=await sZ(this.agent.provider,$);await D(x);let I={fileId:x,name:Z,mimeType:W,size:$.size,destination:"provider"};if(C)I.downgraded="no_scope";return I}let F=_8(),L=await this.attachmentStorage.put({name:L8(F,Z),body:$,contentType:W}),R=_==="both"?await sZ(this.agent.provider,$):void 0;if(R)await D(R);let f={id:F,scopeKey:P.key,fileId:R,objectName:L,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString(),destination:_,...Y};return await this.attachments.put(P,f),{fileId:R,attachmentId:F,name:Z,mimeType:W,size:$.size,destination:_}}async foreignFile(Q,J){let $=new Set(Q.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of $){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==J:this.requireKnownFiles)return C6()}return null}onMessage(Q,J){return this.hooks?.onMessage?.(Q,J)}onToolCall(Q,J){return this.hooks?.onToolCall?.(Q,J)}onToolResult(Q,J,$){return this.hooks?.onToolResult?.(Q,J,$)}onAwaitingInput(Q,J){return this.hooks?.onAwaitingInput?.(Q,J)}redactError(Q,J,$){let Z=this.hooks?.redactError;if(Z)return Z(Q,J,$);return $$(Q,J)}onError(Q,J){return this.hooks?.onError?.(Q,J)}onProviderRetry(Q,J){return this.hooks?.onProviderRetry?.(Q,J)}onStreamComplete(Q,J){return this.hooks?.onStreamComplete?.(Q,J)}reportHookFailure(Q){let J=this.hooks?.reportHookFailure;if(J)try{return J(Q)}catch($){console.error("[gemi/ai] reportHookFailure hook failed",$)}console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,J){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},J);return;case"tool-result":{let $=Q.part;await this.onToolResult($,J,{toolCallId:$.toolCallId,name:String($.name),input:A8($)});return}case"awaiting-input":await this.onAwaitingInput(Q.pending,J);return;case"error":await this.onError(F8(Q.error),J);return;default:return}}async readThread(Q,J={}){let Z=await(J.scope===null||J.scope===void 0?this.store:W8(this.store,J.scope)).loadThread(Q);if(!Z)return null;let{messages:W}=await this.settleThread(Q,Z,{write:!1});return W}isRunLive(Q,J){return this.liveRuns.get(Q)!==null}async settleThread(Q,J,{write:$}){let Z=(z)=>this.isRunLive(z,Q),W=await IZ(J,Z),X=W.messages,K=[],G=new Map(W.settled.map((z)=>[z.id,z]));if(A6(X)||$)try{let z=await bZ(X,{threadId:Q,store:i.store,isRunLive:Z,outputSchemaFor:(V)=>this.toolNamed(V)?.outputSchema,modelOutputFor:(V,Y)=>M8(this.toolNamed(V),Y,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});X=z.messages,K=z.jobs;for(let V of z.settled)G.set(V.id,V);if($&&z.orphans.length>0){await vZ(i.store,z.orphans,(Y)=>this.reportHookFailure(Y));let V=new Set(z.orphans.map((Y)=>Y.id));K=K.map((Y)=>V.has(Y.id)?{...Y,orphaned:!0}:Y)}}catch(z){this.reportHookFailure(z)}if($&&G.size>0)try{await this.store.appendMessages(Q,[...G.values()])}catch(z){this.reportHookFailure(z)}return{messages:X,jobs:K}}jobsBlockMax(){let Q=this.agent.jobs?.contextBlock;if(Q===!1)return 0;return Q?.max??qQ}jobsBlock(Q){return N$(Q,this.jobsBlockMax())}toolNamed(Q){let J=($)=>{for(let Z of $){let W=Z;if(Array.isArray(W.tools)){let X=J(W.tools);if(X)return X}else if(W.name===Q)return W}return};return J(this.agent.tools??[])}follow(Q,J){(async()=>{try{for await(let $ of Q.frames())J.frame($)}catch($){this.reportHookFailure($)}})()}persistRun(Q,J,$,Z=null,W={id:null,notified:Promise.resolve()},X=null){let K=(Y)=>X?Y.then(()=>this.safely(X)):Y,G=Promise.resolve(),z=(async()=>{let Y;try{Y=await Q.result()}catch(N){Z?.close(),await Z?.settled(),G=K(W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:N instanceof Error?N.message:String(N),retryable:!1},J))));return}let D=Y.messages;if(Z?.close(D),await Z?.settled(),J.threadId&&D.length>0)try{await this.store.appendMessages(J.threadId,D)}catch(N){this.reportHookFailure(N)}G=K(this.notifyRun(Y,D,J,W))})(),V=z.then(()=>S6(Promise.all([G,$]).then(()=>{}),this.hookHoldMs));return{stored:z,hooks:V}}async notifyRun(Q,J,$,Z){await Z.notified;for(let W of J){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,$))}await this.safely(()=>this.onStreamComplete(Q,$))}async safely(Q){try{await Q()}catch(J){this.reportHookFailure(J)}}}var tJ=["turn","clientRunId","threadId","messages","regenerate","ifBusy"],W6=["text","files","toolResults"];function aQ(Q,J=j8(Q)?tJ:[...tJ,...W6]){let $={};for(let[Z,W]of Object.entries(Q)){if(J.includes(Z))continue;Object.defineProperty($,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return $}function X6(Q){if(Q===null)return{};let J;if(typeof Q==="string")try{J=JSON.parse(Q)}catch{throw new rJ("The upload's `body` field is not valid JSON.")}if(J===null||typeof J!=="object"||Array.isArray(J))throw new rJ("The upload's `body` field must be a JSON object.");return aQ(J,tJ)}class rJ extends rQ{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function sZ(Q,J){try{return await Q.upload(J)}catch($){if($ instanceof B8&&K6.has($.status))throw new T8(XQ($).message);throw $}}var K6=new Set([400,413,415,422]);class eJ extends rQ{constructor(Q,J){super(J);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:Q,message:J}}},view:{}}}}function G6(Q,J,$,Z){if(!Q)return null;let{maxBytes:W,accept:X}=Q;if(typeof W==="number"&&J.size>W)return{code:"file_too_large",message:`${JSON.stringify($)} is ${aZ(J.size)}; the limit is ${aZ(W)}.`};if(X&&X.length>0&&!X.some((K)=>V6(K,$,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify($)} is not a type this chat accepts. Accepted: ${X.join(", ")}.`};return null}function V6(Q,J,$){let Z=Q.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return J.toLowerCase().endsWith(Z);let W=$.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function aZ(Q){if(Q<1024)return`${Q} B`;let J=["KB","MB","GB"],$=Q/1024,Z=0;while($>=1024&&Z<J.length-1)$/=1024,Z++;return`${Math.round($*10)/10} ${J[Z]}`}class T8 extends rQ{constructor(Q){super(Q);this.name="RejectedUploadError";let J=/(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:J,message:Q}}},view:{}}}}async function zQ(Q,J){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!z6($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number($.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>J)return tZ(J);let W;try{let K=await Y6($,J);if(K===null)return tZ(J);W=K}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 z6(Q){return V8(Q)==="application/json"}async function Y6(Q,J){if(!Number.isFinite(J)||!Q.body)return await Q.text();let $=Q.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:z}=await $.read();if(G)break;if(W+=z.byteLength,W>J)return await $.cancel().catch(T),null;Z.push(z)}let X=new Uint8Array(W),K=0;for(let G of Z)X.set(G,K),K+=G.byteLength;return new TextDecoder().decode(X)}function tZ(Q){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${Q} bytes).`}}function RQ(Q,J,$){return M(Q,{...eQ(G8(Q),$,Q),code:J})}function m(Q){if(Q.status===413)return RQ(413,Q.code??"body_too_large",Q.error??"");return M(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function j8(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function D6(Q){let J=j8(Q)?Q.turn:Q,$={};if(typeof J.text==="string")$.text=J.text;if(Array.isArray(J.files)){let Z=H6(J.files);if(typeof Z==="string")return{error:Z};$.files=Z}if(Array.isArray(J.toolResults))$.toolResults=J.toolResults;if(Object.keys($).length===0)return{};if(J===Q.turn&&J.localId!==void 0&&J.localId!==null&&J.localId!==""){let{localId:Z}=J;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>rZ)return{error:`turn.localId is longer than ${rZ} characters.`};$.localId=Z}return{turn:$}}var rZ=200;function H6(Q){let J=[];for(let[$,Z]of Q.entries()){let W=`turn.files[${$}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let X={};for(let Y of["fileId","attachmentId","name","mimeType"]){let D=Z[Y];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${Y} must be a string.`;X[Y]=D}let{fileId:K,attachmentId:G,name:z,mimeType:V}=X;if(K?.startsWith(oQ))return`${W}.fileId holds a gemi attachment id (${K}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(G!==void 0&&!G.startsWith(oQ))return`${W}.attachmentId is not a gemi attachment id: it must start with "${oQ}".`;if(!K&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;J.push({...K?{fileId:K}:{},...G?{attachmentId:G}:{},...z!==void 0?{name:z}:{},...V!==void 0?{mimeType:V}:{}})}return J}function P6(Q,J){if(typeof J.from==="number"&&Number.isFinite(J.from))return Math.max(0,Math.floor(J.from));if(typeof J.cursor==="number"&&Number.isFinite(J.cursor)){let Z=Math.floor(J.cursor);if(Z>=0)return Z+1;return}let $=Q?.rawRequest?.headers?.get("Last-Event-ID");if($){let Z=Number.parseInt($,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function eZ(Q,J){let $=Q?.search?.get(J);return typeof $==="string"?$:void 0}function N6(Q){let J=Z$(Q);for(let $=Q.length-1;$>=0;$--){let Z=Q[$];if(Z.role!=="user"||J.has(Z.id))continue;let W="",X=[];for(let K of Z.content){if(K.type==="text")W+=K.text;if(K.type==="file")X.push({...K.fileId?{fileId:K.fileId}:{},...K.attachmentId?{attachmentId:K.attachmentId}:{},...K.name?{name:K.name}:{},...K.mimeType?{mimeType:K.mimeType}:{}})}if(!W&&X.length===0)continue;return{index:$,turn:{...W?{text:W}:{},...X.length>0?{files:X}:{}}}}return null}function Q8(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function F6(Q){let J=Q.event;if(Q.text!==void 0||Q.turn!==void 0)throw TypeError("AgentController.startTurn takes an `event` or a `text`/`turn`, not both: an event is not a person's message.");if(typeof J!=="object"||J===null||typeof J.name!=="string"||!m9.test(J.name))throw TypeError('AgentController.startTurn\'s `event.name` must be letters, digits and `.`, `_`, `:`, `-` (at most 64), like "job-settled".');if(J.text!==void 0&&typeof J.text!=="string")throw TypeError("AgentController.startTurn's `event.text` must be a string.");let $;if(J.data!==void 0)try{$=JSON.parse(JSON.stringify(J.data))}catch(Z){throw TypeError(`AgentController.startTurn's \`event.data\` is not JSON: ${String(Z)}`)}return{name:J.name,...J.text?{text:J.text}:{},...$!==void 0?{data:$}:{}}}function J8(Q){return M(409,{code:E8,message:`Thread ${Q} has a run going, and this turn was not to interrupt it.`})}function a(){return M(403,eQ("permission","This run belongs to someone else.",403))}function C6(){return M(403,eQ("permission","A file in this turn was uploaded by someone else.",403))}function U6(Q){if(!Array.isArray(Q))return[];let J=[];for(let $ of Q){let Z=$?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")J.push({fileId:W.fileId})}return J}var _6=["sdp","threadId","pushToTalk"];function iJ(){return M(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function M(Q,J){return new Response(JSON.stringify({error:J}),{status:Q,headers:{"Content-Type":"application/json"}})}function L6(Q,J){if(typeof J!=="string"||J.length===0)return Q;if(J!=="both"&&J!=="provider"&&J!=="storage")throw Error(`Unknown attachment destination "${J}". Expected "both", "provider" or "storage".`);if(J===Q||Q==="both"&&J==="storage")return J;if(Q==="both"&&J==="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 "${J}" 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 $8=!1;function O6(){if($8)return;$8=!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 B6=2147483647;function S6(Q,J){let $=Q.then(()=>{},()=>{});if(!(J<=B6))return $;let Z,W=new Promise((X)=>{Z=setTimeout(X,J)});return Promise.race([$,W]).finally(()=>clearTimeout(Z))}var Z8=!1;function M6(Q){if(Z8||Bun.env.NODE_ENV!=="production")return;if(!(Q instanceof Q$))return;Z8=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}function A6(Q){return Q.some((J)=>J.content.some(($)=>$.type==="tool-result"&&$.status==="running"))}function W8(Q,J){if(typeof J!=="string"||J==="")throw TypeError("A store scope is a non-empty string.");if(!Q.forScope)throw Error("This controller's store cannot be scoped: storeScope() or a turn's `scope` needs a store that implements `forScope` (DatabaseAgentStore or MemoryAgentStore).");return Q.forScope(J)}function X8(Q,J=!1){if(J)return new Response(null,{status:204});return M(404,{code:"no_live_run",message:`No run in progress for thread ${Q} in this process.`})}export{q6 as windowMessages,UQ as voiceTools,j6 as turnStarts,J0 as toRealtimeUsage,$9 as toAgentTools,k6 as supportsStrict,x6 as splitTurns,u6 as settleSummaries,E6 as s,$$ as redactError,r6 as parsePartialJson,I6 as messageSize,FQ as measureUsage,EJ as mcpVoiceTools,IJ as liveRuns,LQ as keepSummary,Z0 as isCallNotFound,Z$ as injectedMessageIds,FJ as generate,P9 as evalChain,Z6 as defineAgentHooks,TJ as defaultVoiceStore,p6 as defaultUsageLimitStore,c6 as defaultSummaryStore,t6 as defaultPromptCacheKey,J$ as defaultNonceStore,wJ as defaultFileOwners,JJ as defaultAttachmentStore,hJ as defaultAgentStore,lQ as VoiceHangup,s as VoiceBridge,T6 as Usage,UJ as ToolNamespace,o as ToolError,s6 as ToolArgumentsTooLongError,i6 as Skill,QJ as ScopedAttachments,d6 as SKILLS_NAMESPACE,vJ as RedisReceiptStore,P8 as RedisNonceStore,e6 as RealtimeSideband,W$ as RealtimeRequestError,$0 as RealtimeClient,D$ as Prompt,N8 as PrismaNonceStore,l6 as PendingEscalation,W0 as OpenAIProvider,BJ as OpenAIImageProvider,kJ as MemoryVoiceSessionStore,m6 as MemoryUsageLimitStore,g6 as MemorySummaryStore,bJ as MemoryReceiptStore,Q$ as MemoryNonceStore,iQ as MemoryLiveRuns,dQ as MemoryFileOwners,mQ as MemoryCircuitStore,O8 as MemoryAttachmentStore,BQ as MemoryAgentStore,_$ as MemoryAgentJobStore,b$ as MEMORY_NAMESPACE,OQ as LiveRunNotFoundError,O$ as JobsRequireThreadError,L$ as JobHandle,R6 as JSONSchemaError,U8 as InvalidAttachmentScopeError,j$ as InMemoryAgentMemoryStore,cQ as ImageRequestError,uQ as ImageProvider,_J as ImageModel,VQ as FrameCursorEvictedError,CQ as FallbackProvider,f$ as FakeAgentMemoryStore,hQ as Eval,jJ as DatabaseAgentStore,zJ as DatabaseAgentMemoryStore,GJ as DatabaseAgentJobStore,Q0 as DEFAULT_TRANSCRIPTION_MODEL,T$ as DEFAULT_MEMORY_MAX_TOKENS,q$ as DEFAULT_MEMORY_LIMITS,b6 as DEFAULT_MAX_SUMMARY_TOKENS,n6 as DEFAULT_MAX_RUN_DURATION_MS,B$ as DEFAULT_JOB_DEADLINE_MS,qQ as DEFAULT_JOBS_CONTEXT_MAX,_Q as DEFAULT_DELEGATE_NAME,w6 as DEFAULT_CONTEXT_WINDOW_STEP,f6 as DEFAULT_CONTEXT_WINDOW_NOTE,v6 as DEFAULT_COMPACT_TRIGGER_TOKENS,y6 as DEFAULT_COMPACT_INSTRUCTIONS,h6 as COMPACT_SUMMARY_HEADER,G0 as AzureOpenAIProvider,SJ as AzureOpenAIImageProvider,K0 as AzureAnthropicProvider,C8 as AttachmentNotFoundError,X0 as AnthropicProvider,YQ as AgentTurnError,gQ as AgentTool,o6 as AgentRunError,RJ as AgentProvider,x$ as AgentMemoryRefusedError,I$ as AgentMemoryConflictError,w$ as AgentMemories,i as AgentJobs,KJ as AgentJobDeadlineSweep,S$ as AgentJob,tQ as AgentController,a6 as Agent};
|
|
336
|
+
`)||void 0,R=await this.context(Q,{body:V}),f=await this.reasoning(Q,{body:V})||void 0,x=await this.skills(Q,{body:V})||void 0,I=await this.runTools(Q,{body:V,context:R})||void 0,h=await this.usageLimits(Q,{body:V,context:R})||void 0,r=await this.trailingContext(Q,{body:V,context:R})||void 0,p=await this.attachmentsFor(Q,Z,{body:V}),l=await this.attachmentRetention(Q,{route:"stream",threadId:Z,body:V});sQ(l,this.turnAttachmentMaxAgeMs);let L=[],A=p&&l?p.withLifetime({next:()=>sQ(l,this.turnAttachmentMaxAgeMs),onPut:(E)=>L.push(E)}):p,B=this.agent.memory?await this.memoryScopes(Q,{body:V}):void 0;if(D?.cancelled)return Q8();let q=Z?new cJ(this.store,Z,C,(E)=>this.reportHookFailure(E)):null,DQ=`run_${crypto.randomUUID()}`,e=[],kQ,QQ={req:Q,runId:DQ,threadId:Z,get denials(){return e},get turn(){return kQ?.turn}},TQ={id:null,notified:Promise.resolve()},j=this.agent.stream({runId:DQ,messages:C,turn:X,threadId:Z,...P.parallel||z==="parallel"||y.has(Q)?{keepOtherTurnsOpen:!0}:{},...q?{onMessage:(E)=>q.finish(E)}:{},onTurn:(E)=>{if(TQ.id!==null)return;TQ.id=E.id;let JQ=q?q.settled():Promise.resolve();TQ.notified=JQ.then(()=>this.safely(()=>this.onMessage(E,QQ)))},instructions:O,...MQ.has(Q)?{event:MQ.get(Q)}:{},...y.has(Q)?{echoTurn:!0}:{},...f?{reasoning:f}:{},...x&&x.length>0?{skills:x}:{},...I?.tools&&I.tools.length>0?{tools:I.tools}:{},...I?.activeTools?{activeTools:I.activeTools}:{},...r?{trailingContext:r}:{},...h?{usageLimits:h}:{},context:R,attachments:A,body:V,redactError:(E,JQ)=>this.redactError(E,JQ,QQ),onProviderRetry:(E)=>this.onProviderRetry(E,QQ),nonces:this.nonces,receipts:this.receipts,subject:Y,...B?{memory:{scopes:B,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&S8(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==tQ.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(E)=>this.prepareStep(E,QQ)}:{}});e=j.denials,kQ=j;let x8=this.liveRuns.register(j,{threadId:Z,owner:Y,clientRunId:G,onEvent:(E)=>this.dispatchEvent(E,QQ),onInternalError:(E)=>this.reportHookFailure(E),maxRunDurationMs:this.agent.maxRunDurationMs});N=j;let jQ=MQ.get(Q);if(uJ.set(j,{startedAt:new Date,owner:Y,turn:jQ?{...jQ.text?{text:jQ.text}:{},event:{name:jQ.name}}:hZ(X),joined:[],body:V}),q)mJ.set(j,q),this.follow(j,q);if(Z)$6(this.liveRuns,Z,j.runId);let X$=X?.files??[],I8=this.definesRetention()&&(X$.length>0||l==="turn")?()=>this.expireTurn({scoped:p,files:X$,made:L,owner:Y}):null,{stored:w8,hooks:$J}=this.persistRun(j,QQ,x8,q,TQ,I8);if(t.set(j,w8),mZ.set(Q,{run:j,hooks:$J}),y.has(Q))y.set(Q,{run:j,hooks:$J});if(P.release)j.result().then(P.release,P.release);return Q.ctx?.()?.waitUntil($J),j.toResponse()};try{await this.authorizeRequest(Q,{route:"stream",threadId:Z,body:V});let P=await this.foreignFile([...X?.files??[],...Z?[]:U6($.messages)],Y);if(P)return P;if(D?.cancelled)return Q8();let C=await this.runLimitKey(Q,{owner:Y,threadId:Z}),F=C===null?T:oZ(this.liveRuns).take(C,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!F)return RQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);let O;try{return O=Z?await this.withThread(Z,Y,U,{req:Q,requested:K?"supersede":z,decide:!K,source:y.has(Q)?"server":"client",turn:X,body:V,limitKey:C}):await U(),O}finally{let R=N,f=O?uZ.get(O):void 0;if(R)R.result().then(F,F);else if(f)f.then(F,F);else F()}}finally{if(D&&nQ.get(G)===D)nQ.delete(G)}}async withThread(Q,J,$,Z){if(Z.requested==="skip"&&SQ.has(Q))return J8(Q);for(;;){let W=await this.underThreadLock(Q,J,$,Z);if(!("waitFor"in W))return W.response;await W.waitFor}}async underThreadLock(Q,J,$,Z){let W=SQ.get(Q)??Promise.resolve(),X,K=new Promise((z)=>{X=z}),G=W.then(()=>K);SQ.set(Q,G),await W;try{let z=this.liveRuns.running({threadId:Q}).map((D)=>({info:D,run:this.liveRuns.get(D.runId)})).filter((D)=>D.run!==null);if(z.length===0){let D=await this.liveRuns.find({threadId:Q}),N=D?this.liveRuns.get(D.runId):null;if(N)await t.get(N);return{response:await $(pJ)}}let V=Z.intake?.policy??(Z.decide?await this.decideBusy(Q,J,z,Z):Z.requested??"supersede"),Y=(D)=>(t.get(D)??D.result()).then(T,T);if(V==="skip")return{response:J8(Q)};if(V==="queue")return{waitFor:Promise.all(z.map(({run:D})=>Y(D)))};if(V==="join"){let D=z.filter(({info:_})=>this.liveRuns.mayAccess(_.runId,J));if(D.length===0)return{response:a()};let N=D[D.length-1],H=i9(Z.turn,MQ.get(Z.req)),U=H?N.run.join?.(H)??null:null;if(!U)return{waitFor:Y(N.run)};return uJ.get(N.run)?.joined.push(hZ(H)),{response:this.joinResponse(Q,J,N.run,U,H,$,Z)}}if(V==="parallel"){let D=Z.intake??={policy:V,waited:new WeakSet},N=z.filter(({run:P})=>!iZ(P,mJ.get(P)).done&&!D.waited.has(P));if(N.length>0){for(let{run:O}of N)D.waited.add(O);let P=Promise.all(N.map(({run:O})=>iZ(O,mJ.get(O)).promise)),C,F=new Promise((O)=>{C=setTimeout(O,s9)});return{waitFor:Promise.race([P,F]).finally(()=>clearTimeout(C))}}let{max:H,overflow:U}=e9(await this.maxThreadRuns(Z.req,{threadId:Q,owner:J,body:Z.body}));if(z.length>=H){if(U==="queue")return{waitFor:Promise.race(z.map(({run:P})=>Y(P)))};return{response:RQ(429,"too_many_runs",`This conversation already has ${z.length} answers going. Wait for one to finish, or stop it, and send again.`)}}let _=Z.limitKey===null?T:oZ(this.liveRuns).take(Z.limitKey,`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!_)return{response:RQ(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`)};return{response:await $({parallel:!0,release:_})}}if(z.some(({info:D})=>!this.liveRuns.mayAccess(D.runId,J)))return{response:a()};for(let{run:D}of z)D.stop({reason:"superseded by a later turn on this thread"});return await Promise.all(z.map(({run:D})=>t.get(D))),{response:await $(pJ)}}finally{if(X(),SQ.get(Q)===G)SQ.delete(Q)}}async decideBusy(Q,J,$,Z){let W=await this.busyPolicy(Z.req,{threadId:Q,owner:J,requested:Z.requested,source:Z.source,turn:Z.turn,body:Z.body,running:$.map(({info:X,run:K})=>{let G=uJ.get(K);return{runId:X.runId,startedAt:G?.startedAt??new Date(X.startedAt),owner:this.liveRuns.ownerOf(X.runId),turn:G?.turn??{},messageId:K.turn?.id,body:G?.body,joined:[...G?.joined??[]]}})});if(!yZ.includes(W))throw TypeError(`AgentController.busyPolicy answers "supersede", "queue", "join", "parallel" or "skip"; got ${JSON.stringify(W)}.`);return W}joinResponse(Q,J,$,Z,W,X,K){let G=(H)=>({kind:"answered",run:H,hooks:t.get(H)??H.result().then(T,T)}),z=Z.taken.then(async(H)=>{if(H||sJ.has($))return null;return this.withThread(Q,J,X,K)}),V=z.then(async(H)=>{if(!H)return sJ.has($)?{kind:"dropped"}:G($);let U=lZ.get(H);if(U)return U;let _=mZ.get(K.req);if(_&&o9(H))return{kind:"answered",..._};return{kind:"refused",error:await YQ.from(H),stored:await this.storeUnanswered(Q,$,W)}},async(H)=>{return this.reportHookFailure(H),{kind:"refused",error:new YQ("The turn started for a joined message failed.",{status:500}),stored:await this.storeUnanswered(Q,$,W)}});if(y.has(K.req))lJ.set(K.req,{run:$,answer:V});async function*Y(){let H=-1;for await(let P of $.frames())H=P.seq,yield P;let U=await z.catch(()=>null),_=await V;if(_.kind==="refused"){if(U?.body?.cancel().catch(T),_.stored&&W.localId)yield{seq:++H,event:{type:"message-id",localId:W.localId,messageId:_.stored.id,message:_.stored}};let P=_.error.status===429;yield{seq:++H,event:{type:"error",error:{code:P?"rate_limited":"unknown",message:`Your message was not answered: ${_.error.message}`,retryable:P}}};return}if(!U?.body)return;try{for await(let P of MZ(U.body))yield P}finally{U.body.cancel().catch(T)}}let D=(async()=>{await $.result().catch(T);let H=await V;if(H.kind==="answered")await H.run.result().catch(T)})(),N=dJ(Y());return uZ.set(N,D),lZ.set(N,V),N}async storeUnanswered(Q,J,$){await t.get(J);let Z=R8($.event?$.event.text:$.text,$.files,$.event);Z.turn=Z.id;try{return await this.store.appendMessages(Q,[Z]),Z}catch(W){return this.reportHookFailure(W),null}}async attach(Q=new w){let J=await zQ(Q,AQ);if(J.error)return m(J);let $=J.body,Z=typeof $.threadId==="string"?$.threadId:eZ(Q,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:Z});let W=$.emptyMiss===!0;if(!await this.threadInScope(Q,Z))return X8(Z,W);let X=typeof $.runId==="string"?$.runId:void 0,K=X&&this.liveRuns.isRunning(X)&&this.liveRuns.threadOf(X)===Z?{runId:X}:await this.liveRuns.find({threadId:Z});if(K&&!this.liveRuns.mayAccess(K.runId,await this.runOwner(Q)))return a();if(!K)return X8(Z,W);let G=typeof $.runId==="string"?$.runId:void 0,z=G&&G!==K.runId?void 0:P6(Q,$);try{return dJ(this.liveRuns.replay(K.runId,z))}catch(V){if(V instanceof VQ)return M(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof LQ)return M(404,{code:V.code,message:V.message});throw V}}async watch(Q=new w){let J=await zQ(Q,AQ);if(J.error)return m(J);let $=J.body,Z=typeof $.threadId==="string"?$.threadId:eZ(Q,"threadId");if(!Z)return M(400,{code:"invalid_request",message:"watch needs a threadId: it is the thread whose runs are announced."});if(await this.authorizeRequest(Q,{route:"attach",threadId:Z}),!await this.threadInScope(Q,Z))return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let W=await this.runOwner(Q),X=this.liveRuns,K=J6(X),G=null,z=null,V=0,Y=()=>{if(z?.stop(),!G)return;let N=K.get(Z);if(N?.delete(G),N&&N.size===0)K.delete(Z);G=null},D=new ReadableStream({start(N){z=D8(N);let H=(_)=>{if(!X.mayAccess(_,W))return;try{N.enqueue(new TextEncoder().encode(Y8({seq:++V,event:{type:"run-start",runId:_,threadId:Z}}))),z?.touch()}catch{Y()}};G=H;let U=K.get(Z);if(!U)U=new Set,K.set(Z,U);U.add(H);for(let{runId:_}of X.running({threadId:Z}))H(_)},cancel(){Y()}});return Q.rawRequest?.signal?.addEventListener("abort",Y,{once:!0}),new Response(D,{status:200,headers:H8()})}async stop(Q=new w){let J=await zQ(Q,AQ);if(J.error)return m(J);let $=J.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof $.threadId==="string"?$.threadId:void 0});let Z=await this.runOwner(Q),W=typeof $.runId==="string"?$.runId:void 0;if(!W&&typeof $.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId($.clientRunId)??void 0,!W){let K=nQ.get($.clientRunId);if(K){if(K.owner!==null&&K.owner!==Z)return a();return K.cancelled=!0,{stopped:!0}}}}if(!W&&typeof $.threadId==="string"){let K=this.liveRuns.running({threadId:$.threadId});if(K.length>1){let G=K.filter((V)=>this.liveRuns.mayAccess(V.runId,Z));if(G.length===0)return a();let z=typeof $.reason==="string"?$.reason:void 0;for(let V of G){let Y=this.liveRuns.get(V.runId);if(Y)EQ(Y,{reason:z})}return{stopped:!0}}W=(await this.liveRuns.find({threadId:$.threadId}))?.runId}let X=W?this.liveRuns.get(W):null;if(!X)return{stopped:!1};if(!this.liveRuns.mayAccess(X.runId,Z))return a();return EQ(X,{reason:typeof $.reason==="string"?$.reason:void 0}),{stopped:!0}}attachmentScope(Q,J,$){let Z=this.hooks?.attachmentScope;if(Z)return Z(Q,J,$);let W=Q.ctx()?.user,X=W?.id??W?.publicId;if(X!==void 0&&X!==null&&String(X)!=="")return{key:`user:${String(X)}`};if(J)return{key:`thread:${J}`};return null}attachmentRetention(Q,J){return this.hooks?.attachmentRetention?.(Q,J)??null}definesRetention(){return this.attachmentRetention!==tQ.prototype.attachmentRetention||Boolean(this.hooks?.attachmentRetention)}async sweepAttachments(Q={}){let J=Q.now??new Date,$=Q.limit??500;if(!this.attachments.expired||!this.attachments.delete)throw Error("sweepAttachments() needs an attachment store with expired() and delete(). Implement both on the controller's `attachments` store.");let Z={deleted:0,failed:0},W=this.deletionTargets();for(let X of await this.attachments.expired(J,$))try{await nJ(X,W),Z.deleted++}catch(K){Z.failed++,this.reportHookFailure(K)}for(let X of await this.fileOwners.expired?.(J,$)??[])try{await this.deleteProviderFile(X),Z.deleted++}catch(K){Z.failed++,this.reportHookFailure(K)}return Z}deletionTargets(){return{store:this.attachments,storage:this.attachmentStorage,provider:this.agent.provider,fileOwners:this.fileOwners}}async deleteProviderFile(Q){let J=this.agent.provider;if(!J.deleteFile)throw Error(`Cannot delete provider file ${Q}: the agent's provider has no deleteFile().`);await J.deleteFile(Q),await this.fileOwners.delete?.(Q)}async expireTurn(Q){let J=this.deletionTargets(),$=new Set,Z=new Set,W=async(X)=>{if($.has(X.id))return;if($.add(X.id),X.fileId)Z.add(X.fileId);try{await nJ(X,J)}catch(K){this.reportHookFailure(K)}};for(let X of Q.made)if(X.deleteAfterTurn)await W(X);for(let X of Q.files){if(X.attachmentId&&Q.scoped){let K=await Q.scoped.get(X.attachmentId).catch(()=>null);if(K?.deleteAfterTurn)await W(K)}if(X.fileId&&!Z.has(X.fileId)){Z.add(X.fileId);let K=await this.fileOwners.get(X.fileId);if(K?.deleteAfterTurn&&K.owner===Q.owner)try{await this.deleteProviderFile(X.fileId)}catch(G){this.reportHookFailure(G)}}}}attachmentLimits(Q){let J=this.hooks?.attachmentLimits;if(J)return J(Q);return null}checkUpload(Q,J,$){return this.hooks?.checkUpload?.(Q,J,$)}attachmentDestination(Q,J,$){let Z=this.hooks?.attachmentDestination;if(Z)return Z(Q,J,$);return"both"}async attachmentsFor(Q,J,$={body:{}}){let Z=await this.attachmentScope(Q,J,$);if(!Z)return null;return new QJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(Q=new w){let J=this.voice;if(!J)return iJ();let $=await zQ(Q,AQ);if($.error)return m($);let{sdp:Z,threadId:W,pushToTalk:X}=$.body;if(typeof Z!=="string"||!Z.trimStart().startsWith("v="))return M(400,{code:"invalid_request",message:"`sdp` must be the browser's SDP offer."});let K=aQ($.body,_6),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(Q,{route:"stream",threadId:G,body:K});let z=Q.ctx?.()?.user??null,V=await J.start({req:Q,body:K,threadId:G,user:z,pushToTalk:X===!0}),Y=Date.now(),D,N=async(F)=>{if(F!==void 0)console.error("[gemi/ai] a voice session could not start.",F);if(D)await J.realtime.hangup(D).catch((O)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",O)});try{await V.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:V.threadId??G??"",reason:"start_failed",startedAt:Y,endedAt:Date.now(),durationMs:0,seconds:0,usage:S(),transcription:{usage:S(),seconds:0},transcript:[],requests:[],toolCalls:[],errors:[]})}catch(O){console.error("[gemi/ai] a voice session's onEnd threw.",O)}},H=V.threadId??G;if(!H)return await N(void 0),M(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(H!==G)await this.authorizeRequest(Q,{route:"stream",threadId:H,body:K})}catch(F){throw await N(void 0),F}let U=crypto.randomUUID(),_=V.tools??[];try{if(V.mcp)_=[..._,...await EJ(V.mcp,{user:z,sessionId:U})]}catch(F){return await N(F),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let P={...V.session,tools:[...UQ(J.delegate),...V.session?.tools??[],..._.map((F)=>F.tool)],...X===!0?{turnDetection:null}:{}},C;try{C=await J.realtime.createCall({sdp:Z,session:P,safetyIdentifier:V.safetyIdentifier})}catch(F){await N(F);let O=F instanceof W$&&F.code==="rate_limited";return M(O?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=C.callId;try{await this.voiceStore.create({id:U,callId:C.callId,threadId:H,owner:await this.runOwner(Q),body:K,startedAt:Y});let{threadId:F,session:O,safetyIdentifier:R,mcp:f,tools:x,...I}=V;return{sessionId:s.start({...I,tools:_,controller:this.constructor,threadId:H,user:z,body:K,call:{realtime:J.realtime,callId:C.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:J.delegate,session:P}).sessionId,sdp:C.sdpAnswer,threadId:H,delegate:J.delegate?.name??_Q,endsAt:Y+(V.limits?.maxDurationMs??900000)}}catch(F){return await N(F),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(Q=new w){if(!this.voice)return iJ();let J=await this.voiceSession(Q);if(J instanceof Response)return J;let $=await zQ(Q,AQ);if($.error)return m($);let Z=aQ($.body,[]);if(await this.authorizeRequest(Q,{route:"stream",threadId:J.threadId,body:Z}),J.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update(J.id,{body:Z}),s.get(J.id)?.setBody(Z),{updated:!0}}async voiceEnd(Q=new w){let J=this.voice;if(!J)return iJ();let $=await this.voiceSession(Q);if($ instanceof Response)return $;if(await this.authorizeRequest(Q,{route:"stream",threadId:$.threadId,body:$.body}),$.endedAt!==void 0)return{ended:!1};let Z=s.get($.id);if(Z)await Z.end("hangup");else await J.realtime.hangup($.callId),await this.voiceStore.update($.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(Q){let J=Q.params?.sessionId,$=typeof J==="string"&&J?await this.voiceStore.get(J):null;if(!$)return M(404,{code:"voice_not_found",message:"No such voice session."});if($.owner!==null&&$.owner!==await this.runOwner(Q))return a();return $}async upload(Q=new w){let J=await Q.rawRequest.formData(),$=J.get("file");if(!($ instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=$ instanceof File&&$.name?$.name:"upload",W=$.type||"application/octet-stream",X=X6(J.get("body")),K=J.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof K==="string"&&K.length>0?K:void 0,body:X});let G=G6(await this.attachmentLimits(Q),$,Z,W);if(G)throw new eJ(G.code,G.message);await this.scopeStore(Q,X);let z=typeof K==="string"&&K.length>0&&await this.store.loadThread(K)!==null?K:void 0,V=await this.runOwner(Q),Y=null,D=(x)=>this.fileOwners.record(x,{owner:V,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString(),...Y}),N={body:X,threadId:z},H=await this.checkUpload({name:Z,size:$.size,mimeType:W},Q,N);if(H)throw new eJ(H.code||"upload_refused",H.message);let U=await this.attachmentDestination($,Q,N),_=O6(U,J.get("destination")),P=await this.attachmentScope(Q,z,{body:X});Y=sQ(await this.attachmentRetention(Q,{route:"upload",threadId:z,body:X}),this.turnAttachmentMaxAgeMs);let C=_!=="provider"&&!P;if(C){if(_==="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()`.');L6()}if(_==="provider"||!P){let x=await sZ(this.agent.provider,$);await D(x);let I={fileId:x,name:Z,mimeType:W,size:$.size,destination:"provider"};if(C)I.downgraded="no_scope";return I}let F=_8(),O=await this.attachmentStorage.put({name:O8(F,Z),body:$,contentType:W}),R=_==="both"?await sZ(this.agent.provider,$):void 0;if(R)await D(R);let f={id:F,scopeKey:P.key,fileId:R,objectName:O,name:Z,mimeType:W,size:$.size,createdAt:new Date().toISOString(),destination:_,...Y};return await this.attachments.put(P,f),{fileId:R,attachmentId:F,name:Z,mimeType:W,size:$.size,destination:_}}async foreignFile(Q,J){let $=new Set(Q.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of $){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==J:this.requireKnownFiles)return C6()}return null}onMessage(Q,J){return this.hooks?.onMessage?.(Q,J)}onToolCall(Q,J){return this.hooks?.onToolCall?.(Q,J)}onToolResult(Q,J,$){return this.hooks?.onToolResult?.(Q,J,$)}onAwaitingInput(Q,J){return this.hooks?.onAwaitingInput?.(Q,J)}redactError(Q,J,$){let Z=this.hooks?.redactError;if(Z)return Z(Q,J,$);return $$(Q,J)}onError(Q,J){return this.hooks?.onError?.(Q,J)}onProviderRetry(Q,J){return this.hooks?.onProviderRetry?.(Q,J)}onStreamComplete(Q,J){return this.hooks?.onStreamComplete?.(Q,J)}reportHookFailure(Q){let J=this.hooks?.reportHookFailure;if(J)try{return J(Q)}catch($){console.error("[gemi/ai] reportHookFailure hook failed",$)}console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,J){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},J);return;case"tool-result":{let $=Q.part;await this.onToolResult($,J,{toolCallId:$.toolCallId,name:String($.name),input:A8($)});return}case"awaiting-input":await this.onAwaitingInput(Q.pending,J);return;case"error":await this.onError(F8(Q.error),J);return;default:return}}async readThread(Q,J={}){let Z=await(J.scope===null||J.scope===void 0?this.store:W8(this.store,J.scope)).loadThread(Q);if(!Z)return null;let{messages:W}=await this.settleThread(Q,Z,{write:!1});return W}isRunLive(Q,J){return this.liveRuns.get(Q)!==null}async settleThread(Q,J,{write:$}){let Z=(z)=>this.isRunLive(z,Q),W=await IZ(J,Z),X=W.messages,K=[],G=new Map(W.settled.map((z)=>[z.id,z]));if(A6(X)||$)try{let z=await bZ(X,{threadId:Q,store:i.store,isRunLive:Z,outputSchemaFor:(V)=>this.toolNamed(V)?.outputSchema,modelOutputFor:(V,Y)=>M8(this.toolNamed(V),Y,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});X=z.messages,K=z.jobs;for(let V of z.settled)G.set(V.id,V);if($&&z.orphans.length>0){await vZ(i.store,z.orphans,(Y)=>this.reportHookFailure(Y));let V=new Set(z.orphans.map((Y)=>Y.id));K=K.map((Y)=>V.has(Y.id)?{...Y,orphaned:!0}:Y)}}catch(z){this.reportHookFailure(z)}if($&&G.size>0)try{await this.store.appendMessages(Q,[...G.values()])}catch(z){this.reportHookFailure(z)}return{messages:X,jobs:K}}jobsBlockMax(){let Q=this.agent.jobs?.contextBlock;if(Q===!1)return 0;return Q?.max??qQ}jobsBlock(Q){return N$(Q,this.jobsBlockMax())}toolNamed(Q){let J=($)=>{for(let Z of $){let W=Z;if(Array.isArray(W.tools)){let X=J(W.tools);if(X)return X}else if(W.name===Q)return W}return};return J(this.agent.tools??[])}follow(Q,J){(async()=>{try{for await(let $ of Q.frames())J.frame($)}catch($){this.reportHookFailure($)}})()}persistRun(Q,J,$,Z=null,W={id:null,notified:Promise.resolve()},X=null){let K=(Y)=>X?Y.then(()=>this.safely(X)):Y,G=Promise.resolve(),z=(async()=>{let Y;try{Y=await Q.result()}catch(N){Z?.close(),await Z?.settled(),G=K(W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:N instanceof Error?N.message:String(N),retryable:!1},J))));return}let D=Y.messages;if(Z?.close(D),await Z?.settled(),J.threadId&&D.length>0)try{await this.store.appendMessages(J.threadId,D)}catch(N){this.reportHookFailure(N)}G=K(this.notifyRun(Y,D,J,W))})(),V=z.then(()=>S6(Promise.all([G,$]).then(()=>{}),this.hookHoldMs));return{stored:z,hooks:V}}async notifyRun(Q,J,$,Z){await Z.notified;for(let W of J){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,$))}await this.safely(()=>this.onStreamComplete(Q,$))}async safely(Q){try{await Q()}catch(J){this.reportHookFailure(J)}}}var tJ=["turn","clientRunId","threadId","messages","regenerate","ifBusy"],W6=["text","files","toolResults"];function aQ(Q,J=j8(Q)?tJ:[...tJ,...W6]){let $={};for(let[Z,W]of Object.entries(Q)){if(J.includes(Z))continue;Object.defineProperty($,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return $}function X6(Q){if(Q===null)return{};let J;if(typeof Q==="string")try{J=JSON.parse(Q)}catch{throw new rJ("The upload's `body` field is not valid JSON.")}if(J===null||typeof J!=="object"||Array.isArray(J))throw new rJ("The upload's `body` field must be a JSON object.");return aQ(J,tJ)}class rJ extends rQ{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function sZ(Q,J){try{return await Q.upload(J)}catch($){if($ instanceof B8&&K6.has($.status))throw new T8(XQ($).message);throw $}}var K6=new Set([400,413,415,422]);class eJ extends rQ{constructor(Q,J){super(J);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:Q,message:J}}},view:{}}}}function G6(Q,J,$,Z){if(!Q)return null;let{maxBytes:W,accept:X}=Q;if(typeof W==="number"&&J.size>W)return{code:"file_too_large",message:`${JSON.stringify($)} is ${aZ(J.size)}; the limit is ${aZ(W)}.`};if(X&&X.length>0&&!X.some((K)=>V6(K,$,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify($)} is not a type this chat accepts. Accepted: ${X.join(", ")}.`};return null}function V6(Q,J,$){let Z=Q.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return J.toLowerCase().endsWith(Z);let W=$.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function aZ(Q){if(Q<1024)return`${Q} B`;let J=["KB","MB","GB"],$=Q/1024,Z=0;while($>=1024&&Z<J.length-1)$/=1024,Z++;return`${Math.round($*10)/10} ${J[Z]}`}class T8 extends rQ{constructor(Q){super(Q);this.name="RejectedUploadError";let J=/(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:J,message:Q}}},view:{}}}}async function zQ(Q,J){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!z6($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z=Number($.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>J)return tZ(J);let W;try{let K=await Y6($,J);if(K===null)return tZ(J);W=K}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 z6(Q){return V8(Q)==="application/json"}async function Y6(Q,J){if(!Number.isFinite(J)||!Q.body)return await Q.text();let $=Q.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:z}=await $.read();if(G)break;if(W+=z.byteLength,W>J)return await $.cancel().catch(T),null;Z.push(z)}let X=new Uint8Array(W),K=0;for(let G of Z)X.set(G,K),K+=G.byteLength;return new TextDecoder().decode(X)}function tZ(Q){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${Q} bytes).`}}function RQ(Q,J,$){return M(Q,{...eQ(G8(Q),$,Q),code:J})}function m(Q){if(Q.status===413)return RQ(413,Q.code??"body_too_large",Q.error??"");return M(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function j8(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function D6(Q){let J=j8(Q)?Q.turn:Q,$={};if(typeof J.text==="string")$.text=J.text;if(Array.isArray(J.files)){let Z=H6(J.files);if(typeof Z==="string")return{error:Z};$.files=Z}if(Array.isArray(J.toolResults))$.toolResults=J.toolResults;if(Object.keys($).length===0)return{};if(J===Q.turn&&J.localId!==void 0&&J.localId!==null&&J.localId!==""){let{localId:Z}=J;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>rZ)return{error:`turn.localId is longer than ${rZ} characters.`};$.localId=Z}return{turn:$}}var rZ=200;function H6(Q){let J=[];for(let[$,Z]of Q.entries()){let W=`turn.files[${$}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let X={};for(let Y of["fileId","attachmentId","name","mimeType"]){let D=Z[Y];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${Y} must be a string.`;X[Y]=D}let{fileId:K,attachmentId:G,name:z,mimeType:V}=X;if(K?.startsWith(oQ))return`${W}.fileId holds a gemi attachment id (${K}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(G!==void 0&&!G.startsWith(oQ))return`${W}.attachmentId is not a gemi attachment id: it must start with "${oQ}".`;if(!K&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;J.push({...K?{fileId:K}:{},...G?{attachmentId:G}:{},...z!==void 0?{name:z}:{},...V!==void 0?{mimeType:V}:{}})}return J}function P6(Q,J){if(typeof J.from==="number"&&Number.isFinite(J.from))return Math.max(0,Math.floor(J.from));if(typeof J.cursor==="number"&&Number.isFinite(J.cursor)){let Z=Math.floor(J.cursor);if(Z>=0)return Z+1;return}let $=Q?.rawRequest?.headers?.get("Last-Event-ID");if($){let Z=Number.parseInt($,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function eZ(Q,J){let $=Q?.search?.get(J);return typeof $==="string"?$:void 0}function N6(Q){let J=Z$(Q);for(let $=Q.length-1;$>=0;$--){let Z=Q[$];if(Z.role!=="user"||J.has(Z.id))continue;let W="",X=[];for(let K of Z.content){if(K.type==="text")W+=K.text;if(K.type==="file")X.push({...K.fileId?{fileId:K.fileId}:{},...K.attachmentId?{attachmentId:K.attachmentId}:{},...K.name?{name:K.name}:{},...K.mimeType?{mimeType:K.mimeType}:{}})}if(!W&&X.length===0)continue;return{index:$,turn:{...W?{text:W}:{},...X.length>0?{files:X}:{}}}}return null}function Q8(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function F6(Q){let J=Q.event;if(Q.text!==void 0||Q.turn!==void 0)throw TypeError("AgentController.startTurn takes an `event` or a `text`/`turn`, not both: an event is not a person's message.");if(typeof J!=="object"||J===null||typeof J.name!=="string"||!m9.test(J.name))throw TypeError('AgentController.startTurn\'s `event.name` must be letters, digits and `.`, `_`, `:`, `-` (at most 64), like "job-settled".');if(J.text!==void 0&&typeof J.text!=="string")throw TypeError("AgentController.startTurn's `event.text` must be a string.");let $;if(J.data!==void 0)try{$=JSON.parse(JSON.stringify(J.data))}catch(Z){throw TypeError(`AgentController.startTurn's \`event.data\` is not JSON: ${String(Z)}`)}return{name:J.name,...J.text?{text:J.text}:{},...$!==void 0?{data:$}:{}}}function J8(Q){return M(409,{code:E8,message:`Thread ${Q} has a run going, and this turn was not to interrupt it.`})}function a(){return M(403,eQ("permission","This run belongs to someone else.",403))}function C6(){return M(403,eQ("permission","A file in this turn was uploaded by someone else.",403))}function U6(Q){if(!Array.isArray(Q))return[];let J=[];for(let $ of Q){let Z=$?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")J.push({fileId:W.fileId})}return J}var _6=["sdp","threadId","pushToTalk"];function iJ(){return M(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function M(Q,J){return new Response(JSON.stringify({error:J}),{status:Q,headers:{"Content-Type":"application/json"}})}function O6(Q,J){if(typeof J!=="string"||J.length===0)return Q;if(J!=="both"&&J!=="provider"&&J!=="storage")throw Error(`Unknown attachment destination "${J}". Expected "both", "provider" or "storage".`);if(J===Q||Q==="both"&&J==="storage")return J;if(Q==="both"&&J==="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 "${J}" 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 $8=!1;function L6(){if($8)return;$8=!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 B6=2147483647;function S6(Q,J){let $=Q.then(()=>{},()=>{});if(!(J<=B6))return $;let Z,W=new Promise((X)=>{Z=setTimeout(X,J)});return Promise.race([$,W]).finally(()=>clearTimeout(Z))}var Z8=!1;function M6(Q){if(Z8||Bun.env.NODE_ENV!=="production")return;if(!(Q instanceof Q$))return;Z8=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}function A6(Q){return Q.some((J)=>J.content.some(($)=>$.type==="tool-result"&&$.status==="running"))}function W8(Q,J){if(typeof J!=="string"||J==="")throw TypeError("A store scope is a non-empty string.");if(!Q.forScope)throw Error("This controller's store cannot be scoped: storeScope() or a turn's `scope` needs a store that implements `forScope` (DatabaseAgentStore or MemoryAgentStore).");return Q.forScope(J)}function X8(Q,J=!1){if(J)return new Response(null,{status:204});return M(404,{code:"no_live_run",message:`No run in progress for thread ${Q} in this process.`})}export{q6 as windowMessages,UQ as voiceTools,j6 as turnStarts,J0 as toRealtimeUsage,$9 as toAgentTools,k6 as supportsStrict,x6 as splitTurns,u6 as settleSummaries,E6 as s,$$ as redactError,r6 as parsePartialJson,I6 as messageSize,FQ as measureUsage,EJ as mcpVoiceTools,IJ as liveRuns,OQ as keepSummary,Z0 as isCallNotFound,Z$ as injectedMessageIds,FJ as generate,P9 as evalChain,Z6 as defineAgentHooks,TJ as defaultVoiceStore,p6 as defaultUsageLimitStore,c6 as defaultSummaryStore,t6 as defaultPromptCacheKey,J$ as defaultNonceStore,wJ as defaultFileOwners,JJ as defaultAttachmentStore,hJ as defaultAgentStore,lQ as VoiceHangup,s as VoiceBridge,T6 as Usage,UJ as ToolNamespace,o as ToolError,s6 as ToolArgumentsTooLongError,i6 as Skill,QJ as ScopedAttachments,d6 as SKILLS_NAMESPACE,vJ as RedisReceiptStore,P8 as RedisNonceStore,e6 as RealtimeSideband,W$ as RealtimeRequestError,$0 as RealtimeClient,D$ as Prompt,N8 as PrismaNonceStore,l6 as PendingEscalation,W0 as OpenAIProvider,BJ as OpenAIImageProvider,kJ as MemoryVoiceSessionStore,m6 as MemoryUsageLimitStore,g6 as MemorySummaryStore,bJ as MemoryReceiptStore,Q$ as MemoryNonceStore,iQ as MemoryLiveRuns,dQ as MemoryFileOwners,mQ as MemoryCircuitStore,L8 as MemoryAttachmentStore,BQ as MemoryAgentStore,_$ as MemoryAgentJobStore,b$ as MEMORY_NAMESPACE,LQ as LiveRunNotFoundError,L$ as JobsRequireThreadError,O$ as JobHandle,R6 as JSONSchemaError,U8 as InvalidAttachmentScopeError,j$ as InMemoryAgentMemoryStore,cQ as ImageRequestError,uQ as ImageProvider,_J as ImageModel,VQ as FrameCursorEvictedError,CQ as FallbackProvider,f$ as FakeAgentMemoryStore,hQ as Eval,jJ as DatabaseAgentStore,zJ as DatabaseAgentMemoryStore,GJ as DatabaseAgentJobStore,Q0 as DEFAULT_TRANSCRIPTION_MODEL,T$ as DEFAULT_MEMORY_MAX_TOKENS,q$ as DEFAULT_MEMORY_LIMITS,b6 as DEFAULT_MAX_SUMMARY_TOKENS,n6 as DEFAULT_MAX_RUN_DURATION_MS,B$ as DEFAULT_JOB_DEADLINE_MS,qQ as DEFAULT_JOBS_CONTEXT_MAX,_Q as DEFAULT_DELEGATE_NAME,w6 as DEFAULT_CONTEXT_WINDOW_STEP,f6 as DEFAULT_CONTEXT_WINDOW_NOTE,v6 as DEFAULT_COMPACT_TRIGGER_TOKENS,y6 as DEFAULT_COMPACT_INSTRUCTIONS,h6 as COMPACT_SUMMARY_HEADER,G0 as AzureOpenAIProvider,SJ as AzureOpenAIImageProvider,K0 as AzureAnthropicProvider,C8 as AttachmentNotFoundError,X0 as AnthropicProvider,YQ as AgentTurnError,gQ as AgentTool,o6 as AgentRunError,RJ as AgentProvider,x$ as AgentMemoryRefusedError,I$ as AgentMemoryConflictError,w$ as AgentMemories,i as AgentJobs,KJ as AgentJobDeadlineSweep,S$ as AgentJob,tQ as AgentController,a6 as Agent};
|
|
337
337
|
|
|
338
|
-
//# debugId=
|
|
338
|
+
//# debugId=6652915AB4DE52EA64756E2164756E21
|