gemi 0.167.0 → 0.169.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 -5
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +16 -2
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/Prompt.d.ts +15 -1
- package/dist/ai/Prompt.d.ts.map +1 -1
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +32 -32
- package/dist/ai/index.js.map +4 -4
- package/dist/app/App.d.ts +3 -3
- package/dist/app/index.js +1 -1
- package/dist/bin/gemi.js +405 -376
- package/dist/bin/gemi.js.map +6 -5
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-eyv6hss6.js → chunk-0q65jzhv.js} +2 -2
- package/dist/{chunk-eyv6hss6.js.map → chunk-0q65jzhv.js.map} +1 -1
- package/dist/{chunk-p3qbym3v.js → chunk-0wet87jm.js} +2 -2
- package/dist/{chunk-p3qbym3v.js.map → chunk-0wet87jm.js.map} +1 -1
- package/dist/{chunk-4fzevafk.js → chunk-0wk992a5.js} +2 -2
- package/dist/{chunk-4fzevafk.js.map → chunk-0wk992a5.js.map} +1 -1
- package/dist/{chunk-q4vtjdea.js → chunk-17272ccy.js} +3 -3
- package/dist/{chunk-q4vtjdea.js.map → chunk-17272ccy.js.map} +1 -1
- package/dist/{chunk-w4at2d5d.js → chunk-1h6g1hkg.js} +2 -2
- package/dist/{chunk-w4at2d5d.js.map → chunk-1h6g1hkg.js.map} +1 -1
- package/dist/{chunk-hdt8cwsv.js → chunk-21hppqtb.js} +2 -2
- package/dist/{chunk-hdt8cwsv.js.map → chunk-21hppqtb.js.map} +1 -1
- package/dist/{chunk-qec3g4w3.js → chunk-2v7wq01w.js} +2 -2
- package/dist/{chunk-qec3g4w3.js.map → chunk-2v7wq01w.js.map} +1 -1
- package/dist/{chunk-z316fasf.js → chunk-2xtkh8bh.js} +19 -19
- package/dist/{chunk-z316fasf.js.map → chunk-2xtkh8bh.js.map} +3 -3
- package/dist/{chunk-0hfvwzd1.js → chunk-31np60bx.js} +2 -2
- package/dist/{chunk-0hfvwzd1.js.map → chunk-31np60bx.js.map} +1 -1
- package/dist/{chunk-mbkje42z.js → chunk-3682hkq0.js} +2 -2
- package/dist/{chunk-mbkje42z.js.map → chunk-3682hkq0.js.map} +1 -1
- package/dist/{chunk-fnj2hc5v.js → chunk-3rp908gn.js} +1 -1
- package/dist/{chunk-3xj1e3ns.js → chunk-44y62yav.js} +3 -3
- package/dist/{chunk-3xj1e3ns.js.map → chunk-44y62yav.js.map} +1 -1
- package/dist/{chunk-c3cdj9y7.js → chunk-4mtqbcc5.js} +2 -2
- package/dist/{chunk-c3cdj9y7.js.map → chunk-4mtqbcc5.js.map} +1 -1
- package/dist/{chunk-80703vks.js → chunk-4qpyz627.js} +2 -2
- package/dist/{chunk-80703vks.js.map → chunk-4qpyz627.js.map} +1 -1
- package/dist/{chunk-4rnpvajg.js → chunk-4tt14jnx.js} +2 -2
- package/dist/{chunk-4rnpvajg.js.map → chunk-4tt14jnx.js.map} +1 -1
- package/dist/{chunk-mcavkjh4.js → chunk-5aexecst.js} +2 -2
- package/dist/{chunk-mcavkjh4.js.map → chunk-5aexecst.js.map} +1 -1
- package/dist/{chunk-efjk5aq7.js → chunk-5n21z4n8.js} +2 -2
- package/dist/{chunk-efjk5aq7.js.map → chunk-5n21z4n8.js.map} +1 -1
- package/dist/{chunk-pk4drzc9.js → chunk-5nz46dyw.js} +2 -2
- package/dist/{chunk-pk4drzc9.js.map → chunk-5nz46dyw.js.map} +1 -1
- package/dist/{chunk-6tbs7yc1.js → chunk-6t1t7h05.js} +2 -2
- package/dist/{chunk-6tbs7yc1.js.map → chunk-6t1t7h05.js.map} +1 -1
- package/dist/{chunk-tms2g9at.js → chunk-777v6242.js} +1 -1
- package/dist/{chunk-kcgnjzqr.js → chunk-8b9ks729.js} +3 -3
- package/dist/{chunk-kcgnjzqr.js.map → chunk-8b9ks729.js.map} +1 -1
- package/dist/{chunk-8f4jkpv7.js → chunk-8hfyscnn.js} +1 -1
- package/dist/{chunk-4587ab6m.js → chunk-978pc27j.js} +2 -2
- package/dist/{chunk-4587ab6m.js.map → chunk-978pc27j.js.map} +1 -1
- package/dist/{chunk-y1ks8ahw.js → chunk-9aj6eavs.js} +2 -2
- package/dist/{chunk-y1ks8ahw.js.map → chunk-9aj6eavs.js.map} +1 -1
- package/dist/{chunk-xw5d66ec.js → chunk-9akefv1y.js} +2 -2
- package/dist/{chunk-xw5d66ec.js.map → chunk-9akefv1y.js.map} +1 -1
- package/dist/{chunk-y6x52vkb.js → chunk-9ft0ayhf.js} +2 -2
- package/dist/{chunk-y6x52vkb.js.map → chunk-9ft0ayhf.js.map} +1 -1
- package/dist/{chunk-m5hd632w.js → chunk-9wcv7e1a.js} +2 -2
- package/dist/{chunk-h5whhrds.js.map → chunk-9wcv7e1a.js.map} +1 -1
- package/dist/{chunk-c0dvdfm0.js → chunk-a9frf7ym.js} +2 -2
- package/dist/{chunk-c0dvdfm0.js.map → chunk-a9frf7ym.js.map} +1 -1
- package/dist/{chunk-ndj94vde.js → chunk-acmf790v.js} +2 -2
- package/dist/{chunk-ndj94vde.js.map → chunk-acmf790v.js.map} +1 -1
- package/dist/{chunk-2jk0f4sj.js → chunk-aj1jrwwh.js} +2 -2
- package/dist/{chunk-2jk0f4sj.js.map → chunk-aj1jrwwh.js.map} +1 -1
- package/dist/{chunk-36yp8364.js → chunk-c46vhvk4.js} +2 -2
- package/dist/{chunk-36yp8364.js.map → chunk-c46vhvk4.js.map} +1 -1
- package/dist/{chunk-tqgpahmn.js → chunk-d849rktz.js} +25 -25
- package/dist/{chunk-tqgpahmn.js.map → chunk-d849rktz.js.map} +6 -6
- package/dist/{chunk-5x9b1ema.js → chunk-df2zeevj.js} +2 -2
- package/dist/{chunk-5x9b1ema.js.map → chunk-df2zeevj.js.map} +1 -1
- package/dist/{chunk-ndyafsv6.js → chunk-drwjwtmj.js} +2 -2
- package/dist/{chunk-ndyafsv6.js.map → chunk-drwjwtmj.js.map} +1 -1
- package/dist/{chunk-wypncj52.js → chunk-ecdjbd2w.js} +3 -3
- package/dist/{chunk-wypncj52.js.map → chunk-ecdjbd2w.js.map} +1 -1
- package/dist/{chunk-6cw6tn57.js → chunk-embwksec.js} +2 -2
- package/dist/{chunk-6cw6tn57.js.map → chunk-embwksec.js.map} +1 -1
- package/dist/chunk-f4nanvkm.js +5 -0
- package/dist/{chunk-8v6y52et.js.map → chunk-f4nanvkm.js.map} +1 -1
- package/dist/{chunk-b8qfypzq.js → chunk-fb77hwk0.js} +3 -3
- package/dist/{chunk-b8qfypzq.js.map → chunk-fb77hwk0.js.map} +1 -1
- package/dist/{chunk-fva651jp.js → chunk-fcbgshf5.js} +2 -2
- package/dist/{chunk-fva651jp.js.map → chunk-fcbgshf5.js.map} +1 -1
- package/dist/{chunk-f6mwnw81.js → chunk-g1jfc50d.js} +3 -3
- package/dist/{chunk-f6mwnw81.js.map → chunk-g1jfc50d.js.map} +1 -1
- package/dist/{chunk-0psf0chk.js → chunk-g548q257.js} +2 -2
- package/dist/{chunk-0psf0chk.js.map → chunk-g548q257.js.map} +2 -2
- package/dist/{chunk-wjff0d08.js → chunk-gjwf07hy.js} +3 -3
- package/dist/{chunk-wjff0d08.js.map → chunk-gjwf07hy.js.map} +1 -1
- package/dist/{chunk-matvbghh.js → chunk-gv5r1rd7.js} +2 -2
- package/dist/{chunk-matvbghh.js.map → chunk-gv5r1rd7.js.map} +1 -1
- package/dist/{chunk-2ewe42dq.js → chunk-gwphn604.js} +3 -3
- package/dist/{chunk-2ewe42dq.js.map → chunk-gwphn604.js.map} +1 -1
- package/dist/{chunk-xed7yf6h.js → chunk-hgpvfhtp.js} +1 -1
- package/dist/{chunk-h5whhrds.js → chunk-hwpp9b7f.js} +2 -2
- package/dist/{chunk-m5hd632w.js.map → chunk-hwpp9b7f.js.map} +1 -1
- package/dist/{chunk-vqf4s99d.js → chunk-jd079awh.js} +2 -2
- package/dist/{chunk-vqf4s99d.js.map → chunk-jd079awh.js.map} +1 -1
- package/dist/{chunk-1ap3vcrr.js → chunk-jxx9mctk.js} +2 -2
- package/dist/{chunk-1ap3vcrr.js.map → chunk-jxx9mctk.js.map} +1 -1
- package/dist/{chunk-mj429x94.js → chunk-k87tqe29.js} +2 -2
- package/dist/{chunk-mj429x94.js.map → chunk-k87tqe29.js.map} +1 -1
- package/dist/{chunk-1k4rvfza.js → chunk-kbw6y0ag.js} +2 -2
- package/dist/{chunk-1k4rvfza.js.map → chunk-kbw6y0ag.js.map} +1 -1
- package/dist/{chunk-pr2enaz5.js → chunk-krdq5s4y.js} +2 -2
- package/dist/{chunk-pr2enaz5.js.map → chunk-krdq5s4y.js.map} +1 -1
- package/dist/{chunk-7ysw97gp.js → chunk-m6sj1q1q.js} +2 -2
- package/dist/{chunk-7ysw97gp.js.map → chunk-m6sj1q1q.js.map} +1 -1
- package/dist/{chunk-hgvt5084.js → chunk-m950vw4c.js} +2 -2
- package/dist/{chunk-hgvt5084.js.map → chunk-m950vw4c.js.map} +1 -1
- package/dist/{chunk-873k84dt.js → chunk-mm45shzv.js} +2 -2
- package/dist/{chunk-873k84dt.js.map → chunk-mm45shzv.js.map} +1 -1
- package/dist/{chunk-6q15sx3h.js → chunk-p56zntmt.js} +3 -3
- package/dist/{chunk-6q15sx3h.js.map → chunk-p56zntmt.js.map} +1 -1
- package/dist/{chunk-p97w2388.js → chunk-q3511sb5.js} +2 -2
- package/dist/{chunk-p97w2388.js.map → chunk-q3511sb5.js.map} +1 -1
- package/dist/{chunk-kfdy4vv1.js → chunk-q788x8pm.js} +2 -2
- package/dist/{chunk-kfdy4vv1.js.map → chunk-q788x8pm.js.map} +1 -1
- package/dist/{chunk-23670kw5.js → chunk-rpdekb8t.js} +2 -2
- package/dist/{chunk-23670kw5.js.map → chunk-rpdekb8t.js.map} +1 -1
- package/dist/{chunk-j7k0nzqz.js → chunk-s4fb4njt.js} +2 -2
- package/dist/{chunk-j7k0nzqz.js.map → chunk-s4fb4njt.js.map} +1 -1
- package/dist/{chunk-7yh908jj.js → chunk-s71e6k9m.js} +3 -3
- package/dist/{chunk-7yh908jj.js.map → chunk-s71e6k9m.js.map} +1 -1
- package/dist/{chunk-6eb6jgdv.js → chunk-sdn3dmpp.js} +4 -4
- package/dist/{chunk-6eb6jgdv.js.map → chunk-sdn3dmpp.js.map} +1 -1
- package/dist/{chunk-qnv9w5g5.js → chunk-skv12k0x.js} +2 -2
- package/dist/{chunk-qnv9w5g5.js.map → chunk-skv12k0x.js.map} +1 -1
- package/dist/{chunk-fxd7pqk3.js → chunk-sp77zwpn.js} +2 -2
- package/dist/{chunk-fxd7pqk3.js.map → chunk-sp77zwpn.js.map} +1 -1
- package/dist/{chunk-82jhqxx7.js → chunk-sv86v56c.js} +3 -3
- package/dist/{chunk-82jhqxx7.js.map → chunk-sv86v56c.js.map} +1 -1
- package/dist/{chunk-bym06a64.js → chunk-sxf94q13.js} +2 -2
- package/dist/{chunk-bym06a64.js.map → chunk-sxf94q13.js.map} +1 -1
- package/dist/{chunk-pd3qbf8r.js → chunk-ta2wsjz6.js} +2 -2
- package/dist/{chunk-pd3qbf8r.js.map → chunk-ta2wsjz6.js.map} +1 -1
- package/dist/{chunk-58k1zstz.js → chunk-thbs63gy.js} +1 -1
- package/dist/{chunk-71prz4rp.js → chunk-vfvjfw5k.js} +2 -2
- package/dist/{chunk-71prz4rp.js.map → chunk-vfvjfw5k.js.map} +1 -1
- package/dist/{chunk-sca3tpce.js → chunk-vnk4vaer.js} +3 -3
- package/dist/{chunk-sca3tpce.js.map → chunk-vnk4vaer.js.map} +1 -1
- package/dist/{chunk-rzqxkm9r.js → chunk-wp9hw3we.js} +2 -2
- package/dist/{chunk-rzqxkm9r.js.map → chunk-wp9hw3we.js.map} +1 -1
- package/dist/{chunk-4w9gbe11.js → chunk-wt1yzzbw.js} +1 -1
- package/dist/{chunk-d29dcs3e.js → chunk-xkas0yp8.js} +3 -3
- package/dist/{chunk-d29dcs3e.js.map → chunk-xkas0yp8.js.map} +1 -1
- package/dist/{chunk-j1yhtwsk.js → chunk-y3s05q6b.js} +2 -2
- package/dist/{chunk-j1yhtwsk.js.map → chunk-y3s05q6b.js.map} +1 -1
- package/dist/{chunk-ndawdgtt.js → chunk-ys8nk9ga.js} +3 -3
- package/dist/{chunk-ndawdgtt.js.map → chunk-ys8nk9ga.js.map} +3 -3
- package/dist/{chunk-0gzqhjyg.js → chunk-z4dhd5pk.js} +2 -2
- package/dist/{chunk-0gzqhjyg.js.map → chunk-z4dhd5pk.js.map} +1 -1
- package/dist/{chunk-xxbkp90v.js → chunk-z5g56ds0.js} +3 -3
- package/dist/{chunk-xxbkp90v.js.map → chunk-z5g56ds0.js.map} +1 -1
- package/dist/{chunk-bzrhc7q3.js → chunk-zqptpk90.js} +2 -2
- package/dist/{chunk-bzrhc7q3.js.map → chunk-zqptpk90.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/http/requestDomain.d.ts.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/forwardedFor.d.ts +3 -3
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/DomainResolver.d.ts +20 -9
- package/dist/services/router/DomainResolver.d.ts.map +1 -1
- package/dist/services/router/DomainRouter.d.ts +2 -1
- package/dist/services/router/DomainRouter.d.ts.map +1 -1
- package/dist/services/router/config.d.ts +30 -1
- package/dist/services/router/config.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-8v6y52et.js +0 -5
- /package/dist/{chunk-fnj2hc5v.js.map → chunk-3rp908gn.js.map} +0 -0
- /package/dist/{chunk-tms2g9at.js.map → chunk-777v6242.js.map} +0 -0
- /package/dist/{chunk-8f4jkpv7.js.map → chunk-8hfyscnn.js.map} +0 -0
- /package/dist/{chunk-xed7yf6h.js.map → chunk-hgpvfhtp.js.map} +0 -0
- /package/dist/{chunk-58k1zstz.js.map → chunk-thbs63gy.js.map} +0 -0
- /package/dist/{chunk-4w9gbe11.js.map → chunk-wt1yzzbw.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$b as
|
|
3
|
-
`)}function
|
|
2
|
+
import{$b as $8,$c as J6,Ac as t9,Bc as r9,Cc as C8,Ec as _8,Fc as T8,Gc as A8,Hc as R8,Ic as E8,Jc as j8,Kc as k8,Lc as x8,Mc as q8,Nc as I8,Oc as w8,Pc as b8,Rc as w,Sc as $9,Tc as s,Uc as T,Vc as Z8,Wc as s0,Xc as a0,Yb as J8,Yc as t0,Zb as NQ,Zc as r0,_b as UQ,_c as e0,ad as $6,bd as Q6,cc as xJ,cd as Z6,dc as S,dd as W6,ec as A,ed as K6,fd as DJ,gc as t8,gd as X6,hc as d8,hd as AQ,ic as KJ,id as Y6,jc as o0,jd as RQ,kc as g,kd as G6,lc as Q8,ld as EJ,mc as LQ,md as B$,nc as OQ,nd as V6,oc as CQ,od as H6,pc as m,pd as EQ,qc as _Q,qd as z6,rc as oJ,rd as D6,sc as MQ,sd as B6,tc as SQ,td as z$,uc as sJ,vc as U8,wc as L8,yc as O8,zc as v}from"../chunk-2xtkh8bh.js";import{Ld as D8}from"../chunk-9aj6eavs.js";import"../chunk-gjwf07hy.js";import{$h as i0,Gh as zQ,Hi as FQ,Jh as BQ,Ki as p$,Oi as PQ,Zh as _9,_h as d0,ai as n0,bi as q}from"../chunk-ys8nk9ga.js";import{Pi as DQ,Ri as iJ,Si as nJ}from"../chunk-5n21z4n8.js";import{$i as h}from"../chunk-1h6g1hkg.js";import"../chunk-jxx9mctk.js";import"../chunk-6t1t7h05.js";import"../chunk-a9frf7ym.js";import{ck as n,dk as o,rk as SJ}from"../chunk-gwphn604.js";import"../chunk-m950vw4c.js";import"../chunk-vfvjfw5k.js";import{el as c9}from"../chunk-8b9ks729.js";import"../chunk-0q65jzhv.js";import"../chunk-9akefv1y.js";import{xl as eJ}from"../chunk-rpdekb8t.js";import"../chunk-9wcv7e1a.js";import{existsSync as wQ,readdirSync as P6,readFileSync as V8}from"fs";import{isAbsolute as bQ,join as UJ,relative as fQ,sep as vQ}from"path";var H8="prompts.json",yQ=/\{\{>\s*([\w./-]+)\s*\}\}/g,X8=/\{\{(\w+)\}\}/g,hQ=/^[\w-]+(\/[\w-]+)*$/,Y8={dir:"app/agents",shared:"prompts"},OJ={},tJ=new Map,LJ;function gQ(){if(LJ===void 0){let J=UJ(eJ(),"dist","server",H8);LJ=wQ(J)?JSON.parse(V8(J,"utf8")):null}return LJ??null}function uQ(J){return J.replace(/\r?\n$/,"")}function G8(){return OJ.cache??Bun.env.NODE_ENV==="production"}function cQ(J){if(!hQ.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let $=OJ.dir??Y8.dir,Q=bQ($)?$:UJ(process.cwd(),$),Z=J.includes("/")?`${J}.md`:UJ(OJ.shared??Y8.shared,`${J}.md`);return UJ(Q,Z)}function mQ(J){let $=cQ(J),Q=G8()?tJ.get($):void 0;if(Q!==void 0)return Q;let Z=Bun.env.NODE_ENV==="production";if(Z){let K=gQ()?.[fQ(eJ(),$).split(vQ).join("/")];if(K!==void 0)return K}let W;try{W=uQ(V8($,"utf8"))}catch(K){if(K.code==="ENOENT"){let X=Z?` or in dist/server/${H8}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${$}${X}).`)}throw K}if(G8())tJ.set($,W);return W}function rJ(J,$){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return mQ(J).replace(yQ,(Q,Z)=>rJ(Z,[...$,J]))}class z8{static configure(J){OJ={...J},tJ.clear(),LJ=void 0}static render(J,$={}){return rJ(J,[]).replace(X8,(Q,Z)=>{if(!Object.hasOwn($,Z))throw Error(`The prompt "${J}" has no value for {{${Z}}}.`);return String($[Z])})}static placeholders(J){let $=[...rJ(J,[]).matchAll(X8)].map((Q)=>Q[1]);return[...new Set($)]}}class J$ extends D8{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await v.sweep({limit:100})===100);}}var CJ=20;function F8(J,$){if($<=0||J.length===0)return null;let Q=(K,X)=>X.createdAt-K.createdAt||(K.id<X.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.",...[...J.filter((K)=>K.state==="running").sort(Q),...J.filter((K)=>K.state!=="running").sort(Q)].slice(0,$).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="running")X.push(`running since ${$$(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${$$(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${B8(K.error.message,200)}`:"failed";X.push(`failed at ${$$(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${B8(JSON.stringify(K.summary),300)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
|
|
3
|
+
`)}function $$(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function B8(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}class Z${table;sql;dialect;connection;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of pQ(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return SJ(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=this.q(),Q=this.clock($);await $`
|
|
4
4
|
INSERT INTO ${this.name($)}
|
|
5
5
|
(id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
|
|
6
6
|
orphaned, attachment_scope, created_at, updated_at, deadline_at)
|
|
7
7
|
VALUES
|
|
8
8
|
(${J.id}, ${J.threadId}, ${J.runId}, ${J.toolCallId}, ${J.toolName},
|
|
9
|
-
${J.owner}, ${J.job}, ${
|
|
9
|
+
${J.owner}, ${J.job}, ${_J(J.summary)}, 'running', 0, ${J.attachmentScope},
|
|
10
10
|
${Q}, ${Q}, ${Q} + ${this.ms($,J.deadlineMs)})
|
|
11
|
-
`;let Z=await this.get(J.id);if(!Z)throw Error(`The background job ${J.id} was not found after it was written.`);return Z}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?
|
|
11
|
+
`;let Z=await this.get(J.id);if(!Z)throw Error(`The background job ${J.id} was not found after it was written.`);return Z}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?Q$(Q[0]):null}async listForThread(J,$={}){let Q=this.q(),Z=$.states===void 0?Q`1 = 1`:$.states.length===0?Q`1 = 0`:Q`state IN (${P8(Q,$.states)})`;return($.limit===void 0?await Q`
|
|
12
12
|
SELECT * FROM ${this.name(Q)}
|
|
13
13
|
WHERE thread_id = ${J} AND ${Z}
|
|
14
14
|
ORDER BY created_at DESC, id DESC
|
|
@@ -17,18 +17,18 @@ import{$b as e$,$c as d0,Ac as n9,Bc as o9,Cc as N8,Ec as U8,Fc as S8,Gc as C8,H
|
|
|
17
17
|
WHERE thread_id = ${J} AND ${Z}
|
|
18
18
|
ORDER BY created_at DESC, id DESC
|
|
19
19
|
LIMIT ${Math.max(0,Math.floor($.limit))}
|
|
20
|
-
`).map(
|
|
20
|
+
`).map(Q$)}async transition(J,$,Q){if($.length===0)return!1;let Z=this.q(),W=this.clock(Z),K=[Z`updated_at = ${W}`];if(Q.state!==void 0)K.push(Z`state = ${Q.state}`);if("output"in Q)K.push(Z`output = ${_J(Q.output)}`);if("error"in Q)K.push(Z`error = ${_J(Q.error)}`);if("usage"in Q)K.push(Z`${this.column(Z,"usage")} = ${_J(Q.usage)}`);if("orphaned"in Q)K.push(Z`orphaned = ${Q.orphaned?1:0}`);if(Q.state!==void 0&&Q.state!=="running")K.push(Q.settledAt!==void 0?Z`settled_at = COALESCE(settled_at, ${this.ms(Z,Q.settledAt)})`:Z`settled_at = COALESCE(settled_at, ${W})`);let X=K.reduce((V,Y)=>Z`${V}, ${Y}`),G=await Z`
|
|
21
21
|
UPDATE ${this.name(Z)} SET ${X}
|
|
22
|
-
WHERE id = ${J} AND state IN (${
|
|
23
|
-
`;return
|
|
22
|
+
WHERE id = ${J} AND state IN (${P8(Z,$)})
|
|
23
|
+
`;return N8(G)>0}async overdue(J,$){let Q=this.q();return(await Q`
|
|
24
24
|
SELECT * FROM ${this.name(Q)}
|
|
25
25
|
WHERE state = 'running' AND deadline_at <= ${this.ms(Q,J)}
|
|
26
26
|
ORDER BY deadline_at, id
|
|
27
27
|
LIMIT ${Math.max(0,Math.floor($))}
|
|
28
|
-
`).map(
|
|
28
|
+
`).map(Q$)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async prune(J){let $=this.q(),Q=await $`
|
|
29
29
|
DELETE FROM ${this.name($)}
|
|
30
30
|
WHERE state <> 'running' AND settled_at <= ${this.clock($)} - ${this.ms($,J)}
|
|
31
|
-
`;return
|
|
31
|
+
`;return N8(Q)}joinable(){if(this.connection===void 0)return;let J=n();if(J===void 0||o()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function P8(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function _J(J){return J===void 0?null:JSON.stringify(J)}function MJ(J){if(J===null||J===void 0)return;return JSON.parse(String(J))}function Q$(J){let $=MJ(J.summary),Q=MJ(J.output),Z=MJ(J.error),W=MJ(J.usage);return{id:String(J.id),threadId:String(J.thread_id),runId:String(J.run_id),toolCallId:String(J.tool_call_id),toolName:String(J.tool_name),owner:J.owner===null||J.owner===void 0?null:String(J.owner),job:J.job===null||J.job===void 0?null:String(J.job),...$!==void 0?{summary:$}:{},state:String(J.state),...Q!==void 0?{output:Q}:{},...Z!==void 0?{error:Z}:{},...W!==void 0?{usage:W}:{},...Number(J.orphaned)===1?{orphaned:!0}:{},attachmentScope:J.attachment_scope===null||J.attachment_scope===void 0?null:String(J.attachment_scope),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),deadlineAt:Number(J.deadline_at),...J.settled_at===null||J.settled_at===void 0?{}:{settledAt:Number(J.settled_at)}}}function N8(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function pQ(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
32
32
|
\`id\` VARCHAR(191) NOT NULL,
|
|
33
33
|
\`thread_id\` VARCHAR(191) NOT NULL,
|
|
34
34
|
\`run_id\` VARCHAR(191) NOT NULL,
|
|
@@ -72,7 +72,7 @@ import{$b as e$,$c as d0,Ac as n9,Bc as o9,Cc as N8,Ec as U8,Fc as S8,Gc as C8,H
|
|
|
72
72
|
"updated_at" BIGINT NOT NULL,
|
|
73
73
|
"deadline_at" BIGINT NOT NULL,
|
|
74
74
|
"settled_at" BIGINT${Z}
|
|
75
|
-
)`,`CREATE INDEX IF NOT EXISTS "${$}_thread_id_created_at_idx" ON "${$}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_state_deadline_at_idx" ON "${$}"("state", "deadline_at")`]}var
|
|
75
|
+
)`,`CREATE INDEX IF NOT EXISTS "${$}_thread_id_created_at_idx" ON "${$}"("thread_id", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_state_deadline_at_idx" ON "${$}"("state", "deadline_at")`]}var M8=4;class K${table;sql;dialect;connection;constructor(J,$={}){let Q=$.table??"gemi_agent_memories";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent memories table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of lQ(this.dialect,this.table))await this.sql.unsafe(J)}async list(J,$={}){if(J.length===0)return[];if($.kinds!==void 0&&$.kinds.length===0)return[];let Q=this.q(),Z=[Q`scope IN (${QJ(Q,J)})`];if($.kinds!==void 0)Z.push(Q`kind IN (${QJ(Q,$.kinds)})`);if(!$.includeExpired)Z.push(Q`(expires_at IS NULL OR expires_at > ${this.clock(Q)})`);if($.after!==void 0){let[V]=await Q`
|
|
76
76
|
SELECT created_at, id FROM ${this.name(Q)}
|
|
77
77
|
WHERE id = ${$.after} AND scope IN (${QJ(Q,J)})
|
|
78
78
|
`;if(V){let Y=this.ms(Q,Number(V.created_at));Z.push(Q`(created_at > ${Y} OR (created_at = ${Y} AND id > ${String(V.id)}))`)}}let W=Z.reduce((V,Y)=>Q`${V} AND ${Y}`),K=$.limit===void 0||$.tags!==void 0?void 0:Math.max(0,Math.floor($.limit)),G=(K===void 0?await Q`
|
|
@@ -82,16 +82,16 @@ import{$b as e$,$c as d0,Ac as n9,Bc as o9,Cc as N8,Ec as U8,Fc as S8,Gc as C8,H
|
|
|
82
82
|
SELECT * FROM ${this.name(Q)} WHERE ${W}
|
|
83
83
|
ORDER BY created_at, id
|
|
84
84
|
LIMIT ${K}
|
|
85
|
-
`).map(
|
|
85
|
+
`).map(W$);if($.tags!==void 0){if(G=G.filter((V)=>R8(V,$.tags)),$.limit!==void 0)G=G.slice(0,Math.max(0,Math.floor($.limit)))}return G}async get(J){let $=this.q(),Q=await $`SELECT * FROM ${this.name($)} WHERE id = ${J}`;return Q[0]?W$(Q[0]):null}async upsert(J){let $=J.key??null;if($===null)return await this.insert(J,null),{record:await this.mustGet(J.id),action:"added"};for(let Q=1;;Q++){let Z=await this.atKey(J.scope,$);if(Z){if(E8(Z,J))return{record:Z,action:"unchanged"};let W=await this.update(Z.id,{kind:J.kind,content:J.content,tags:J.tags??[],pinned:J.pinned??!1,expiresAt:J.expiresAt??null},Z.version);if(W)return{record:W,action:"updated"}}else try{return await this.insert(J,$),{record:await this.mustGet(J.id),action:"added"}}catch(W){if(Q>=M8||!await this.atKey(J.scope,$))throw W}if(Q>=M8)throw Error(`The memory at "${$}" in ${J.scope} kept changing while it was being written.`)}}async update(J,$,Q){let Z=this.q(),W=[Z`version = version + 1`,Z`updated_at = ${this.clock(Z)}`];if($.kind!==void 0)W.push(Z`kind = ${$.kind}`);if($.content!==void 0)W.push(Z`content = ${$.content}`);if($.key!==void 0)W.push(Z`${this.column(Z,"key")} = ${$.key}`);if($.tags!==void 0)W.push(Z`tags = ${JSON.stringify($.tags)}`);if($.pinned!==void 0)W.push(Z`pinned = ${$.pinned?1:0}`);if($.expiresAt!==void 0)W.push($.expiresAt===null?Z`expires_at = NULL`:Z`expires_at = ${this.ms(Z,$.expiresAt)}`);let K=W.reduce((G,V)=>Z`${G}, ${V}`),X=Q===void 0?await Z`UPDATE ${this.name(Z)} SET ${K} WHERE id = ${J}`:await Z`
|
|
86
86
|
UPDATE ${this.name(Z)} SET ${K}
|
|
87
87
|
WHERE id = ${J} AND version = ${Math.floor(Q)}
|
|
88
|
-
`;if(
|
|
88
|
+
`;if(AJ(X)===0)return null;return this.get(J)}async delete(J){if(J.length===0)return 0;let $=this.q(),Q=await $`DELETE FROM ${this.name($)} WHERE id IN (${QJ($,[...new Set(J)])})`;return AJ(Q)}async deleteScope(J){let $=this.q();return AJ(await $`DELETE FROM ${this.name($)} WHERE scope = ${J}`)}async search(J,$,Q={}){let Z=await this.list(J,{kinds:Q.kinds,tags:Q.tags});return A8(Z,$,Q.limit)}async count(J){let $=this.q(),[Q]=await $`
|
|
89
89
|
SELECT COUNT(*) AS total FROM ${this.name($)}
|
|
90
90
|
WHERE scope = ${J} AND (expires_at IS NULL OR expires_at > ${this.clock($)})
|
|
91
91
|
`;return Number(Q?.total??0)}async touch(J,$){if(J.length===0)return;let Q=this.q();await Q`
|
|
92
92
|
UPDATE ${this.name(Q)} SET last_used_at = ${this.ms(Q,$)}
|
|
93
93
|
WHERE id IN (${QJ(Q,[...new Set(J)])})
|
|
94
|
-
`}async prune(J){let $=this.q();return
|
|
94
|
+
`}async prune(J){let $=this.q();return AJ(await $`DELETE FROM ${this.name($)} WHERE expires_at IS NOT NULL AND expires_at <= ${this.ms($,J)}`)}async now(){let J=this.q(),[$]=await J`SELECT ${this.clock(J)} AS now`;return Number($.now)}async insert(J,$){let Q=this.q(),Z=this.clock(Q),W=J.expiresAt===void 0||J.expiresAt===null?null:Math.max(0,Math.round(J.expiresAt));await Q`
|
|
95
95
|
INSERT INTO ${this.name(Q)}
|
|
96
96
|
(id, scope, kind, ${this.column(Q,"key")}, content, tags, pinned, source, version,
|
|
97
97
|
created_at, updated_at, expires_at)
|
|
@@ -102,7 +102,7 @@ import{$b as e$,$c as d0,Ac as n9,Bc as o9,Cc as N8,Ec as U8,Fc as S8,Gc as C8,H
|
|
|
102
102
|
${W===null?null:this.ms(Q,W)})
|
|
103
103
|
`}async atKey(J,$){let Q=this.q(),Z=await Q`
|
|
104
104
|
SELECT * FROM ${this.name(Q)} WHERE scope = ${J} AND ${this.column(Q,"key")} = ${$}
|
|
105
|
-
`;return Z[0]?
|
|
105
|
+
`;return Z[0]?W$(Z[0]):null}async mustGet(J){let $=await this.get(J);if(!$)throw Error(`The memory ${J} was not found after it was written.`);return $}joinable(){if(this.connection===void 0)return;let J=n();if(J===void 0||o()!==this.connection)return;return J}q(){return this.joinable()??this.sql}column(J,$){let Q=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe(Q?`\`${$}\``:`"${$}"`)}name(J){let $=this.dialect==="mysql"||this.dialect==="mariadb";return J.unsafe($?`\`${this.table}\``:`"${this.table}"`)}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function QJ(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function S8(J,$){if(J===null||J===void 0||J==="")return $;try{return JSON.parse(String(J))}catch{return $}}function W$(J){let $=S8(J.tags,[]);return{id:String(J.id),scope:String(J.scope),kind:String(J.kind),content:String(J.content),key:J.key===null||J.key===void 0?null:String(J.key),tags:Array.isArray($)?$.map(String):[],pinned:Number(J.pinned)===1,source:S8(J.source,{by:"app"}),version:Number(J.version),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at),lastUsedAt:J.last_used_at===null||J.last_used_at===void 0?null:Number(J.last_used_at),expiresAt:J.expires_at===null||J.expires_at===void 0?null:Number(J.expires_at)}}function AJ(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function lQ(J,$){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
106
106
|
\`id\` VARCHAR(191) NOT NULL,
|
|
107
107
|
\`scope\` VARCHAR(191) NOT NULL,
|
|
108
108
|
\`kind\` VARCHAR(191) NOT NULL,
|
|
@@ -139,22 +139,22 @@ import{$b as e$,$c as d0,Ac as n9,Bc as o9,Cc as N8,Ec as U8,Fc as S8,Gc as C8,H
|
|
|
139
139
|
"updated_at" BIGINT NOT NULL,
|
|
140
140
|
"last_used_at" BIGINT,
|
|
141
141
|
"expires_at" BIGINT${Z}
|
|
142
|
-
)`,`CREATE INDEX IF NOT EXISTS "${$}_scope_kind_created_at_idx" ON "${$}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${$}_scope_key_key" ON "${$}"("scope", "key")`]}var I8={n:0,mean:0,stddev:0,low:null,high:null};function y(J){let $=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if(J<0.5)return Math.log(Math.PI/Math.sin(Math.PI*J))-y(1-J);J-=1;let Q=$[0],Z=J+7.5;for(let W=1;W<9;W++)Q+=$[W]/(J+W);return 0.5*Math.log(2*Math.PI)+(J+0.5)*Math.log(Z)-Z+Math.log(Q)}function q8(J,$,Q){let W=1,K=1-(J+$)*Q/(J+1);if(Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let X=K;for(let G=1;G<=300;G++){let V=2*G,Y=G*($-G)*Q/((J+V-1)*(J+V));if(K=1+Y*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+Y/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(K=1/K,X*=K*W,Y=-(J+G)*(J+$+G)*Q/((J+V)*(J+V+1)),K=1+Y*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+Y/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let H=K*W;if(X*=H,Math.abs(H-1)<0.00000000000001)break}return X}function vQ(J,$,Q){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(y($+Q)-y($)-y(Q)+$*Math.log(J)+Q*Math.log(1-J));return J<($+1)/($+Q+2)?Z*q8($,Q,J)/$:1-Z*q8(Q,$,1-J)/Q}function W$(J,$){return vQ($/($+J*J),$/2,0.5)}function yQ(J){if(!(J>0))return Number.POSITIVE_INFINITY;let $=1.959964,Q=2;while(W$(Q,J)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=($+Q)/2;if(W$(W,J)>0.05)$=W;else Q=W}return($+Q)/2}function hQ(J,$,Q,Z){let W=J+Q,K=$+Z,X=(H,D)=>y(H+1)-y(D+1)-y(H-D+1),G=(H)=>Math.exp(X($,H)+X(Z,W-H)-X(K,W)),V=G(J),Y=0;for(let H=Math.max(0,W-Z);H<=Math.min($,W);H++){let D=G(H);if(D<=V*1.0000001)Y+=D}return Math.min(1,Y)}function w8(J,$){if(J.length<2)return 0;let Q=J.reduce((W,K)=>W+(K-$)**2,0),Z=Math.sqrt(Q/(J.length-1));return Z<0.000000000001*Math.max(1,Math.abs($))?0:Z}function K$(J){let $=J.length;if($===0)return I8;let Q=J.map((G)=>G?1:0),Z=Q.reduce((G,V)=>G+V,0)/$,W=3.841458881296,K=(Z+W/(2*$))/(1+W/$),X=1.959964*Math.sqrt(Z*(1-Z)/$+W/(4*$*$))/(1+W/$);return{n:$,mean:Z,stddev:w8(Q,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function X$(J){let $=J.length;if($===0)return I8;let Q=J.reduce((K,X)=>K+X,0)/$,Z=w8(J,Q);if($<2||Z===0)return{n:$,mean:Q,stddev:Z,low:null,high:null};let W=yQ($-1)*Z/Math.sqrt($);return{n:$,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function ZJ(J,$,Q){return{before:J.mean,after:$.mean,delta:$.mean-J.mean,p:Q,pAdjusted:Q,significant:!1}}function b8(J,$){if(J.n===0||$.n===0)return ZJ(J,$,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return ZJ(J,$,hQ(Q(J),J.n,Q($),$.n))}function f8(J,$){if(J.n<2||$.n<2)return ZJ(J,$,null);let Q=J.stddev**2/J.n,Z=$.stddev**2/$.n,W=Math.sqrt(Q+Z);if(W===0)return ZJ(J,$,null);let K=(Q+Z)**2/(Q**2/(J.n-1)+Z**2/($.n-1));return ZJ(J,$,W$(($.mean-J.mean)/W,K))}function v8(J,$,Q){if(Q==="holm"){let Z=J.filter((K)=>K.p!==null).sort((K,X)=>K.p-X.p),W=0;Z.forEach((K,X)=>{W=Math.max(W,Math.min(1,K.p*(Z.length-X))),K.pAdjusted=W})}else for(let Z of J)Z.pAdjusted=Z.p;for(let Z of J)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<$&&Z.delta!==0}class SJ{name;cases;runs;concurrency;graders;pricing;task;constructor(J){this.name=J.name,this.cases=J.cases,this.runs=J.runs??1,this.concurrency=J.concurrency??1,this.task=J.task,this.graders=typeof J.graders==="function"?J.graders({judge:($)=>SJ.judge($)}):J.graders,this.pricing=J.pricing}static create(J){let $=`The eval "${J.name}"`;WJ(J.runs,$,"runs"),WJ(J.concurrency,$,"concurrency");let Q=new Set;for(let W of J.cases){if(Q.has(W.id))throw Error(`${$} has two cases with the id "${W.id}".`);Q.add(W.id)}let Z=new SJ(J);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")WJ(K.samples,`${$}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,$,Q={}){return m8(J,$,Q)}static format(J,$={}){return mQ(J,$)}async run(J={}){let $=`${this.name}.run`;WJ(J.runs,$,"runs"),WJ(J.concurrency,$,"concurrency");let Q=J.only?new Set(J.only):null;if(Q){let B=[...Q].filter((P)=>!this.cases.some((L)=>L.id===P));if(B.length>0)throw Error(`The eval "${this.name}" has no case ${B.map((P)=>`"${P}"`).join(", ")}.`)}let Z=J.runs??this.runs,W=Date.now(),K=new AbortController,X=J.signal?AbortSignal.any([J.signal,K.signal]):K.signal,G=this.cases.filter((B)=>!Q||Q.has(B.id)),V={};for(let[B,P]of Object.entries(this.graders)){if(X.aborted)break;if(typeof P==="function"||P.kind!=="judge"||!P.calibration)continue;V[B]=await this.calibrate(P,X)}let Y=G.flatMap((B)=>Array.from({length:Z},(P,L)=>({test:B,run:L+1}))),H=Array.from({length:Y.length}),D=0,z,F=async()=>{while(D<Y.length&&!X.aborted){let B=D++,P=Y[B],L=await this.sample(P.test,P.run,X,J.keepOutputs??!1);H[B]=L;try{J.onSample?.(L)}catch(O){z??={error:O},K.abort(O)}}},U=Math.min(J.concurrency??this.concurrency,Y.length);if(await Promise.all(Array.from({length:U},F)),z)throw z.error;let N=H.filter((B)=>B!==void 0);return this.report(N,V,Z,new Date(W).toISOString(),Date.now()-W,{aborted:X.aborted||N.length<Y.length,planned:G.map((B)=>B.id)})}async sample(J,$,Q,Z){let W=Date.now(),K,X,G=await KJ(async()=>{try{K=await this.task(J.input,{case:J,run:$,signal:Q})}catch(U){X=l8(U)}}),V={},Y=!1,H=await KJ(async()=>{if(X!==void 0)return;let U={case:J,input:J.input,run:$};for(let[N,B]of Object.entries(this.graders)){if(J.skip?.includes(N))continue;let P=await y8(B,K,U,Q);if(!P)continue;if(V[N]=P,!P.pass&&typeof B!=="function"&&B.gate)Y=!0}}),D=Object.values(V).map((U)=>U.score),z=X===void 0&&D.length===0,F=this.pricing?Y$(this.pricing,G.byModel).cost+Y$(this.pricing,H.byModel).cost:void 0;return{case:J.id,run:$,pass:X===void 0&&!z&&Object.values(V).every((U)=>U.pass),excluded:Y||z,...z?{ungraded:!0}:{},score:X!==void 0||z?0:p8(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:G.usage,byModel:uQ(G.byModel,H.byModel),judgeUsage:H.usage,...F!==void 0?{cost:F}:{},durationMs:Date.now()-W}}async calibrate(J,$){let Q=J.calibration,Z=[],W=0,K=await KJ(async()=>{for(let[V,Y]of Q.examples.entries()){if($.aborted)break;let H=Y.id??`example-${V+1}`,D={case:{id:H,input:Y.input},input:Y.input,run:0},z=await y8(J,Y.output,D,$),F=z?.pass??!1;if(F===Y.expected)W++;else Z.push({id:H,expected:Y.expected,got:F,...z?.note?{note:z.note}:{}})}}),X=Q.examples.length,G=X===0?1:W/X;return{n:X,agreement:G,ok:G>=(Q.minAgreement??0.8),disagreements:Z,usage:K.usage}}report(J,$,Q,Z,W,K){let X=new Set(Object.entries(this.graders).filter(([,z])=>typeof z!=="function"&&z.gate).map(([z])=>z)),G={};for(let z of this.cases){let F=J.filter((U)=>U.case===z.id);if(F.length===0)continue;G[z.id]={...h8(F),graders:g8(F,X)}}let V=S(),Y=S(),H={};for(let z of J){V=A(V,z.usage),Y=A(Y,z.judgeUsage);for(let[F,U]of Object.entries(z.byModel))H[F]=A(H[F]??S(),U)}let D=this.pricing?Y$(this.pricing,H):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:Q,aborted:K.aborted,planned:K.planned,samples:J,cases:G,graders:g8(J,X),calibration:$,totals:{...h8(J),usage:V,judgeUsage:Y,byModel:H,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(H)}}}}async function y8(J,$,Q,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return G$(await J($,Q),W);if(J.kind!=="judge")return G$(await J.check($,Q),W);return await gQ(J,$,Q,W,Z)}catch(K){return{pass:!1,score:0,error:l8(K)}}}async function gQ(J,$,Q,Z,W){let K=await J.prompt($,Q),X=typeof K==="string"?{prompt:K}:K,G=[];for(let D=0;D<(J.samples??1)&&!W.aborted;D++){let z=await V$({signal:W,provider:J.provider,...J.instructions!==void 0?{instructions:J.instructions}:{},...X,output:J.output,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},...J.maxOutputTokens!==void 0?{maxOutputTokens:J.maxOutputTokens}:{},...J.temperature!==void 0?{temperature:J.temperature}:{},logErrors:!1});if(!z.ok){G.push({pass:!1,score:0,error:`The judge failed: ${z.error.message}`});continue}let F=G$(J.verdict(z.output,Q),Z);if(F)G.push(F)}if(G.length===0)return null;if(G.length===1)return G[0];let V=G.filter((D)=>D.pass).length,Y=G.map((D)=>D.note??D.error).filter(Boolean),H=G.map((D)=>D.error).filter(Boolean);return{pass:V*2>G.length,score:p8(G.map((D)=>D.score)),...Y.length>0?{note:Y.join(" | ")}:{},...H.length===G.length?{error:H.join(" | ")}:{}}}function G$(J,$){if(J===null||J===void 0)return null;if(typeof J==="boolean")return{pass:J,score:J?1:0};if(typeof J==="number"){if(!Number.isFinite(J))throw Error(`A grader answered the score ${J}.`);let Q=u8(J);return{pass:Q>=$,score:Q}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:u8(J.score),...J.note!==void 0?{note:J.note}:{}}}function h8(J){let $=J.filter((Q)=>!Q.excluded);return{samples:J.length,kept:$.length,passed:$.filter((Q)=>Q.pass).length,errors:J.filter((Q)=>Q.error!==void 0).length,passRate:K$($.map((Q)=>Q.pass)),score:X$($.map((Q)=>Q.score))}}function g8(J,$){let Q=J.filter((W)=>!W.excluded),Z=[...new Set(J.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let X=($.has(W)?J:Q).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:K$(X.map((G)=>G.pass)),score:X$(X.map((G)=>G.score))}]}))}function Y$(J,$){let Q=0,Z=[];for(let[W,K]of Object.entries($)){let X=c8(J,W,K);if(X===void 0){Z.push(W);continue}Q+=X}return{cost:Q,unpriced:Z}}function uQ(...J){let $={};for(let Q of J)for(let[Z,W]of Object.entries(Q))$[Z]=A($[Z]??S(),W);return $}function m8(J,$,Q){for(let[B,P]of[["baseline",J],["current report",$]])if(P.aborted)throw Error(`Eval.compare: the ${B} for "${P.name}" was aborted (${P.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`);let Z=Q.alpha??0.05,W=Q.adjust??"holm",K=[],X=(B,P,L)=>{let O={label:B,passRate:b8(P.passRate,L.passRate),score:f8(P.score,L.score)};return K.push(O),{passRate:O.passRate,score:O.score}},G=(B,P,L)=>Object.fromEntries(Object.keys(L).filter((O)=>(O in P)).map((O)=>[O,X(`${B} ${O}`,P[O],L[O])])),V=(B,P)=>({fromCurrent:B.filter((L)=>!P.includes(L)),fromBaseline:P.filter((L)=>!B.includes(L))}),Y=X("total",J.totals,$.totals),H=G("case",J.cases,$.cases),D=G("grader",J.graders,$.graders),z=K.flatMap((B)=>[B.passRate,B.score]);v8(z,Z,W);let F={cases:V([...new Set([...J.planned??[],...Object.keys(J.cases)])],[...new Set([...$.planned??[],...Object.keys($.cases)])]),graders:V(Object.keys(J.graders),Object.keys($.graders))},U=[...F.cases.fromCurrent.map((B)=>`case ${B}: in the baseline, missing from this report`),...F.graders.fromCurrent.map((B)=>`grader ${B}: in the baseline, missing from this report`)],N=[];for(let B of K)for(let[P,L]of[["pass rate",B.passRate],["score",B.score]]){if(!L.significant)continue;let O=`${B.label}: ${P} ${L.before.toFixed(2)} \u2192 ${L.after.toFixed(2)} (p = ${cQ(L.pAdjusted)})`;(L.delta<0?U:N).push(O)}return{totals:Y,cases:H,graders:D,missing:F,comparisons:z.filter((B)=>B.p!==null).length,alpha:Z,adjust:W,regressions:U,improvements:N}}function cQ(J){return J<0.001?"<0.001":J.toFixed(3)}function mQ(J,$){let Q=$.baseline&&!$.baseline.aborted&&!J.aborted?m8($.baseline,J,$):void 0,{totals:Z}=J,W=[];if(W.push(`eval ${J.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(J.durationMs/1000).toFixed(1)}s)`),J.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let K=(Y)=>{if(Y.n===0)return"-";let H=Y.mean.toFixed(2);if(Y.low===null||Y.high===null)return`${H} (${Y.n===1?"n=1":"no spread"})`;return`${H} [${Y.low.toFixed(2)}, ${Y.high.toFixed(2)}]`},X=(Y)=>Y?` ${Y.delta>=0?"+":""}${Y.delta.toFixed(2)}${Y.significant?"*":""}`:"",G=(Y,H)=>{let D=[0,1,2,3].map((F)=>Math.max(...[[Y,"n","pass rate","score"],...H].map((U)=>U[F].length))),z=(F)=>F.map((U,N)=>U.padEnd(D[N])).join(" ").trimEnd();W.push("",z([Y,"n","pass rate","score"]),...H.map(z))};G("case",Object.entries(J.cases).map(([Y,H])=>[Y,`${H.kept}/${H.samples}`,K(H.passRate)+X(Q?.cases[Y]?.passRate),K(H.score)+X(Q?.cases[Y]?.score)])),G("grader",Object.entries(J.graders).map(([Y,H])=>[Y,String(H.passRate.n),K(H.passRate)+X(Q?.graders[Y]?.passRate),K(H.score)+X(Q?.graders[Y]?.score)])),W.push("",`total pass rate ${K(Z.passRate)}${X(Q?.totals.passRate)} score ${K(Z.score)}${X(Q?.totals.score)}`);for(let[Y,H]of Object.entries(J.calibration))W.push(`judge ${Y}: agreement ${H.agreement.toFixed(2)} on ${H.n} examples${H.ok?"":" (BELOW minAgreement)"}`);let V=(Y)=>`${Y.inputTokens} in, ${Y.outputTokens} out`;if(W.push(`tokens: task ${V(Z.usage)}; judges ${V(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),Q){W.push("",`* significant at ${Q.alpha} over ${Q.comparisons} tests (${Q.adjust==="holm"?"Holm-adjusted":"unadjusted"}; Fisher's exact for pass rates, Welch's t for scores)`);for(let Y of Q.regressions)W.push(`regression: ${Y}`);for(let Y of Q.improvements)W.push(`improvement: ${Y}`)}return W.join(`
|
|
143
|
-
`)}function p8(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function u8(J){return Math.min(1,Math.max(0,J))}function l8(J){return J instanceof Error?J.message:String(J)}function WJ(J,$,Q){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${$} sets \`${Q}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var pQ=/^[A-Za-z0-9_-]{1,64}$/;function lQ(J,$){let Q=dQ($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((H)=>H$(J,H,Z));let K=Object.entries(Q.namespaces),X=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,D]of K){if(!pQ.test(H))throw Error(`toAgentTools: "${H}" 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 "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!X.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let G=new Map(K.map(([H])=>[H,[]])),V=[];for(let H of W){let D=K.find(([z])=>H.tags.includes(z))?.[0];if(D===void 0)V.push(H$(J,H,Z));else G.get(D).push(H$(J,H,!1))}let Y=[];for(let[H,D]of K){let z=G.get(H);if(z.length===0)continue;Y.push(z$.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...Y,...V]}function dQ(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function H$(J,$,Q){if($.kind==="tool")return iQ(J,$,Q);return AJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Q,execute:(Z,W)=>{let K=h.getStore()?.req;if(!K)throw new g(`"${$.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 J.execute({kind:"local",req:K},$.name,Z,W)}})}function iQ(J,$,Q){let Z=J.nativeTool($.name);return AJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:J.nativeApproval($.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,K)=>{let X=h.getStore()?.req;return J.startNative(X?{kind:"local",req:X}:void 0,$.name,W,K)}})}function nQ(J){if(J==="auto")return;let $=/^(\d+)x(\d+)$/.exec(J);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let Q=Number($[1]),Z=Number($[2]);if(Q%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max(Q/Z,Z/Q)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function d8(J,$){if(J.size!==void 0)try{nQ(J.size)}catch(Q){throw Error(`${$}: ${Q.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let Q=J.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Q}.`)}}function i8(J,$){if(J instanceof File)return J;let Q=J.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([J],`${$}.${Z}`,{type:Q})}class D${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;d8(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new D$(J)}async generate(J){let $=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...$,signal:J.signal}))}async edit(J){let $=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...$,images:J.images.map((Q,Z)=>i8(Q,`image-${Z}`)),...J.mask?{mask:i8(J.mask,"mask")}:{},signal:J.signal}))}present(J){return n8(this.provider.model,J.usage),oQ(J)}merge(J){let $={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return d8($,`ImageModel "${this.name}"`),$}}function oQ(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function u(J){return typeof process>"u"?void 0:process.env?.[J]}var sQ="preview";function o8(J){let $=J.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function aQ(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function XJ(J,$={}){return{base:(J.baseURL??u("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??u("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??$.timeoutMs??120000,maxRetries:J.maxRetries??2}}function s8(J){let $=J.baseURL??J.endpoint??u("AZURE_OPENAI_ENDPOINT");if($)return o8($);let Q=J.resourceName??u("AZURE_OPENAI_RESOURCE_NAME")??u("AZURE_RESOURCE_NAME");return Q?o8(`https://${Q.trim()}.cognitiveservices.azure.com`):""}function YJ(J,$={}){let Q=J.apiVersion??u("AZURE_OPENAI_API_VERSION")??sQ;return{base:`${s8(J)}${aQ(Q)}`,query:`?api-version=${encodeURIComponent(Q)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??u("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??$.timeoutMs??120000,maxRetries:J.maxRetries??2}}function a8(J,$={}){return{...YJ(J,$),base:`${s8(J)}/v1`,query:""}}var tQ=500,r8=20000;function rQ(J,$){if(!J)return;let Q=J.trim();if(/^\d+(\.\d+)?$/.test(Q))return Math.max(0,Number(Q)*1000);let Z=Date.parse(Q);if(Number.isNaN(Z))return;return Math.max(0,Z-$)}function RJ(J,$){let Q=Math.min(r8,tQ*2**J);return Math.round(Q*(0.5+$()*0.5))}function eQ(J){return J===429||J===408||J===409||J>=500}function JZ(J,$){return eQ(J)&&E($).retryable}function e8(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function J9(J,$){return new Promise((Q,Z)=>{let W=setTimeout(Q,J);$?.addEventListener("abort",()=>{clearTimeout(W),Z(e8($))},{once:!0})})}async function F$(J,$,Q=J9){if(!$)return await Q(J);$.throwIfAborted();let Z;try{await Promise.race([Q(J,$),new Promise((W,K)=>{Z=()=>K(e8($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function c(J,$,Q){let Z=Q.fetchImpl??((H,D)=>fetch(H,D)),W=Q.sleep??J9,K=Q.random??Math.random,X=Q.now??Date.now,G=Math.max(0,Q.maxRetries),V=(H)=>F$(H,Q.signal,W),Y;for(let H=0;H<=G;H++){Q.signal?.throwIfAborted();let D=new AbortController,z=()=>D.abort(Q.signal?.reason);Q.signal?.addEventListener("abort",z,{once:!0});let F=!1,U=Q.timeoutMs>0?setTimeout(()=>{F=!0,D.abort()},Q.timeoutMs):void 0,N;try{N=await Z(J,{...$,signal:D.signal})}catch(O){if(U!==void 0)clearTimeout(U);if(Q.signal?.removeEventListener("abort",z),Q.signal?.aborted)throw O;if(Y=F?new t8(Q.timeoutMs):O,F&&Q.retryTimeouts===!1)throw Y;if(H===G)throw Y;await V(RJ(H,K));continue}if(U!==void 0)clearTimeout(U);if(N.ok)return N;Q.signal?.removeEventListener("abort",z);let B=await $Z(N),P=new w(N.status,B,N.headers.get("x-request-id")??void 0,rQ(N.headers.get("retry-after"),X()));if(H===G||!JZ(N.status,P))throw P;let L=P.retryAfter??(N.status===429?E(P).retryAfter:void 0);await V(L===void 0?RJ(H,K):Math.min(L,r8)),Y=P}throw Y??Error("Provider request failed with no response.")}async function $Z(J){let $;try{$=await J.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var B$=300000;function P$(J){return{generationsUrl:`${J.base}/images/generations${J.query}`,editsUrl:`${J.base}/images/edits${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}class TJ extends Error{code;retryable;retryAfter;constructor(J,$={}){super(J.message,$);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var QZ={png:"image/png",jpeg:"image/jpeg"};function ZZ(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let K=J?.output_tokens_details?.image_tokens;if(typeof K==="number")Z.imageOutputTokens=K;return Z}function WZ(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function KZ(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new TJ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof J.output_format==="string"?J.output_format:"png";return{bytes:WZ(Q),mimeType:QZ[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:ZZ(J.usage)}}async function $9(J,$,Q,Z){let W;try{W=await c(J,$,{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(K){if(Z.signal?.aborted)throw K;throw new TJ(E(K),{cause:K})}return KZ(await W.json())}async function Q9(J,$,Q={}){return await $9(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function Z9(J,$,Q={}){return await $9(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class EJ{static models(){return[]}modelName(){return this.model}async generate(J){return await Q9(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let $=new FormData;for(let[Q,Z]of Object.entries(this.body(J)))if(Z!==void 0)$.set(Q,String(Z));for(let Q of J.images)$.append("image[]",Q,Q.name);if(J.mask)$.set("mask",J.mask,J.mask.name);return await Z9(this.endpoint(),$,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return E(J)}}var W9=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class N$ extends EJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new N$(J,$)}static models(){return W9}endpoint(){return P$(XJ(this.config,{timeoutMs:B$}))}}class U$ extends EJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new U$(J,$)}static models(){return W9}modelName(){return this.config.deployment??this.model}endpoint(){return P$(YJ(this.config,{timeoutMs:B$}))}}var Y9=3;function L$(J){let $=new Map;for(let Q of J)for(let Z of Q.content??[]){if(Z.type!=="file"||!Z.fileId||$.has(Z.fileId))continue;$.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return $}function G9(J,$,Q=new Map){if(!($ instanceof w))return[];if($.status!==400&&$.status!==404)return[];let Z=YZ($.body);if(!Z)return[];let W=XZ(J.input);if(W.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let Y=J.input[Number(K[1])],H=C$(Y)[Number(K[2])],D=H&&typeof H.file_id==="string"?H.file_id:void 0;if(D)return[D]}let X=Z.message??"",G=X9(W.map((Y)=>Y.fileId).filter((Y)=>GZ(X,Y)));if(G.length>0)return G;let V=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(X);if(V){let Y=V[1].toLowerCase()==="image type"?"input_image":"input_file",H=V[2].toLowerCase(),D=X9(W.filter((F)=>F.type===Y).map((F)=>F.fileId)),z=D.filter((F)=>(Q.get(F)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(z.length===1)return z;if(z.length===0&&D.length===1)return D}return[]}function V9(J,$,Q=new Map){return{...J,input:J.input.map((Z)=>{let W=C$(Z);if(!W.some((K)=>K9(K,$)))return Z;return{...Z,content:W.map((K)=>K9(K,$)?{type:"input_text",text:O$(Q.get(String(K.file_id))?.name)}:K)}})}}function O$(J){return`[${J?`attachment ${JSON.stringify(J)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function K9(J,$){return typeof J.file_id==="string"&&$.has(J.file_id)}function C$(J){let $=J?.content;return Array.isArray($)?$:[]}function XZ(J){let $=[];for(let Q of J)for(let Z of C$(Q))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function YZ(J){if(!J||typeof J!=="object")return null;let $=J,Q=$.error&&typeof $.error==="object"?$.error:J;return{message:typeof Q.message==="string"?Q.message:void 0,param:typeof Q.param==="string"?Q.param:void 0}}function GZ(J,$){let Q=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Q}($|[^A-Za-z0-9_-])`).test(J)}function X9(J){return[...new Set(J)]}async function*VZ(J){let $="",Q="",Z=[],W,K=()=>{if(Z.length===0&&!Q)return null;let V={event:Q,data:Z.join(`
|
|
142
|
+
)`,`CREATE INDEX IF NOT EXISTS "${$}_scope_kind_created_at_idx" ON "${$}"("scope", "kind", "created_at")`,`CREATE INDEX IF NOT EXISTS "${$}_expires_at_idx" ON "${$}"("expires_at")`,`CREATE UNIQUE INDEX IF NOT EXISTS "${$}_scope_key_key" ON "${$}"("scope", "key")`]}var v8={n:0,mean:0,stddev:0,low:null,high:null};function y(J){let $=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-0.13857109526572012,0.000009984369578019572,0.00000015056327351493116];if(J<0.5)return Math.log(Math.PI/Math.sin(Math.PI*J))-y(1-J);J-=1;let Q=$[0],Z=J+7.5;for(let W=1;W<9;W++)Q+=$[W]/(J+W);return 0.5*Math.log(2*Math.PI)+(J+0.5)*Math.log(Z)-Z+Math.log(Q)}function f8(J,$,Q){let W=1,K=1-(J+$)*Q/(J+1);if(Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let X=K;for(let G=1;G<=300;G++){let V=2*G,Y=G*($-G)*Q/((J+V-1)*(J+V));if(K=1+Y*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+Y/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(K=1/K,X*=K*W,Y=-(J+G)*(J+$+G)*Q/((J+V)*(J+V+1)),K=1+Y*K,Math.abs(K)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)K=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;if(W=1+Y/W,Math.abs(W)<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)W=0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001;K=1/K;let H=K*W;if(X*=H,Math.abs(H-1)<0.00000000000001)break}return X}function dQ(J,$,Q){if(J<=0)return 0;if(J>=1)return 1;let Z=Math.exp(y($+Q)-y($)-y(Q)+$*Math.log(J)+Q*Math.log(1-J));return J<($+1)/($+Q+2)?Z*f8($,Q,J)/$:1-Z*f8(Q,$,1-J)/Q}function X$(J,$){return dQ($/($+J*J),$/2,0.5)}function iQ(J){if(!(J>0))return Number.POSITIVE_INFINITY;let $=1.959964,Q=2;while(X$(Q,J)>0.05)Q*=2;for(let Z=0;Z<100;Z++){let W=($+Q)/2;if(X$(W,J)>0.05)$=W;else Q=W}return($+Q)/2}function nQ(J,$,Q,Z){let W=J+Q,K=$+Z,X=(H,D)=>y(H+1)-y(D+1)-y(H-D+1),G=(H)=>Math.exp(X($,H)+X(Z,W-H)-X(K,W)),V=G(J),Y=0;for(let H=Math.max(0,W-Z);H<=Math.min($,W);H++){let D=G(H);if(D<=V*1.0000001)Y+=D}return Math.min(1,Y)}function y8(J,$){if(J.length<2)return 0;let Q=J.reduce((W,K)=>W+(K-$)**2,0),Z=Math.sqrt(Q/(J.length-1));return Z<0.000000000001*Math.max(1,Math.abs($))?0:Z}function Y$(J){let $=J.length;if($===0)return v8;let Q=J.map((G)=>G?1:0),Z=Q.reduce((G,V)=>G+V,0)/$,W=3.841458881296,K=(Z+W/(2*$))/(1+W/$),X=1.959964*Math.sqrt(Z*(1-Z)/$+W/(4*$*$))/(1+W/$);return{n:$,mean:Z,stddev:y8(Q,Z),low:Math.max(0,K-X),high:Math.min(1,K+X)}}function G$(J){let $=J.length;if($===0)return v8;let Q=J.reduce((K,X)=>K+X,0)/$,Z=y8(J,Q);if($<2||Z===0)return{n:$,mean:Q,stddev:Z,low:null,high:null};let W=iQ($-1)*Z/Math.sqrt($);return{n:$,mean:Q,stddev:Z,low:Q-W,high:Q+W}}function ZJ(J,$,Q){return{before:J.mean,after:$.mean,delta:$.mean-J.mean,p:Q,pAdjusted:Q,significant:!1}}function h8(J,$){if(J.n===0||$.n===0)return ZJ(J,$,null);let Q=(Z)=>Math.round(Z.mean*Z.n);return ZJ(J,$,nQ(Q(J),J.n,Q($),$.n))}function g8(J,$){if(J.n<2||$.n<2)return ZJ(J,$,null);let Q=J.stddev**2/J.n,Z=$.stddev**2/$.n,W=Math.sqrt(Q+Z);if(W===0)return ZJ(J,$,null);let K=(Q+Z)**2/(Q**2/(J.n-1)+Z**2/($.n-1));return ZJ(J,$,X$(($.mean-J.mean)/W,K))}function u8(J,$,Q){if(Q==="holm"){let Z=J.filter((K)=>K.p!==null).sort((K,X)=>K.p-X.p),W=0;Z.forEach((K,X)=>{W=Math.max(W,Math.min(1,K.p*(Z.length-X))),K.pAdjusted=W})}else for(let Z of J)Z.pAdjusted=Z.p;for(let Z of J)Z.significant=Z.pAdjusted!==null&&Z.pAdjusted<$&&Z.delta!==0}class RJ{name;cases;runs;concurrency;graders;pricing;task;constructor(J){this.name=J.name,this.cases=J.cases,this.runs=J.runs??1,this.concurrency=J.concurrency??1,this.task=J.task,this.graders=typeof J.graders==="function"?J.graders({judge:($)=>RJ.judge($)}):J.graders,this.pricing=J.pricing}static create(J){let $=`The eval "${J.name}"`;WJ(J.runs,$,"runs"),WJ(J.concurrency,$,"concurrency");let Q=new Set;for(let W of J.cases){if(Q.has(W.id))throw Error(`${$} has two cases with the id "${W.id}".`);Q.add(W.id)}let Z=new RJ(J);for(let[W,K]of Object.entries(Z.graders))if(typeof K!=="function"&&K.kind==="judge")WJ(K.samples,`${$}'s judge "${W}"`,"samples");return Z}static judge(J){return{...J,kind:"judge"}}static compare(J,$,Q={}){return i8(J,$,Q)}static format(J,$={}){return tQ(J,$)}async run(J={}){let $=`${this.name}.run`;WJ(J.runs,$,"runs"),WJ(J.concurrency,$,"concurrency");let Q=J.only?new Set(J.only):null;if(Q){let F=[...Q].filter((P)=>!this.cases.some((L)=>L.id===P));if(F.length>0)throw Error(`The eval "${this.name}" has no case ${F.map((P)=>`"${P}"`).join(", ")}.`)}let Z=J.runs??this.runs,W=Date.now(),K=new AbortController,X=J.signal?AbortSignal.any([J.signal,K.signal]):K.signal,G=this.cases.filter((F)=>!Q||Q.has(F.id)),V={};for(let[F,P]of Object.entries(this.graders)){if(X.aborted)break;if(typeof P==="function"||P.kind!=="judge"||!P.calibration)continue;V[F]=await this.calibrate(P,X)}let Y=G.flatMap((F)=>Array.from({length:Z},(P,L)=>({test:F,run:L+1}))),H=Array.from({length:Y.length}),D=0,z,B=async()=>{while(D<Y.length&&!X.aborted){let F=D++,P=Y[F],L=await this.sample(P.test,P.run,X,J.keepOutputs??!1);H[F]=L;try{J.onSample?.(L)}catch(O){z??={error:O},K.abort(O)}}},U=Math.min(J.concurrency??this.concurrency,Y.length);if(await Promise.all(Array.from({length:U},B)),z)throw z.error;let N=H.filter((F)=>F!==void 0);return this.report(N,V,Z,new Date(W).toISOString(),Date.now()-W,{aborted:X.aborted||N.length<Y.length,planned:G.map((F)=>F.id)})}async sample(J,$,Q,Z){let W=Date.now(),K,X,G=await KJ(async()=>{try{K=await this.task(J.input,{case:J,run:$,signal:Q})}catch(U){X=o8(U)}}),V={},Y=!1,H=await KJ(async()=>{if(X!==void 0)return;let U={case:J,input:J.input,run:$};for(let[N,F]of Object.entries(this.graders)){if(J.skip?.includes(N))continue;let P=await c8(F,K,U,Q);if(!P)continue;if(V[N]=P,!P.pass&&typeof F!=="function"&&F.gate)Y=!0}}),D=Object.values(V).map((U)=>U.score),z=X===void 0&&D.length===0,B=this.pricing?V$(this.pricing,G.byModel).cost+V$(this.pricing,H.byModel).cost:void 0;return{case:J.id,run:$,pass:X===void 0&&!z&&Object.values(V).every((U)=>U.pass),excluded:Y||z,...z?{ungraded:!0}:{},score:X!==void 0||z?0:n8(D),grades:V,...X!==void 0?{error:X}:{},...Z&&X===void 0?{output:K}:{},usage:G.usage,byModel:sQ(G.byModel,H.byModel),judgeUsage:H.usage,...B!==void 0?{cost:B}:{},durationMs:Date.now()-W}}async calibrate(J,$){let Q=J.calibration,Z=[],W=0,K=await KJ(async()=>{for(let[V,Y]of Q.examples.entries()){if($.aborted)break;let H=Y.id??`example-${V+1}`,D={case:{id:H,input:Y.input},input:Y.input,run:0},z=await c8(J,Y.output,D,$),B=z?.pass??!1;if(B===Y.expected)W++;else Z.push({id:H,expected:Y.expected,got:B,...z?.note?{note:z.note}:{}})}}),X=Q.examples.length,G=X===0?1:W/X;return{n:X,agreement:G,ok:G>=(Q.minAgreement??0.8),disagreements:Z,usage:K.usage}}report(J,$,Q,Z,W,K){let X=new Set(Object.entries(this.graders).filter(([,z])=>typeof z!=="function"&&z.gate).map(([z])=>z)),G={};for(let z of this.cases){let B=J.filter((U)=>U.case===z.id);if(B.length===0)continue;G[z.id]={...m8(B),graders:p8(B,X)}}let V=S(),Y=S(),H={};for(let z of J){V=A(V,z.usage),Y=A(Y,z.judgeUsage);for(let[B,U]of Object.entries(z.byModel))H[B]=A(H[B]??S(),U)}let D=this.pricing?V$(this.pricing,H):void 0;return{name:this.name,startedAt:Z,durationMs:W,runs:Q,aborted:K.aborted,planned:K.planned,samples:J,cases:G,graders:p8(J,X),calibration:$,totals:{...m8(J),usage:V,judgeUsage:Y,byModel:H,...D?{cost:D.cost}:{},unpriced:D?D.unpriced:Object.keys(H)}}}}async function c8(J,$,Q,Z){let W=typeof J==="function"?0.5:J.threshold??0.5;try{if(typeof J==="function")return H$(await J($,Q),W);if(J.kind!=="judge")return H$(await J.check($,Q),W);return await oQ(J,$,Q,W,Z)}catch(K){return{pass:!1,score:0,error:o8(K)}}}async function oQ(J,$,Q,Z,W){let K=await J.prompt($,Q),X=typeof K==="string"?{prompt:K}:K,G=[];for(let D=0;D<(J.samples??1)&&!W.aborted;D++){let z=await z$({signal:W,provider:J.provider,...J.instructions!==void 0?{instructions:J.instructions}:{},...X,output:J.output,...J.reasoning!==void 0?{reasoning:J.reasoning}:{},...J.maxOutputTokens!==void 0?{maxOutputTokens:J.maxOutputTokens}:{},...J.temperature!==void 0?{temperature:J.temperature}:{},logErrors:!1});if(!z.ok){G.push({pass:!1,score:0,error:`The judge failed: ${z.error.message}`});continue}let B=H$(J.verdict(z.output,Q),Z);if(B)G.push(B)}if(G.length===0)return null;if(G.length===1)return G[0];let V=G.filter((D)=>D.pass).length,Y=G.map((D)=>D.note??D.error).filter(Boolean),H=G.map((D)=>D.error).filter(Boolean);return{pass:V*2>G.length,score:n8(G.map((D)=>D.score)),...Y.length>0?{note:Y.join(" | ")}:{},...H.length===G.length?{error:H.join(" | ")}:{}}}function H$(J,$){if(J===null||J===void 0)return null;if(typeof J==="boolean")return{pass:J,score:J?1:0};if(typeof J==="number"){if(!Number.isFinite(J))throw Error(`A grader answered the score ${J}.`);let Q=l8(J);return{pass:Q>=$,score:Q}}return{pass:J.pass,score:J.score===void 0?J.pass?1:0:l8(J.score),...J.note!==void 0?{note:J.note}:{}}}function m8(J){let $=J.filter((Q)=>!Q.excluded);return{samples:J.length,kept:$.length,passed:$.filter((Q)=>Q.pass).length,errors:J.filter((Q)=>Q.error!==void 0).length,passRate:Y$($.map((Q)=>Q.pass)),score:G$($.map((Q)=>Q.score))}}function p8(J,$){let Q=J.filter((W)=>!W.excluded),Z=[...new Set(J.flatMap((W)=>Object.keys(W.grades)))];return Object.fromEntries(Z.map((W)=>{let X=($.has(W)?J:Q).flatMap((G)=>G.grades[W]?[G.grades[W]]:[]);return[W,{passRate:Y$(X.map((G)=>G.pass)),score:G$(X.map((G)=>G.score))}]}))}function V$(J,$){let Q=0,Z=[];for(let[W,K]of Object.entries($)){let X=d8(J,W,K);if(X===void 0){Z.push(W);continue}Q+=X}return{cost:Q,unpriced:Z}}function sQ(...J){let $={};for(let Q of J)for(let[Z,W]of Object.entries(Q))$[Z]=A($[Z]??S(),W);return $}function i8(J,$,Q){for(let[F,P]of[["baseline",J],["current report",$]])if(P.aborted)throw Error(`Eval.compare: the ${F} for "${P.name}" was aborted (${P.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`);let Z=Q.alpha??0.05,W=Q.adjust??"holm",K=[],X=(F,P,L)=>{let O={label:F,passRate:h8(P.passRate,L.passRate),score:g8(P.score,L.score)};return K.push(O),{passRate:O.passRate,score:O.score}},G=(F,P,L)=>Object.fromEntries(Object.keys(L).filter((O)=>(O in P)).map((O)=>[O,X(`${F} ${O}`,P[O],L[O])])),V=(F,P)=>({fromCurrent:F.filter((L)=>!P.includes(L)),fromBaseline:P.filter((L)=>!F.includes(L))}),Y=X("total",J.totals,$.totals),H=G("case",J.cases,$.cases),D=G("grader",J.graders,$.graders),z=K.flatMap((F)=>[F.passRate,F.score]);u8(z,Z,W);let B={cases:V([...new Set([...J.planned??[],...Object.keys(J.cases)])],[...new Set([...$.planned??[],...Object.keys($.cases)])]),graders:V(Object.keys(J.graders),Object.keys($.graders))},U=[...B.cases.fromCurrent.map((F)=>`case ${F}: in the baseline, missing from this report`),...B.graders.fromCurrent.map((F)=>`grader ${F}: in the baseline, missing from this report`)],N=[];for(let F of K)for(let[P,L]of[["pass rate",F.passRate],["score",F.score]]){if(!L.significant)continue;let O=`${F.label}: ${P} ${L.before.toFixed(2)} \u2192 ${L.after.toFixed(2)} (p = ${aQ(L.pAdjusted)})`;(L.delta<0?U:N).push(O)}return{totals:Y,cases:H,graders:D,missing:B,comparisons:z.filter((F)=>F.p!==null).length,alpha:Z,adjust:W,regressions:U,improvements:N}}function aQ(J){return J<0.001?"<0.001":J.toFixed(3)}function tQ(J,$){let Q=$.baseline&&!$.baseline.aborted&&!J.aborted?i8($.baseline,J,$):void 0,{totals:Z}=J,W=[];if(W.push(`eval ${J.name}: ${Z.samples} samples, ${Z.kept} kept, ${Z.passed} passed, ${Z.errors} errors (${(J.durationMs/1000).toFixed(1)}s)`),J.aborted)W.push(`ABORTED: only ${Z.samples} of the planned samples ran; not comparable.`);let K=(Y)=>{if(Y.n===0)return"-";let H=Y.mean.toFixed(2);if(Y.low===null||Y.high===null)return`${H} (${Y.n===1?"n=1":"no spread"})`;return`${H} [${Y.low.toFixed(2)}, ${Y.high.toFixed(2)}]`},X=(Y)=>Y?` ${Y.delta>=0?"+":""}${Y.delta.toFixed(2)}${Y.significant?"*":""}`:"",G=(Y,H)=>{let D=[0,1,2,3].map((B)=>Math.max(...[[Y,"n","pass rate","score"],...H].map((U)=>U[B].length))),z=(B)=>B.map((U,N)=>U.padEnd(D[N])).join(" ").trimEnd();W.push("",z([Y,"n","pass rate","score"]),...H.map(z))};G("case",Object.entries(J.cases).map(([Y,H])=>[Y,`${H.kept}/${H.samples}`,K(H.passRate)+X(Q?.cases[Y]?.passRate),K(H.score)+X(Q?.cases[Y]?.score)])),G("grader",Object.entries(J.graders).map(([Y,H])=>[Y,String(H.passRate.n),K(H.passRate)+X(Q?.graders[Y]?.passRate),K(H.score)+X(Q?.graders[Y]?.score)])),W.push("",`total pass rate ${K(Z.passRate)}${X(Q?.totals.passRate)} score ${K(Z.score)}${X(Q?.totals.score)}`);for(let[Y,H]of Object.entries(J.calibration))W.push(`judge ${Y}: agreement ${H.agreement.toFixed(2)} on ${H.n} examples${H.ok?"":" (BELOW minAgreement)"}`);let V=(Y)=>`${Y.inputTokens} in, ${Y.outputTokens} out`;if(W.push(`tokens: task ${V(Z.usage)}; judges ${V(Z.judgeUsage)}${Z.cost!==void 0?`; cost $${Z.cost.toFixed(4)}`:""}${Z.unpriced.length>0&&Z.cost!==void 0?` (unpriced: ${Z.unpriced.join(", ")})`:""}`),Q){W.push("",`* significant at ${Q.alpha} over ${Q.comparisons} tests (${Q.adjust==="holm"?"Holm-adjusted":"unadjusted"}; Fisher's exact for pass rates, Welch's t for scores)`);for(let Y of Q.regressions)W.push(`regression: ${Y}`);for(let Y of Q.improvements)W.push(`improvement: ${Y}`)}return W.join(`
|
|
143
|
+
`)}function n8(J){return J.reduce(($,Q)=>$+Q,0)/J.length}function l8(J){return Math.min(1,Math.max(0,J))}function o8(J){return J instanceof Error?J.message:String(J)}function WJ(J,$,Q){if(J===void 0||Number.isInteger(J)&&J>=1)return;throw Error(`${$} sets \`${Q}\` to ${String(J)}, but it has to be a whole number of at least 1.`)}var rQ=/^[A-Za-z0-9_-]{1,64}$/;function eQ(J,$){let Q=JZ($)?$:{filter:$},Z=Q.deferred===!0,W=J.descriptors(Q.filter);if(!Q.namespaces)return W.map((H)=>D$(J,H,Z));let K=Object.entries(Q.namespaces),X=new Set(J.descriptors().flatMap((H)=>H.tags));for(let[H,D]of K){if(!rQ.test(H))throw Error(`toAgentTools: "${H}" 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 "${H}" needs a description. It is what the model reads to decide whether to look inside.`);if(!X.has(H))throw Error(`toAgentTools: no tool is tagged "${H}", so its namespace would be empty.`)}let G=new Map(K.map(([H])=>[H,[]])),V=[];for(let H of W){let D=K.find(([z])=>H.tags.includes(z))?.[0];if(D===void 0)V.push(D$(J,H,Z));else G.get(D).push(D$(J,H,!1))}let Y=[];for(let[H,D]of K){let z=G.get(H);if(z.length===0)continue;Y.push(B$.create({name:H,description:D.description,tools:z,deferred:D.deferred??Z}))}return[...Y,...V]}function JZ(J){return typeof J==="object"&&J!==null&&(("filter"in J)||("namespaces"in J)||("deferred"in J))}function D$(J,$,Q){if($.kind==="tool")return $Z(J,$,Q);return EJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:$.requiresApproval,deferred:Q,execute:(Z,W)=>{let K=h.getStore()?.req;if(!K)throw new g(`"${$.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 J.execute({kind:"local",req:K},$.name,Z,W)}})}function $Z(J,$,Q){let Z=J.nativeTool($.name);return EJ.create({name:$.name,description:$.description,inputSchema:$.inputSchema,...$.outputSchema?{outputSchema:$.outputSchema}:{},requiresApproval:J.nativeApproval($.name),deferred:Q,...Z.timeoutMs!==void 0?{timeoutMs:Z.timeoutMs}:{},...Z.async?{async:Z.async}:{},execute:(W,K)=>{let X=h.getStore()?.req;return J.startNative(X?{kind:"local",req:X}:void 0,$.name,W,K)}})}function QZ(J){if(J==="auto")return;let $=/^(\d+)x(\d+)$/.exec(J);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(J)}.`);let Q=Number($[1]),Z=Number($[2]);if(Q%16!==0||Z%16!==0)throw Error(`Image size ${J} is not supported: width and height must both be divisible by 16.`);if(Math.max(Q/Z,Z/Q)>3)throw Error(`Image size ${J} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function s8(J,$){if(J.size!==void 0)try{QZ(J.size)}catch(Q){throw Error(`${$}: ${Q.message}`)}if(J.background==="transparent"&&J.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(J.compression!==void 0){let Q=J.compression;if(!Number.isInteger(Q)||Q<0||Q>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Q}.`)}}function a8(J,$){if(J instanceof File)return J;let Q=J.type||"image/png",Z=Q==="image/jpeg"?"jpg":Q.split("/")[1]??"png";return new File([J],`${$}.${Z}`,{type:Q})}class F${name;provider;settings;constructor(J){let{name:$,provider:Q,...Z}=J;s8(Z,`ImageModel "${$}"`),this.name=$,this.provider=Q,this.settings=Z}static create(J){return new F$(J)}async generate(J){let $=this.merge(J);return this.present(await this.provider.generate({prompt:J.prompt,...$,signal:J.signal}))}async edit(J){let $=this.merge(J);return this.present(await this.provider.edit({prompt:J.prompt,...$,images:J.images.map((Q,Z)=>a8(Q,`image-${Z}`)),...J.mask?{mask:a8(J.mask,"mask")}:{},signal:J.signal}))}present(J){return t8(this.provider.model,J.usage),ZZ(J)}merge(J){let $={...this.settings,...J.size!==void 0?{size:J.size}:{},...J.quality!==void 0?{quality:J.quality}:{},...J.background!==void 0?{background:J.background}:{},...J.format!==void 0?{format:J.format}:{},...J.compression!==void 0?{compression:J.compression}:{}};return s8($,`ImageModel "${this.name}"`),$}}function ZZ(J){return{image:new Blob([J.bytes],{type:J.mimeType}),mimeType:J.mimeType,size:J.size,usage:J.usage}}function u(J){return typeof process>"u"?void 0:process.env?.[J]}var WZ="preview";function r8(J){let $=J.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function KZ(J){return/^\d{4}-\d{2}-\d{2}/.test(J)?"":"/v1"}function XJ(J,$={}){return{base:(J.baseURL??u("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=J.apiKey??u("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...J.headers}},timeoutMs:J.timeoutMs??$.timeoutMs??120000,maxRetries:J.maxRetries??2}}function e8(J){let $=J.baseURL??J.endpoint??u("AZURE_OPENAI_ENDPOINT");if($)return r8($);let Q=J.resourceName??u("AZURE_OPENAI_RESOURCE_NAME")??u("AZURE_RESOURCE_NAME");return Q?r8(`https://${Q.trim()}.cognitiveservices.azure.com`):""}function YJ(J,$={}){let Q=J.apiVersion??u("AZURE_OPENAI_API_VERSION")??WZ;return{base:`${e8(J)}${KZ(Q)}`,query:`?api-version=${encodeURIComponent(Q)}`,headers:async()=>{if(J.getToken)return{authorization:`Bearer ${await J.getToken()}`,...J.headers};let Z=J.apiKey??u("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...J.headers}},timeoutMs:J.timeoutMs??$.timeoutMs??120000,maxRetries:J.maxRetries??2}}function J9(J,$={}){return{...YJ(J,$),base:`${e8(J)}/v1`,query:""}}var XZ=500,Q9=20000;function YZ(J,$){if(!J)return;let Q=J.trim();if(/^\d+(\.\d+)?$/.test(Q))return Math.max(0,Number(Q)*1000);let Z=Date.parse(Q);if(Number.isNaN(Z))return;return Math.max(0,Z-$)}function TJ(J,$){let Q=Math.min(Q9,XZ*2**J);return Math.round(Q*(0.5+$()*0.5))}function GZ(J){return J===429||J===408||J===409||J>=500}function VZ(J,$){return GZ(J)&&T($).retryable}function Z9(J){return J.reason??new DOMException("The operation was aborted.","AbortError")}function W9(J,$){return new Promise((Q,Z)=>{let W=setTimeout(Q,J);$?.addEventListener("abort",()=>{clearTimeout(W),Z(Z9($))},{once:!0})})}async function P$(J,$,Q=W9){if(!$)return await Q(J);$.throwIfAborted();let Z;try{await Promise.race([Q(J,$),new Promise((W,K)=>{Z=()=>K(Z9($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function c(J,$,Q){let Z=Q.fetchImpl??((H,D)=>fetch(H,D)),W=Q.sleep??W9,K=Q.random??Math.random,X=Q.now??Date.now,G=Math.max(0,Q.maxRetries),V=(H)=>P$(H,Q.signal,W),Y;for(let H=0;H<=G;H++){Q.signal?.throwIfAborted();let D=new AbortController,z=()=>D.abort(Q.signal?.reason);Q.signal?.addEventListener("abort",z,{once:!0});let B=!1,U=Q.timeoutMs>0?setTimeout(()=>{B=!0,D.abort()},Q.timeoutMs):void 0,N;try{N=await Z(J,{...$,signal:D.signal})}catch(O){if(U!==void 0)clearTimeout(U);if(Q.signal?.removeEventListener("abort",z),Q.signal?.aborted)throw O;if(Y=B?new $9(Q.timeoutMs):O,B&&Q.retryTimeouts===!1)throw Y;if(H===G)throw Y;await V(TJ(H,K));continue}if(U!==void 0)clearTimeout(U);if(N.ok)return N;Q.signal?.removeEventListener("abort",z);let F=await HZ(N),P=new w(N.status,F,N.headers.get("x-request-id")??void 0,YZ(N.headers.get("retry-after"),X()));if(H===G||!VZ(N.status,P))throw P;let L=P.retryAfter??(N.status===429?T(P).retryAfter:void 0);await V(L===void 0?TJ(H,K):Math.min(L,Q9)),Y=P}throw Y??Error("Provider request failed with no response.")}async function HZ(J){let $;try{$=await J.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var N$=300000;function U$(J){return{generationsUrl:`${J.base}/images/generations${J.query}`,editsUrl:`${J.base}/images/edits${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}class jJ extends Error{code;retryable;retryAfter;constructor(J,$={}){super(J.message,$);if(this.name="ImageRequestError",this.code=J.code,this.retryable=J.retryable,J.retryAfter!==void 0)this.retryAfter=J.retryAfter}}var zZ={png:"image/png",jpeg:"image/jpeg"};function DZ(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_tokens_details?.image_tokens;if(typeof W==="number")Z.imageInputTokens=W;let K=J?.output_tokens_details?.image_tokens;if(typeof K==="number")Z.imageOutputTokens=K;return Z}function BZ(J){let $=atob(J),Q=new Uint8Array($.length);for(let Z=0;Z<$.length;Z++)Q[Z]=$.charCodeAt(Z);return Q}function FZ(J){let Q=J?.data?.[0]?.b64_json;if(typeof Q!=="string"||Q.length===0)throw new jJ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let Z=typeof J.output_format==="string"?J.output_format:"png";return{bytes:BZ(Q),mimeType:zZ[Z]??`image/${Z}`,size:typeof J.size==="string"?J.size:"",...typeof J.background==="string"?{background:J.background}:{},usage:DZ(J.usage)}}async function K9(J,$,Q,Z){let W;try{W=await c(J,$,{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,retryTimeouts:!1,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(K){if(Z.signal?.aborted)throw K;throw new jJ(T(K),{cause:K})}return FZ(await W.json())}async function X9(J,$,Q={}){return await K9(J.generationsUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify($)},J,Q)}async function Y9(J,$,Q={}){return await K9(J.editsUrl,{method:"POST",headers:await J.headers(),body:$},J,Q)}class kJ{static models(){return[]}modelName(){return this.model}async generate(J){return await X9(this.endpoint(),this.body(J),{signal:J.signal})}async edit(J){let $=new FormData;for(let[Q,Z]of Object.entries(this.body(J)))if(Z!==void 0)$.set(Q,String(Z));for(let Q of J.images)$.append("image[]",Q,Q.name);if(J.mask)$.set("mask",J.mask,J.mask.name);return await Y9(this.endpoint(),$,{signal:J.signal})}body(J){return{model:this.modelName(),prompt:J.prompt,...J.size?{size:J.size}:{},...J.quality?{quality:J.quality}:{},...J.background?{background:J.background}:{},...J.format?{output_format:J.format}:{},...J.compression!==void 0?{output_compression:J.compression}:{}}}normalizeError(J){return T(J)}}var G9=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class L$ extends kJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new L$(J,$)}static models(){return G9}endpoint(){return U$(XJ(this.config,{timeoutMs:N$}))}}class O$ extends kJ{model;config;constructor(J,$={}){super();this.model=J,this.config=$}static model(J,$){return new O$(J,$)}static models(){return G9}modelName(){return this.config.deployment??this.model}endpoint(){return U$(YJ(this.config,{timeoutMs:N$}))}}var z9=3;function C$(J){let $=new Map;for(let Q of J)for(let Z of Q.content??[]){if(Z.type!=="file"||!Z.fileId||$.has(Z.fileId))continue;$.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return $}function D9(J,$,Q=new Map){if(!($ instanceof w))return[];if($.status!==400&&$.status!==404)return[];let Z=NZ($.body);if(!Z)return[];let W=PZ(J.input);if(W.length===0)return[];let K=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(K){let Y=J.input[Number(K[1])],H=M$(Y)[Number(K[2])],D=H&&typeof H.file_id==="string"?H.file_id:void 0;if(D)return[D]}let X=Z.message??"",G=H9(W.map((Y)=>Y.fileId).filter((Y)=>UZ(X,Y)));if(G.length>0)return G;let V=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(X);if(V){let Y=V[1].toLowerCase()==="image type"?"input_image":"input_file",H=V[2].toLowerCase(),D=H9(W.filter((B)=>B.type===Y).map((B)=>B.fileId)),z=D.filter((B)=>(Q.get(B)?.name??"").trim().toLowerCase().endsWith(`.${H}`));if(z.length===1)return z;if(z.length===0&&D.length===1)return D}return[]}function B9(J,$,Q=new Map){return{...J,input:J.input.map((Z)=>{let W=M$(Z);if(!W.some((K)=>V9(K,$)))return Z;return{...Z,content:W.map((K)=>V9(K,$)?{type:"input_text",text:_$(Q.get(String(K.file_id))?.name)}:K)}})}}function _$(J){return`[${J?`attachment ${JSON.stringify(J)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function V9(J,$){return typeof J.file_id==="string"&&$.has(J.file_id)}function M$(J){let $=J?.content;return Array.isArray($)?$:[]}function PZ(J){let $=[];for(let Q of J)for(let Z of M$(Q))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function NZ(J){if(!J||typeof J!=="object")return null;let $=J,Q=$.error&&typeof $.error==="object"?$.error:J;return{message:typeof Q.message==="string"?Q.message:void 0,param:typeof Q.param==="string"?Q.param:void 0}}function UZ(J,$){let Q=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${Q}($|[^A-Za-z0-9_-])`).test(J)}function H9(J){return[...new Set(J)]}async function*LZ(J){let $="",Q="",Z=[],W,K=()=>{if(Z.length===0&&!Q)return null;let V={event:Q,data:Z.join(`
|
|
144
144
|
`),id:W};return Q="",Z=[],W=void 0,V.data?V:null},X=(V)=>{let Y=V.endsWith("\r")?V.slice(0,-1):V;if(Y==="")return K();if(Y.startsWith(":"))return null;let H=Y.indexOf(":"),D=H===-1?Y:Y.slice(0,H),z=H===-1?"":Y.slice(H+1);if(z.startsWith(" "))z=z.slice(1);if(D==="event")Q=z;else if(D==="data")Z.push(z);else if(D==="id")W=z;return null};for await(let V of J){$+=V;let Y=$.indexOf(`
|
|
145
145
|
`);while(Y!==-1){let H=$.slice(0,Y);$=$.slice(Y+1);let D=X(H);if(D)yield D;Y=$.indexOf(`
|
|
146
|
-
`)}}if($.length>0){let V=X($);if(V)yield V}let G=K();if(G)yield G}async function*H9(J,$={}){let Q=new Map,Z=new Set,W,K=!1,X,G=(V,Y)=>({type:"finish",reason:V,usage:Y,...X?{model:X}:{}});for await(let V of VZ(J)){if(V.data==="[DONE]")break;let Y;try{Y=JSON.parse(V.data)}catch{continue}let H=typeof Y.type==="string"?Y.type:V.event,D=Y.response?.model;if(typeof D==="string"&&D)X=D;switch(H){case"response.output_text.delta":{let z=String(Y.delta??"");if(!z)break;yield $.structuredOutput?{type:"output-delta",delta:z}:{type:"text-delta",delta:z};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let z=String(Y.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:Y.item_id};break}case"response.output_item.added":{let z=Y.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??Y.item_id??z.call_id??"");Q.set(F,{callId:String(z.call_id??F),name:String(z.name??""),namespace:typeof z.namespace==="string"&&z.namespace?z.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let z=Q.get(String(Y.item_id??""));if(!z)break;let F=String(Y.delta??"");if(!F)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:F,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(Y.item_id??""),F=Q.get(z);if(!F)break;F.done=!0,yield{type:"tool-call",toolCallId:F.callId,name:F.name,args:String(Y.arguments??""),...F.namespace?{namespace:F.namespace}:{}};break}case"response.output_item.done":{let z=Y.item;if(!z)break;if(z.type==="function_call"){let F=String(z.id??Y.item_id??z.call_id??""),U=Q.get(F);if(U?.done)break;let N=(typeof z.namespace==="string"?z.namespace:"")||U?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??F),name:String(z.name??U?.name??""),args:String(z.arguments??""),...N?{namespace:N}:{}},U)U.done=!0;break}if(z.type==="tool_search_call"||z.type==="tool_search_output"){if(z.type==="tool_search_call"&&z.arguments!==void 0)W=z.arguments;let F=HZ(z);if(F.loaded.length===0&&F.namespaces.length===0)break;let U=String(z.tool_search_call_id??z.id??"");if(Z.has(U))break;Z.add(U);let N=W;W=void 0,yield{type:"tool-search",...F,...N!==void 0&&N!==null?{arguments:N}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(Y.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{K=!0,yield G("stop",_$(Y.response?.usage));break}case"response.incomplete":{K=!0;let z=_$(Y.response?.usage),F=Y.response?.incomplete_details?.reason;if(F==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:zZ(Y.response?.content_filters),retryable:!1}},yield G("error",z);break}yield G(F==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{K=!0;let z=Y.response?.error??Y.error??Y;yield{type:"error",error:DZ(z)},yield G("error",_$(Y.response?.usage));break}}if(K)return}if(!K)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield G("error",b())}function HZ(J){let $=[],Q=[];return z9(J.results??J.tools??J.loaded??J.output,$,Q,0),{loaded:M$($),namespaces:M$(Q)}}function z9(J,$,Q,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){$.push(W);continue}if(!W||typeof W!=="object")continue;let K=W,X=typeof K.name==="string"?K.name:typeof K.tool_name==="string"?K.tool_name:"",G=K.tools??K.functions;if(Array.isArray(G)){if(X)Q.push(X);z9(G,$,Q,Z+1);continue}if(X)$.push(X)}}function M$(J){return J.filter(($,Q)=>J.indexOf($)===Q)}function zZ(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let Q=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,K=W.content_filter_results;if(!K||typeof K!=="object")continue;for(let[X,G]of Object.entries(K))if(G&&typeof G==="object"&&G.filtered===!0)Q.push(`${X} (${String(W.source_type??"unknown")})`)}return Q.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${M$(Q).join(", ")}.`}function DZ(J){let $=typeof J?.message==="string"?J.message:"The provider stream failed.",Q=String(J?.code??"").toLowerCase();if(Q==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Q==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Q.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function b(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function _$(J){if(!J)return b();let $=Number(J.input_tokens??0),Q=Number(J.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J.total_tokens??$+Q)},W=J.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let K=J.input_tokens_details?.cached_tokens;if(typeof K==="number")Z.cachedInputTokens=K;return Z}async function*D9(J){if(!J)return;let $=J.getReader(),Q=new TextDecoder;try{while(!0){let{done:W,value:K}=await $.read();if(W)break;if(K)yield Q.decode(K,{stream:!0})}let Z=Q.decode();if(Z)yield Z}finally{$.releaseLock()}}function S$(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}async function*A$(J,$,Q){let Z=$,W=new Set,K=0,X=Math.max(0,J.maxRetries),G=J.random??Math.random,V,Y=(D)=>{if(!V)return D;let z=A(A(b(),V),D.usage);return V=void 0,{...D,usage:z}},H=()=>Y({type:"finish",reason:"aborted",usage:b()});for(let D=0;;D++){let z;while(z===void 0)try{z=await c(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Z)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:Q.signal,fetchImpl:J.fetchImpl,sleep:J.sleep,random:J.random})}catch(B){let P=K<Y9?G9(Z,B,Q.files).filter((O)=>!W.has(O)):[];if(P.length>0){K++;let O=E(B).message;for(let j of P)W.add(j),yield{type:"file-rejected",fileId:j,message:O,...s(B)};Z=V9(Z,new Set(P),Q.files);continue}let L=E(B);if(L.code==="aborted"){yield H();return}yield{type:"error",error:L,...s(B)},yield Y({type:"finish",reason:"error",usage:b()});return}let F=[],U=!1,N;try{for await(let B of H9(D9(z.body),{structuredOutput:Q.structuredOutput})){if(U){yield B.type==="finish"?Y(B):B;continue}if(jJ(B)){U=!0,yield*F.splice(0),yield B;continue}if(B.type==="error")N=B.error;F.push(B)}}catch(B){let P=E(B);if(P.code==="aborted"||Q.signal?.aborted){yield H();return}if(U){yield{type:"error",error:P},yield Y({type:"finish",reason:"error",usage:b()});return}N=P,F.push({type:"error",error:P},{type:"finish",reason:"error",usage:b()})}if(U)return;if(N?.retryable&&D<X&&!Q.signal?.aborted){for(let B of F)if(B.type==="finish")V=A(V??b(),B.usage);try{await F$(RJ(D,G),Q.signal,J.sleep)}catch{yield H();return}continue}for(let B of F)yield B.type==="finish"?Y(B):B;return}}async function R$(J,$,Q="user_data"){let Z=new FormData;Z.set("purpose",Q),Z.set("file",$);let K=await(await c(J.filesUrl,{method:"POST",headers:await J.headers(),body:Z},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,fetchImpl:J.fetchImpl})).json();if(!K?.id)throw Error("The provider accepted the upload but returned no file id.");return K.id}function T$(J){let $=FZ(J);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Q=BZ($);if(Q?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Q.major>1,toolSearch:F9(Q)};if(Q?.kind==="gpt")return{reasoning:Q.major>=5,structuredOutput:Q.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Q.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:F9(Q)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function F9(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function FZ(J){return J.trim().toLowerCase()}function BZ(J){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Q=/^o(\d+)(?:[-.]|$)/.exec(J);if(Q?.[1])return{kind:"o",major:Number(Q[1]),minor:0};return null}var PZ={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function NZ(J){if(typeof J!=="string")return;let $;try{$=JSON.parse(J)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let Q=PZ[$.type];if(Q)$.type=Q;if($.type==="response.done"&&$.response?.usage)$.usage=kJ($.response.usage);if($.type==="conversation.item.input_audio_transcription.completed"&&$.usage)if($.usage.type==="duration"){let Z=Number($.usage.seconds);if(Number.isFinite(Z))$.transcriptionSeconds=Z}else $.transcriptionUsage=kJ($.usage);return $}var B9=1,UZ=500;function LZ(J,$){let Q=globalThis.WebSocket;if(!Q)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new Q(J,{headers:$.headers})}class xJ{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(J){this.init=J,this.callId=J.callId,this.ready=new Promise(($,Q)=>{this.resolveReady=$,this.rejectReady=Q}),this.ready.catch(()=>{}),this.closed=new Promise(($)=>this.resolveClosed=$),this.open()}send(J){if(this.finished||this.closing)return;let $=JSON.stringify(J);if(this.socket?.readyState===B9)this.socket.send($);else this.outbox.push($)}updateSession(J){this.send({type:"session.update",session:qJ(J)})}addItem(J){this.send({type:"conversation.item.create",item:J})}addNote(J){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:J}]})}functionOutput(J,$){this.addItem({type:"function_call_output",call_id:J,output:typeof $==="string"?$:JSON.stringify($)})}createResponse(J={}){let $={};if(J.instructions!==void 0)$.instructions=J.instructions;if(J.toolChoice!==void 0)$.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};if(J.outputModalities)$.output_modalities=J.outputModalities;if(J.conversation)$.conversation=J.conversation;if(J.metadata)$.metadata=J.metadata;Object.assign($,J.vendor),this.send(Object.keys($).length?{type:"response.create",response:$}:{type:"response.create"})}cancelResponse(J){this.send(J?{type:"response.cancel",response_id:J}:{type:"response.cancel"})}on(J){return this.listeners.add(J),()=>this.listeners.delete(J)}[Symbol.asyncIterator](){let J={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(J),{next:async()=>{for(;;){let Q=J.queue.shift();if(Q)return{value:Q,done:!1};if(J.done)return this.subscribers.delete(J),{value:void 0,done:!0};await new Promise((Z)=>J.wake=Z),J.wake=void 0}},return:async()=>{return J.done=!0,J.queue.length=0,this.subscribers.delete(J),{value:void 0,done:!0}}}}close(J=1000,$="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=B9)this.socket.close(J,$);else this.finish(J,$,!0)}async hangup(){try{await this.init.hangup()}catch(J){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw J}this.close(1000,"hangup")}async open(){let J;try{let Q=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);J=(this.init.webSocket??LZ)(this.init.url,{headers:Q})}catch(Q){return this.dropped(1006,Q instanceof Error?Q.message:String(Q),!1)}this.socket=J;let $=!1;J.addEventListener("open",()=>{$=!0;let Q=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let W of this.outbox.splice(0))J.send(W);if(this.resolveReady(),Q)this.emit({type:"sideband.reconnected",attempt:Z})}),J.addEventListener("message",(Q)=>{let Z=NZ(Q.data);if(Z)this.emit(Z)}),J.addEventListener("close",(Q)=>{if(this.socket!==J)return;this.dropped(Q.code??1006,Q.reason??"",$)}),J.addEventListener("error",()=>{})}dropped(J,$,Q){if(this.socket=void 0,this.closing)return this.finish(J,$,!0);let Z=this.init.reconnect?.attempts??3;if(!((J!==1000||!Q)&&this.failures<Z))return this.finish(J,$,!1);this.failures+=1;let K=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),K)}finish(J,$,Q){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:J,reason:$,byClient:Q};this.finalEvent=Z,this.emit(Z);for(let W of this.subscribers)W.done=!0,W.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${J} ${$}).`));this.resolveClosed(Z)}emit(J){if(this.backlog){if(this.backlog.push(J),this.backlog.length>UZ)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(J),$.wake?.()}for(let $ of this.listeners)try{$(J)}catch{}}}var E$=30000,P9=10,N9=7200,OZ=600,L9="gpt-live-transcribe";function CZ(J){return J.type==="transcription"}function _Z(J){if(J.language!==void 0&&J.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let W of J.keywords??[])if(/[<>\r\n]/.test(W))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(W)}.`);let $={model:J.model??L9};if(J.prompt!==void 0)$.prompt=J.prompt;if(J.keywords?.length)$.keywords=J.keywords;if(J.languages?.length)$.languages=J.languages;if(J.language!==void 0)$.language=J.language;if(J.delay!==void 0)$.delay=J.delay;let Q={transcription:$,turn_detection:J.turnDetection?O9(J.turnDetection):null};if(J.noiseReduction!==void 0)Q.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let Z={type:"transcription",audio:{input:Q}};if(J.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...J.vendor}}function MZ(J){if(!J)return{type:"object",properties:{}};return U9(J)?J.toJSONSchema():J}function qJ(J,$){if(CZ(J))return _Z(J);let Q={type:"realtime"},Z=J.model??$;if(Z)Q.model=Z;if(J.instructions!==void 0)Q.instructions=J.instructions;if(J.outputModalities)Q.output_modalities=J.outputModalities;if(J.maxOutputTokens!==void 0)Q.max_output_tokens=J.maxOutputTokens;if(J.truncation!==void 0)Q.truncation=J.truncation;if(J.tools)Q.tools=J.tools.map((X)=>({type:"function",name:X.name,...X.description?{description:X.description}:{},parameters:MZ(X.parameters)}));if(J.toolChoice!==void 0)Q.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};let W={};if(J.turnDetection!==void 0)W.turn_detection=J.turnDetection&&O9(J.turnDetection);if(J.transcription!==void 0)W.transcription=J.transcription;if(J.noiseReduction!==void 0)W.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let K={};if(J.voice!==void 0)K.voice=J.voice;if(J.speed!==void 0)K.speed=J.speed;if(Object.keys(W).length||Object.keys(K).length)Q.audio={...Object.keys(W).length?{input:W}:{},...Object.keys(K).length?{output:K}:{}};return{...Q,...J.vendor}}function O9(J){let $={type:J.type};if(J.createResponse!==void 0)$.create_response=J.createResponse;if(J.interruptResponse!==void 0)$.interrupt_response=J.interruptResponse;if(J.type==="semantic_vad"){if(J.eagerness!==void 0)$.eagerness=J.eagerness}else{if(J.threshold!==void 0)$.threshold=J.threshold;if(J.prefixPaddingMs!==void 0)$.prefix_padding_ms=J.prefixPaddingMs;if(J.silenceDurationMs!==void 0)$.silence_duration_ms=J.silenceDurationMs;if(J.idleTimeoutMs!==void 0)$.idle_timeout_ms=J.idleTimeoutMs}return $}function kJ(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_token_details??J?.input_tokens_details,K=J?.output_token_details??J?.output_tokens_details;if(typeof W?.cached_tokens==="number")Z.cachedInputTokens=W.cached_tokens;if(typeof W?.audio_tokens==="number")Z.audioInputTokens=W.audio_tokens;let X=W?.cached_tokens_details?.audio_tokens;if(typeof X==="number")Z.cachedAudioInputTokens=X;if(typeof W?.image_tokens==="number"&&W.image_tokens>0)Z.imageInputTokens=W.image_tokens;if(typeof K?.audio_tokens==="number")Z.audioOutputTokens=K.audio_tokens;return Z}class f extends Error{code;retryable;status;constructor(J,$={}){super(J.message,{cause:$.cause});if(this.name="RealtimeRequestError",this.code=J.code,this.retryable=J.retryable,$.status!==void 0)this.status=$.status}}var SZ=60;class GJ{model;target;options;constructor(J,$){this.target=J,this.options=$,this.model=$.model}url(J){return`${this.target.base}/realtime${J}${this.target.query}`}sidebandUrl(J){let $=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),Q=this.target.query?`${this.target.query}&`:"?";return`${$}/realtime${Q}call_id=${encodeURIComponent(J)}`}async createCall(J){let $=J.flow??this.options.callFlow??"unified",Q,Z;if($==="ephemeral")Q={authorization:`Bearer ${(await this.clientSecret({session:J.session,ttlSeconds:SZ,signal:J.signal})).value}`,"content-type":"application/sdp"},Z=J.sdp;else{let V=new FormData;V.set("sdp",J.sdp),V.set("session",JSON.stringify(qJ(J.session??{},this.model))),Q=await this.target.headers(),Z=V}if(J.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=this.url("/calls"),K=await this.request(J.webrtcFilter?`${W}${W.includes("?")?"&":"?"}webrtcfilter=on`:W,{method:"POST",headers:Q,body:Z},J.signal),X=await K.text(),G=AZ(K);if(!G)throw new f({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:X,callId:G}}async clientSecret(J={}){let $=J.ttlSeconds??OZ;if(!Number.isInteger($)||$<P9||$>N9)throw RangeError(`ttlSeconds must be a whole number from ${P9} to ${N9}, got ${$}.`);let Q={...await this.target.headers(),"content-type":"application/json"};if(J.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:Q,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:qJ(J.session??{},this.model)})},J.signal)).json();if(typeof W?.value!=="string")throw new f({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:W.value,expiresAt:Number(W.expires_at??0),session:W.session,callsUrl:this.url("/calls")}}async hangup(J,$={}){try{await this.request(this.url(`/calls/${encodeURIComponent(J)}/hangup`),{method:"POST",headers:await this.target.headers()},$.signal)}catch(Q){if(C9(Q,J))return;throw Q}}sideband(J,$={}){return new xJ({...$,callId:J,url:this.sidebandUrl(J),headers:this.target.headers,webSocket:$.webSocket??this.options.webSocket,hangup:()=>this.hangup(J)})}async request(J,$,Q){try{return await c(J,$,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:Q,fetchImpl:this.options.fetchImpl})}catch(Z){if(Q?.aborted)throw Z;throw new f(E(Z),{cause:Z,...Z instanceof w?{status:Z.status}:{}})}}}function C9(J,$){if(!(J instanceof f)||J.status!==404)return!1;let Q=J.cause instanceof w?J.cause.body:void 0,Z=Q?.error??Q,W=String(Z?.code??"").toLowerCase(),K=String(Z?.message??"").toLowerCase();if(W.includes("call"))return!0;if(K.includes($.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function AZ(J){let $=J.headers.get("location");if(!$)return;let Q=$.split("?")[0].replace(/\/+$/,""),Z=Q.slice(Q.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function k$(J,$){let{capabilities:Q}=$,Z={model:$.model,input:RZ(J.messages,Q,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=fZ(J.tools,Q);if(W.length>0){if(Z.tools=W,!Q.parallelToolCalls)Z.parallel_tool_calls=!1}if(J.output)Z.text={format:{type:"json_schema",name:J.output.name,schema:J.output.schema,strict:J.output.strict}};if(J.reasoning&&Q.reasoning)Z.reasoning=J.reasoning==="none"?{effort:"none"}:{effort:J.reasoning,summary:"auto"};if(typeof J.temperature==="number")Z.temperature=J.temperature;if(typeof J.maxOutputTokens==="number")Z.max_output_tokens=J.maxOutputTokens;return Z}function RZ(J,$,Q){let Z=[],W=new Map;if($.toolSearch){for(let K of Q??[])if(IJ(K))W.set(K.name,K)}for(let K of J){let X=K.role,G=[],V=()=>{if(G.length===0)return;Z.push({type:"message",role:X,content:G}),G=[]};for(let Y of K.content??[])switch(Y.type){case"text":{if(!Y.text)break;G.push(a(X,Y.text));break}case"output":{if(Y.partial)break;G.push(a(X,JSON.stringify(Y.value)));break}case"file":{if(X==="assistant")break;let H=jZ(Y);if(!$.fileInput){if(H)G.push(a(X,j$(Y,!1)));break}if(Y.fileId?.startsWith(m))throw Error(`FilePart.fileId holds a gemi attachment id (${Y.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!Y.fileId&&!H)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(Y.providerRejected){if(H)G.push(a(X,j$(Y,!1)));G.push(a(X,O$(Y.name)));break}if(H)G.push(a(X,j$(Y,!!Y.fileId)));if(Y.fileId)G.push(kZ(Y));break}case"reasoning":{V();let H=IZ(Y);if(H)Z.push(H);break}case"tool-call":{if(Y.partial)break;if(V(),$.toolSearch&&Array.isArray(Y.toolSearches))for(let D of Y.toolSearches)Z.push(...bZ(D,Q??[]));let H={type:"function_call",call_id:Y.toolCallId,name:String(Y.name),arguments:JSON.stringify(Y.input??{})};if(Y.namespace&&W.has(Y.namespace))H.namespace=Y.namespace;Z.push(H);break}case"tool-result":{V(),Z.push({type:"function_call_output",call_id:Y.toolCallId,output:wZ(Y)});break}}V()}return EZ(Z)}var TZ="No result was recorded for this tool call. Assume it did not complete.";function EZ(J){let $=new Set,Q=new Set,Z=[];for(let K of J){if(K.type==="function_call"){let X=String(K.call_id);if($.has(X))continue;$.add(X)}else if(K.type==="function_call_output"){let X=String(K.call_id);if(!$.has(X)||Q.has(X))continue;Q.add(X)}Z.push(K)}if(Q.size===$.size)return Z;let W=[];for(let K of Z){if(W.push(K),K.type!=="function_call")continue;let X=String(K.call_id);if(Q.has(X))continue;Q.add(X),W.push({type:"function_call_output",call_id:X,output:TZ})}return W}function a(J,$){return{type:J==="assistant"?"output_text":"input_text",text:$}}function jZ(J){let $=J.attachmentId;return typeof $==="string"&&$.startsWith(m)?$:void 0}function j$(J,$){let Q=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)Q.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)Q.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${Q.join(" ")}`;return $?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function kZ(J){let $=J.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":xZ(J.name))?"input_image":"input_file",file_id:J.fileId}}function xZ(J){let $=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return $?.[1]!==void 0&&qZ.has($[1])}var qZ=new Set(["jpeg","jpg","png","gif","webp"]);function IZ(J){if(!J.id)return null;let $={type:"reasoning",id:J.id};return $.summary=J.text?[{type:"summary_text",text:J.text}]:[],$}function wZ(J){if(J.status==="ok"){let $=J.modelOutput!==void 0?J.modelOutput:J.output;return typeof $==="string"?$:JSON.stringify($??null)}if(J.status==="running"){let $=J.job?.summary===void 0?"":` Started with: ${JSON.stringify(J.job.summary)}.`;return`Started background job ${J.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${$}`}if(J.status==="denied"){let $=J.reason?` Reason given: ${J.reason}`:"";if(J.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(J.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function bZ(J,$){let Q=new Set(_9(J?.loaded)),Z=_9(J?.namespaces),W=new Set(Z),K=[];for(let G of $)if(IJ(G)){if(!W.has(G.name))continue;let V=G.tools.filter((Y)=>Q.size===0||Q.has(Y.name));if(V.length===0)continue;K.push({type:"namespace",name:G.name,description:G.description,tools:V.map((Y)=>t(Y,!0))})}else if(G.deferred&&Q.has(G.name))K.push(t(G,!0));if(K.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:J.arguments&&typeof J.arguments==="object"?J.arguments:{paths:Z.length>0?Z:[...Q]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function _9(J){return Array.isArray(J)?J.filter(($)=>typeof $==="string"):[]}function IJ(J){return Array.isArray(J.tools)}function fZ(J,$){if(!J||J.length===0)return[];if(!$.toolSearch){let W=[];for(let K of J)if(IJ(K))for(let X of K.tools)W.push(t(X,!1));else W.push(t(K,!1));return W}let Q=[],Z=!1;for(let W of J)if(IJ(W)){let K=W.tools.map((X)=>{if(X.deferred)Z=!0;return t(X,!0)});Q.push({type:"namespace",name:W.name,description:W.description,tools:K})}else{if(W.deferred)Z=!0;Q.push(t(W,!0))}if(Z)Q.push({type:"tool_search"});return Q}function t(J,$){let Q={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if($&&J.deferred)Q.defer_loading=!0;return Q}class r{static models(){return[]}normalizeError(J){return E(J)}}var M9=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class x$ extends r{model;capabilities;config;constructor(J,$={}){super();this.model=J,this.capabilities=T$(J),this.config=$}static model(J,$){return new x$(J,$)}static models(){return M9}stream(J){let $=k$(J,{model:this.model,capabilities:this.capabilities});return A$(this.endpoint(),$,{signal:J.signal,structuredOutput:Boolean(J.output),files:L$(J.messages)})}upload(J){return R$(this.endpoint(),J)}endpoint(){return S$(XJ(this.config))}get realtime(){return new GJ(XJ(this.config,{timeoutMs:E$}),{model:this.model})}}class q$ extends r{model;capabilities;config;constructor(J,$={}){super();this.model=J,this.capabilities=T$(J),this.config=$}static model(J,$){return new q$(J,$)}static models(){return M9}stream(J){let $=k$(J,{model:this.deployment(),capabilities:this.capabilities});return A$(this.endpoint(),$,{signal:J.signal,structuredOutput:Boolean(J.output),files:L$(J.messages)})}upload(J){return R$(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return S$(YJ(this.config))}get realtime(){return new GJ(a8(this.config,{timeoutMs:E$}),{model:this.deployment(),callFlow:"ephemeral"})}}class wJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,$){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return!0;let Z=this.now();if(Z<Q.openUntil)return!1;if(Q.probeUntil!==void 0&&Z<Q.probeUntil)return!1;return Q.probeUntil=Z+$.cooldownMs,!0}record(J,$,Q){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if($==="success")return this.entries.delete(J),W?"closed":void 0;if($==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let $=this.entries.get(J);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}var S9=Symbol("timed-out");class VJ extends r{model;capabilities;entries;options;circuit;constructor(J,$={}){super();if(J.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of J)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=[...J];let Q=$.circuit;if(Q){let Z=Q.failures??3,W=Q.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 K=new Set;for(let G of J){let V=I$(G);if(K.has(V))throw Error(`FallbackProvider: two legs share the circuit key "${V}". Give one of them a \`circuitKey\`.`);K.add(V)}let X=Q.store??new wJ;this.options={...$,circuit:{...Q,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=vZ(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new VJ(J,$)}from(J){if(!Number.isInteger(J)||J<0||J>=this.entries.length)throw RangeError(`FallbackProvider.from(${J}): the chain has ${this.entries.length} entries.`);return new VJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new VJ([$],this.options)}upload(J){return this.entries[0].provider.upload(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let $,Q=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let K=this.entries[W],X=W===this.entries.length-1,G=K.provider.model;if(this.circuit&&!X&&!await this.allow(K))continue;Z+=1;let V=!1,Y=async(_)=>{if(V)return;V=!0,await this.record(W,K,_)},H=new AbortController,D=()=>H.abort(Q?.reason);if(Q?.aborted)H.abort(Q.reason);else Q?.addEventListener("abort",D,{once:!0});let z=[],F=!1,U=!1,N,B,P,L=!1,O,j=!1,k=(_)=>{let R=$?A(A(S(),$),_.usage):_.usage;return $=void 0,{..._,usage:R}};try{O=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let _=!0;for(;;){let R=_&&K.timeoutMs!==void 0?await yZ(O.next(),K.timeoutMs):await O.next();if(R===S9){L=!0,P={error:{code:"provider_error",message:`${G} sent nothing within ${K.timeoutMs}ms.`,retryable:!0}};break}if(_=!1,R.done){j=!0;break}let C=R.value;if(C.type==="finish"&&C.model)B=C.model;if(F){if(C.type==="finish")N=A(N??S(),C.usage),U=!0,yield k(C);else{if(C.type==="error")P={error:C.error};yield C}continue}if(jJ(C)){F=!0,await Y("success"),yield*z.splice(0),yield C;continue}if(C.type==="error")P={error:C.error,...C.status!==void 0?{status:C.status}:{},...C.requestId!==void 0?{requestId:C.requestId}:{}};else if(C.type==="finish"){if(N=A(N??S(),C.usage),C.reason==="error"&&!P)P={error:{code:"provider_error",message:`${G} ended the call with an error and did not say which.`,retryable:!1}}}z.push(C)}}catch(_){let R=K.provider.normalizeError(_);if(F){if(R.code!=="aborted")yield{type:"error",error:R,...s(_)};this.report({index:W,model:G,responseModel:B,attempt:Z,usage:N,outcome:w$(R),error:R}),yield k({type:"finish",reason:R.code==="aborted"?"aborted":"error",usage:S(),...B?{model:B}:{}});return}P={error:R,...s(_)}}finally{if(Q?.removeEventListener("abort",D),!j)H.abort(),O?.return?.()?.catch(()=>{})}if(F){if(!U&&$)yield{type:"finish",reason:P?"error":"stop",usage:$},$=void 0;this.report({index:W,model:G,responseModel:B,attempt:Z,usage:N,outcome:P?w$(P.error):"ok",...P?{error:P.error}:{}});return}if(Q?.aborted){await Y("none"),this.report({index:W,model:G,responseModel:B,attempt:Z,usage:N,outcome:"aborted"}),yield k({type:"finish",reason:"aborted",usage:N??S(),...B?{model:B}:{}});return}if(!P){await Y("success"),this.report({index:W,model:G,responseModel:B,attempt:Z,usage:N,outcome:"ok"});for(let _ of z)yield _.type==="finish"?k(_):_;return}let I=!X&&P.error.code!=="aborted"&&this.shouldFallBack(P.error,{index:W,model:G,timedOut:L,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}});if(await Y(I?"failure":"none"),this.report({index:W,model:G,responseModel:B,attempt:Z,usage:N,outcome:I?"fallback":w$(P.error),error:P.error}),I){if(N)$=A($??S(),N);continue}let x=!1,d;for(let _ of z){if(_.type==="finish"){d=_;continue}if(_.type==="error")x=!0;yield _}if(!x&&P.error.code!=="aborted")yield{type:"error",error:P.error,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}};yield k({type:"finish",reason:P.error.code==="aborted"?"aborted":d?.reason??"error",usage:N??S(),...B?{model:B}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(I$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=I$($),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:$.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,$){let Q=this.options.fallbackOn??((Z)=>Z.retryable);try{return Q(J,$)}catch{return!1}}report(J){if(J.usage===void 0)delete J.usage;if(J.responseModel===void 0)delete J.responseModel;try{this.options.onUsage?.(J)}catch{}}}function I$(J){return J.circuitKey??J.provider.model}function w$(J){return J.code==="aborted"?"aborted":"failed"}function vZ(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch)}}function yZ(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(S9),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function hZ(J,$,Q={}){let Z=Q.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let K=0;K<J.entries.length;K++){let X=J.leg(K),G={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{G.results.push(await $(X,{index:K,sample:V}))}catch(Y){G.errors.push({sample:V,error:Y})}W.push(G)}return W}class fJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var zJ="ask_agent",gZ={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},uZ={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 HJ(J={}){return[{name:J.name??zJ,description:J.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 bJ=new Map;class p{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(J){return new p(J)}static get(J){return bJ.get(J)}static async endAll(J){await Promise.all([...bJ.values()].map(($)=>$.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...gZ,...A9(J.limits)},this.lines={...uZ,...A9(J.lines)},this.delegateName=J.delegate?.name??zJ;let $=new Set(HJ(J.delegate).map((Q)=>Q.name));for(let Q of J.tools??[]){if($.has(Q.tool.name)||this.toolHandlers.has(Q.tool.name))throw Error(`VoiceBridge: two tools are named "${Q.tool.name}".`);this.toolHandlers.set(Q.tool.name,Q)}if("realtime"in J.call){let{realtime:Q,callId:Z}=J.call;this.callId=Z,this.sideband=Q.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=J.call.callId??J.call.sideband.callId,this.sideband=J.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise((Q)=>this.resolveEnded=Q),bJ.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(J){this.body=J;let $=this.params.contextNote?.(J);if($)this.sideband.addNote($)}end(J="hangup",$){return this.ending??=this.finish(J,$??null)}async listen(){for await(let J of this.sideband){try{this.params.onEvent?.(J)}catch{}this.closingWaiter?.(J),await this.handle(J)}}async handle(J){switch(J.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.usage;if($){this.usage=A(this.usage,$);let Q=this.info();this.hook(()=>this.params.onUsage?.($,Q))}return}case"conversation.item.input_audio_transcription.completed":{let $=J;if(this.say("user",String($.transcript??"")),$.transcriptionUsage||$.transcriptionSeconds!==void 0){this.transcription={usage:$.transcriptionUsage?A(this.transcription.usage,$.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+($.transcriptionSeconds??0)};let Q=this.info(),Z={...$.transcriptionUsage?{usage:$.transcriptionUsage}:{},...$.transcriptionSeconds!==void 0?{seconds:$.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}return}case"response.output_audio_transcript.done":this.say("assistant",String(J.transcript??""));return;case"response.output_text.done":this.say("assistant",String(J.text??""));return;case"response.function_call_arguments.done":{let $=J;if(this.touch(),!this.ending)this.call($.call_id,$.name,$.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let $=J.error;if(this.errors.push({code:$?.code,message:String($?.message??"")}),this.pendingCreate&&$?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,$.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let $=J;if(!this.ending&&!$.byClient)this.end($.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,$){if($.trim())this.transcript.push({role:J,text:$,at:Date.now()})}call(J,$,Q){let Z=cZ(Q);if($===this.delegateName){let K=typeof Z.request==="string"?Z.request.trim():"";if(!K)return this.answer(J,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:K,status:"queued"},turn:{text:K},callId:J})}let W=this.toolHandlers.get($);if(W)return void this.runTool(J,W,Z);switch($){case"stop_work":{let K=this.running;if(K)K.stopRequested=!0,K.handle?.stop({reason:"Stopped by voice."});let X=this.dropQueue();return this.answer(J,{stopped:Boolean(K),dropped:X})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((K)=>K.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(J,{status:"error",message:"There is no open question."});let K=typeof Z.answer==="string"?Z.answer:"",X=typeof Z.approve==="boolean"?Z.approve:void 0,G=this.pending.map((V)=>mZ(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:G},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${$}.`})}}enqueue(J){if(!this.running){this.requests.push(J.record),this.run(J);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(J.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(J.record),this.queue.push(J),this.answer(J.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),J.callId=void 0}async run(J){this.running=J,J.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let $=new Set;await this.waitForThread($);let Q=await this.latestBody();while(!J.stopRequested&&await this.waitForThread($));if(J.stopRequested||this.ending){J.record.status="dropped",this.complete(J,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:Q,turn:J.turn})}catch(K){J.record.status="refused",this.complete(J,{status:"refused",message:K instanceof Error?K.message:"The request could not be started."});return}J.handle=Z,J.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(J.record.status="done",J.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(J,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(J,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(J,{status:"stopped",text:W.text});else this.complete(J,{status:"done",text:W.text})}catch($){J.record.status="done",this.complete(J,{status:"failed",message:$ instanceof Error?$.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let $=this.queue.shift();if($&&!this.ending)this.run($);else this.touch()}}async runTool(J,$,Q){let Z=$.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(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let K={name:Z,status:"running"};this.toolCalls.push(K),this.toolsRunning+=1,this.pauseIdle();let X=new AbortController,G=$.timeoutMs??this.limits.toolTimeoutMs,V,Y;try{let D=await Promise.race([$.run(Q,{sessionId:this.sessionId,signal:X.signal}),new Promise((z,F)=>{V=setTimeout(()=>{F(new g(`"${Z}" took longer than ${Math.round(G/1000)} s.`)),X.abort()},G)})]);K.status="done",Y={status:"done",output:this.clip(D)}}catch(D){if(D instanceof fJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let z=D instanceof g?D.message:"The tool failed.";if(!(D instanceof g))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);K.status="failed",K.message=z,Y={status:"failed",message:z}}finally{clearTimeout(V),K.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let H=this.info();if(this.hook(()=>this.params.onToolCall?.({...K},H)),!this.ending)this.answer(J,Y)}clip(J){let $;try{$=JSON.stringify(J)}catch{return String(J)}if($===void 0||$.length<=this.limits.toolOutputChars)return J;return`${$.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${$.length} characters in all)`}async waitForThread(J=new Set){let $=this.params.liveRuns;if(!$)return!1;let Q=await $.find({threadId:this.threadId}),Z=Q&&!J.has(Q.runId)?$.get(Q.runId):null;if(!Q||!Z)return!1;return J.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let $=await J.get(this.sessionId).catch(()=>null);if($)this.body=$.body;return this.body}async follow(J){let $=this.params.progress??pZ();try{for await(let Q of J.run){let Z=$(Q);if(Z)this.note(Z)}}catch{}}complete(J,$){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,$),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify($)}`);this.respond()}answer(J,$){this.sideband.functionOutput(J,$),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let J=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=J,this.sideband.send({type:"response.create",event_id:J})}questions(){return this.pending.map((J)=>({kind:J.kind,tool:String(J.name),input:J.input}))}dropQueue(){let J=this.queue.splice(0);for(let $ of J)$.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let $=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if($<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),$)}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 J=this.info();this.hook(()=>this.params.onTick?.(J))}hook(J){this.hooks=this.hooks.then(async()=>{try{await J()}catch($){if($ instanceof fJ)this.end("usage",$.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",$),this.end("error",this.lines.error)}})}tampered(J){let $=this.params.session;if(!$||!J)return!1;if($.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==$.instructions)return!0;if(Array.isArray(J.tools)){let Q=new Set([...HJ(this.params.delegate),...$.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if(Q.size!==Z.size||[...Q].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,$){for(let X of this.timers)clearTimeout(X);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),$&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine($);if(J!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,K={sessionId:this.sessionId,...this.callId?{callId:this.callId}:{},threadId:this.threadId,reason:J,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};bJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(K)}catch(X){console.error("[gemi/ai] a voice session's onEnd threw.",X)}return this.resolveEnded(K),K}async hangUp(){try{await this.hangupCall()}catch(J){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",J),this.errors.push({code:"hangup_failed",message:J instanceof Error?J.message:String(J)});let $;await Promise.race([this.sideband.closed,new Promise((Q)=>$=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout($),this.sideband.close()}}async closingLine(J){await new Promise(($)=>{let Q=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",K,X=setTimeout(G,this.limits.closingLineMs);function G(){clearTimeout(X),$()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(Y)=>{let H=Y;if(H.type==="sideband.closed")return G();if(W==="cancelling"){if(H.type==="response.done"||H.type==="error"&&H.error?.event_id===Z)V();return}if(H.type==="error"&&H.error?.event_id===Q)return G();if(H.type==="response.created"&&!K){K=H.response?.id;return}let D=(z)=>!K||!z||z===K;if(H.type==="response.done"&&D(H.response?.id))W="playing";else if(H.type==="output_audio_buffer.stopped"&&W==="playing"&&D(H.response_id))G()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function A9(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function cZ(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function mZ(J,$,Q){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:$};if(J.kind==="approval")return{...Z,approve:Q===!0,...$?{reason:$}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function pZ(){let J=new Set;return($)=>{if($.type==="tool-call"){if($.part.partial||$.resent||J.has($.part.toolCallId))return;return J.add($.part.toolCallId),`running ${String($.part.name)}`}if($.type==="tool-progress"){let Q=$.data;if(typeof Q==="string")return Q;if(Q&&typeof Q==="object")for(let Z of["message","label","title"]){let W=Q[Z];if(typeof W==="string"&&W)return W}}return}}var R9="http://gemi.internal/__gemi__/voice/mcp";async function b$(J,$){if(!$.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}=J,Z=J.scopes??Q.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:$.user,via:"voice",id:`voice:${$.sessionId}`,scopes:Z}});return(await Q.available(W(T9()),J.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(G,V)=>{let Y=T9();return h.run(Y,async()=>{return await J.authorize?.({name:X.name,input:G,sessionId:V.sessionId}),Q.execute(W(Y),X.name,G,void 0,{signal:V.signal})},{user:$.user})}}))}function T9(){return new q(new Request(R9,{method:"POST"}),{},"api",new URL(R9).pathname)}class f${records=new Map;retainEndedMs;constructor(J={}){this.retainEndedMs=J.retainEndedMs??600000}async create(J){this.sweep(),this.records.set(J.id,structuredClone(J))}async get(J){let $=this.records.get(J);return $?structuredClone($):null}async update(J,$){let Q=this.records.get(J);if(!Q)return;this.records.set(J,{...Q,...structuredClone($),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[$,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<J)this.records.delete($)}}var v$=new f$;var E9=new WeakMap,j9=100;class b9{threadsTable;messagesTable;sql;dialect;connection;constructor(J,$={}){this.threadsTable=k9($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=k9($.messagesTable??"gemi_agent_messages","messages"),this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){let J=iZ(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($)}async createThread(J){let $=this.q(),Q=crypto.randomUUID(),Z=J.userId===void 0||J.userId===null?null:String(J.userId),W=this.clock($);return await $`
|
|
146
|
+
`)}}if($.length>0){let V=X($);if(V)yield V}let G=K();if(G)yield G}async function*F9(J,$={}){let Q=new Map,Z=new Set,W,K=!1,X,G=(V,Y)=>({type:"finish",reason:V,usage:Y,...X?{model:X}:{}});for await(let V of LZ(J)){if(V.data==="[DONE]")break;let Y;try{Y=JSON.parse(V.data)}catch{continue}let H=typeof Y.type==="string"?Y.type:V.event,D=Y.response?.model;if(typeof D==="string"&&D)X=D;switch(H){case"response.output_text.delta":{let z=String(Y.delta??"");if(!z)break;yield $.structuredOutput?{type:"output-delta",delta:z}:{type:"text-delta",delta:z};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let z=String(Y.delta??"");if(!z)break;yield{type:"reasoning-delta",delta:z,id:Y.item_id};break}case"response.output_item.added":{let z=Y.item;if(!z)break;if(z.type==="function_call"){let B=String(z.id??Y.item_id??z.call_id??"");Q.set(B,{callId:String(z.call_id??B),name:String(z.name??""),namespace:typeof z.namespace==="string"&&z.namespace?z.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let z=Q.get(String(Y.item_id??""));if(!z)break;let B=String(Y.delta??"");if(!B)break;yield{type:"tool-call-delta",toolCallId:z.callId,name:z.name,argsDelta:B,...z.namespace?{namespace:z.namespace}:{}};break}case"response.function_call_arguments.done":{let z=String(Y.item_id??""),B=Q.get(z);if(!B)break;B.done=!0,yield{type:"tool-call",toolCallId:B.callId,name:B.name,args:String(Y.arguments??""),...B.namespace?{namespace:B.namespace}:{}};break}case"response.output_item.done":{let z=Y.item;if(!z)break;if(z.type==="function_call"){let B=String(z.id??Y.item_id??z.call_id??""),U=Q.get(B);if(U?.done)break;let N=(typeof z.namespace==="string"?z.namespace:"")||U?.namespace;if(yield{type:"tool-call",toolCallId:String(z.call_id??B),name:String(z.name??U?.name??""),args:String(z.arguments??""),...N?{namespace:N}:{}},U)U.done=!0;break}if(z.type==="tool_search_call"||z.type==="tool_search_output"){if(z.type==="tool_search_call"&&z.arguments!==void 0)W=z.arguments;let B=OZ(z);if(B.loaded.length===0&&B.namespaces.length===0)break;let U=String(z.tool_search_call_id??z.id??"");if(Z.has(U))break;Z.add(U);let N=W;W=void 0,yield{type:"tool-search",...B,...N!==void 0&&N!==null?{arguments:N}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(Y.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{K=!0,yield G("stop",S$(Y.response?.usage));break}case"response.incomplete":{K=!0;let z=S$(Y.response?.usage),B=Y.response?.incomplete_details?.reason;if(B==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:CZ(Y.response?.content_filters),retryable:!1}},yield G("error",z);break}yield G(B==="max_output_tokens"?"length":"stop",z);break}case"response.failed":case"error":{K=!0;let z=Y.response?.error??Y.error??Y;yield{type:"error",error:_Z(z)},yield G("error",S$(Y.response?.usage));break}}if(K)return}if(!K)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield G("error",b())}function OZ(J){let $=[],Q=[];return P9(J.results??J.tools??J.loaded??J.output,$,Q,0),{loaded:A$($),namespaces:A$(Q)}}function P9(J,$,Q,Z){if(!Array.isArray(J)||Z>4)return;for(let W of J){if(typeof W==="string"){$.push(W);continue}if(!W||typeof W!=="object")continue;let K=W,X=typeof K.name==="string"?K.name:typeof K.tool_name==="string"?K.tool_name:"",G=K.tools??K.functions;if(Array.isArray(G)){if(X)Q.push(X);P9(G,$,Q,Z+1);continue}if(X)$.push(X)}}function A$(J){return J.filter(($,Q)=>J.indexOf($)===Q)}function CZ(J){if(!Array.isArray(J))return"The provider's content filter blocked this request.";let Q=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,K=W.content_filter_results;if(!K||typeof K!=="object")continue;for(let[X,G]of Object.entries(K))if(G&&typeof G==="object"&&G.filtered===!0)Q.push(`${X} (${String(W.source_type??"unknown")})`)}return Q.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${A$(Q).join(", ")}.`}function _Z(J){let $=typeof J?.message==="string"?J.message:"The provider stream failed.",Q=String(J?.code??"").toLowerCase();if(Q==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Q==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Q.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function b(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function S$(J){if(!J)return b();let $=Number(J.input_tokens??0),Q=Number(J.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J.total_tokens??$+Q)},W=J.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let K=J.input_tokens_details?.cached_tokens;if(typeof K==="number")Z.cachedInputTokens=K;return Z}async function*N9(J){if(!J)return;let $=J.getReader(),Q=new TextDecoder;try{while(!0){let{done:W,value:K}=await $.read();if(W)break;if(K)yield Q.decode(K,{stream:!0})}let Z=Q.decode();if(Z)yield Z}finally{$.releaseLock()}}function R$(J){return{responsesUrl:`${J.base}/responses${J.query}`,filesUrl:`${J.base}/files${J.query}`,headers:J.headers,timeoutMs:J.timeoutMs,maxRetries:J.maxRetries}}async function*E$(J,$,Q){let Z=$,W=new Set,K=0,X=Math.max(0,J.maxRetries),G=J.random??Math.random,V,Y=(D)=>{if(!V)return D;let z=A(A(b(),V),D.usage);return V=void 0,{...D,usage:z}},H=()=>Y({type:"finish",reason:"aborted",usage:b()});for(let D=0;;D++){let z;while(z===void 0)try{z=await c(J.responsesUrl,{method:"POST",headers:{...await J.headers(),"content-type":"application/json"},body:JSON.stringify(Z)},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,signal:Q.signal,fetchImpl:J.fetchImpl,sleep:J.sleep,random:J.random})}catch(F){let P=K<z9?D9(Z,F,Q.files).filter((O)=>!W.has(O)):[];if(P.length>0){K++;let O=T(F).message;for(let j of P)W.add(j),yield{type:"file-rejected",fileId:j,message:O,...s(F)};Z=B9(Z,new Set(P),Q.files);continue}let L=T(F);if(L.code==="aborted"){yield H();return}yield{type:"error",error:L,...s(F)},yield Y({type:"finish",reason:"error",usage:b()});return}let B=[],U=!1,N;try{for await(let F of F9(N9(z.body),{structuredOutput:Q.structuredOutput})){if(U){yield F.type==="finish"?Y(F):F;continue}if(xJ(F)){U=!0,yield*B.splice(0),yield F;continue}if(F.type==="error")N=F.error;B.push(F)}}catch(F){let P=T(F);if(P.code==="aborted"||Q.signal?.aborted){yield H();return}if(U){yield{type:"error",error:P},yield Y({type:"finish",reason:"error",usage:b()});return}N=P,B.push({type:"error",error:P},{type:"finish",reason:"error",usage:b()})}if(U)return;if(N?.retryable&&D<X&&!Q.signal?.aborted){for(let F of B)if(F.type==="finish")V=A(V??b(),F.usage);try{await P$(TJ(D,G),Q.signal,J.sleep)}catch{yield H();return}continue}for(let F of B)yield F.type==="finish"?Y(F):F;return}}async function T$(J,$,Q="user_data"){let Z=new FormData;Z.set("purpose",Q),Z.set("file",$);let K=await(await c(J.filesUrl,{method:"POST",headers:await J.headers(),body:Z},{maxRetries:J.maxRetries,timeoutMs:J.timeoutMs,fetchImpl:J.fetchImpl})).json();if(!K?.id)throw Error("The provider accepted the upload but returned no file id.");return K.id}function j$(J){let $=MZ(J);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Q=SZ($);if(Q?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Q.major>1,toolSearch:U9(Q)};if(Q?.kind==="gpt")return{reasoning:Q.major>=5,structuredOutput:Q.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Q.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:U9(Q)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function U9(J){if(J.kind==="o")return J.major>=5;return J.major>5||J.major===5&&J.minor>=2}function MZ(J){return J.trim().toLowerCase()}function SZ(J){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(J);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Q=/^o(\d+)(?:[-.]|$)/.exec(J);if(Q?.[1])return{kind:"o",major:Number(Q[1]),minor:0};return null}var AZ={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function RZ(J){if(typeof J!=="string")return;let $;try{$=JSON.parse(J)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let Q=AZ[$.type];if(Q)$.type=Q;if($.type==="response.done"&&$.response?.usage)$.usage=qJ($.response.usage);if($.type==="conversation.item.input_audio_transcription.completed"&&$.usage)if($.usage.type==="duration"){let Z=Number($.usage.seconds);if(Number.isFinite(Z))$.transcriptionSeconds=Z}else $.transcriptionUsage=qJ($.usage);return $}var L9=1,EZ=500;function TZ(J,$){let Q=globalThis.WebSocket;if(!Q)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new Q(J,{headers:$.headers})}class IJ{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(J){this.init=J,this.callId=J.callId,this.ready=new Promise(($,Q)=>{this.resolveReady=$,this.rejectReady=Q}),this.ready.catch(()=>{}),this.closed=new Promise(($)=>this.resolveClosed=$),this.open()}send(J){if(this.finished||this.closing)return;let $=JSON.stringify(J);if(this.socket?.readyState===L9)this.socket.send($);else this.outbox.push($)}updateSession(J){this.send({type:"session.update",session:wJ(J)})}addItem(J){this.send({type:"conversation.item.create",item:J})}addNote(J){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:J}]})}functionOutput(J,$){this.addItem({type:"function_call_output",call_id:J,output:typeof $==="string"?$:JSON.stringify($)})}createResponse(J={}){let $={};if(J.instructions!==void 0)$.instructions=J.instructions;if(J.toolChoice!==void 0)$.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};if(J.outputModalities)$.output_modalities=J.outputModalities;if(J.conversation)$.conversation=J.conversation;if(J.metadata)$.metadata=J.metadata;Object.assign($,J.vendor),this.send(Object.keys($).length?{type:"response.create",response:$}:{type:"response.create"})}cancelResponse(J){this.send(J?{type:"response.cancel",response_id:J}:{type:"response.cancel"})}on(J){return this.listeners.add(J),()=>this.listeners.delete(J)}[Symbol.asyncIterator](){let J={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(J),{next:async()=>{for(;;){let Q=J.queue.shift();if(Q)return{value:Q,done:!1};if(J.done)return this.subscribers.delete(J),{value:void 0,done:!0};await new Promise((Z)=>J.wake=Z),J.wake=void 0}},return:async()=>{return J.done=!0,J.queue.length=0,this.subscribers.delete(J),{value:void 0,done:!0}}}}close(J=1000,$="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=L9)this.socket.close(J,$);else this.finish(J,$,!0)}async hangup(){try{await this.init.hangup()}catch(J){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw J}this.close(1000,"hangup")}async open(){let J;try{let Q=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);J=(this.init.webSocket??TZ)(this.init.url,{headers:Q})}catch(Q){return this.dropped(1006,Q instanceof Error?Q.message:String(Q),!1)}this.socket=J;let $=!1;J.addEventListener("open",()=>{$=!0;let Q=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let W of this.outbox.splice(0))J.send(W);if(this.resolveReady(),Q)this.emit({type:"sideband.reconnected",attempt:Z})}),J.addEventListener("message",(Q)=>{let Z=RZ(Q.data);if(Z)this.emit(Z)}),J.addEventListener("close",(Q)=>{if(this.socket!==J)return;this.dropped(Q.code??1006,Q.reason??"",$)}),J.addEventListener("error",()=>{})}dropped(J,$,Q){if(this.socket=void 0,this.closing)return this.finish(J,$,!0);let Z=this.init.reconnect?.attempts??3;if(!((J!==1000||!Q)&&this.failures<Z))return this.finish(J,$,!1);this.failures+=1;let K=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),K)}finish(J,$,Q){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:J,reason:$,byClient:Q};this.finalEvent=Z,this.emit(Z);for(let W of this.subscribers)W.done=!0,W.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${J} ${$}).`));this.resolveClosed(Z)}emit(J){if(this.backlog){if(this.backlog.push(J),this.backlog.length>EZ)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(J),$.wake?.()}for(let $ of this.listeners)try{$(J)}catch{}}}var k$=30000,O9=10,C9=7200,jZ=600,M9="gpt-live-transcribe";function kZ(J){return J.type==="transcription"}function xZ(J){if(J.language!==void 0&&J.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let W of J.keywords??[])if(/[<>\r\n]/.test(W))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(W)}.`);let $={model:J.model??M9};if(J.prompt!==void 0)$.prompt=J.prompt;if(J.keywords?.length)$.keywords=J.keywords;if(J.languages?.length)$.languages=J.languages;if(J.language!==void 0)$.language=J.language;if(J.delay!==void 0)$.delay=J.delay;let Q={transcription:$,turn_detection:J.turnDetection?S9(J.turnDetection):null};if(J.noiseReduction!==void 0)Q.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let Z={type:"transcription",audio:{input:Q}};if(J.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...J.vendor}}function qZ(J){if(!J)return{type:"object",properties:{}};return _9(J)?J.toJSONSchema():J}function wJ(J,$){if(kZ(J))return xZ(J);let Q={type:"realtime"},Z=J.model??$;if(Z)Q.model=Z;if(J.instructions!==void 0)Q.instructions=J.instructions;if(J.outputModalities)Q.output_modalities=J.outputModalities;if(J.maxOutputTokens!==void 0)Q.max_output_tokens=J.maxOutputTokens;if(J.truncation!==void 0)Q.truncation=J.truncation;if(J.tools)Q.tools=J.tools.map((X)=>({type:"function",name:X.name,...X.description?{description:X.description}:{},parameters:qZ(X.parameters)}));if(J.toolChoice!==void 0)Q.tool_choice=typeof J.toolChoice==="string"?J.toolChoice:{type:"function",name:J.toolChoice.name};let W={};if(J.turnDetection!==void 0)W.turn_detection=J.turnDetection&&S9(J.turnDetection);if(J.transcription!==void 0)W.transcription=J.transcription;if(J.noiseReduction!==void 0)W.noise_reduction=J.noiseReduction&&{type:J.noiseReduction};let K={};if(J.voice!==void 0)K.voice=J.voice;if(J.speed!==void 0)K.speed=J.speed;if(Object.keys(W).length||Object.keys(K).length)Q.audio={...Object.keys(W).length?{input:W}:{},...Object.keys(K).length?{output:K}:{}};return{...Q,...J.vendor}}function S9(J){let $={type:J.type};if(J.createResponse!==void 0)$.create_response=J.createResponse;if(J.interruptResponse!==void 0)$.interrupt_response=J.interruptResponse;if(J.type==="semantic_vad"){if(J.eagerness!==void 0)$.eagerness=J.eagerness}else{if(J.threshold!==void 0)$.threshold=J.threshold;if(J.prefixPaddingMs!==void 0)$.prefix_padding_ms=J.prefixPaddingMs;if(J.silenceDurationMs!==void 0)$.silence_duration_ms=J.silenceDurationMs;if(J.idleTimeoutMs!==void 0)$.idle_timeout_ms=J.idleTimeoutMs}return $}function qJ(J){let $=Number(J?.input_tokens??0),Q=Number(J?.output_tokens??0),Z={inputTokens:$,outputTokens:Q,totalTokens:Number(J?.total_tokens??$+Q)},W=J?.input_token_details??J?.input_tokens_details,K=J?.output_token_details??J?.output_tokens_details;if(typeof W?.cached_tokens==="number")Z.cachedInputTokens=W.cached_tokens;if(typeof W?.audio_tokens==="number")Z.audioInputTokens=W.audio_tokens;let X=W?.cached_tokens_details?.audio_tokens;if(typeof X==="number")Z.cachedAudioInputTokens=X;if(typeof W?.image_tokens==="number"&&W.image_tokens>0)Z.imageInputTokens=W.image_tokens;if(typeof K?.audio_tokens==="number")Z.audioOutputTokens=K.audio_tokens;return Z}class f extends Error{code;retryable;status;constructor(J,$={}){super(J.message,{cause:$.cause});if(this.name="RealtimeRequestError",this.code=J.code,this.retryable=J.retryable,$.status!==void 0)this.status=$.status}}var IZ=60;class GJ{model;target;options;constructor(J,$){this.target=J,this.options=$,this.model=$.model}url(J){return`${this.target.base}/realtime${J}${this.target.query}`}sidebandUrl(J){let $=this.target.base.replace(/^http(s?):/i,(Z,W)=>`ws${W}:`),Q=this.target.query?`${this.target.query}&`:"?";return`${$}/realtime${Q}call_id=${encodeURIComponent(J)}`}async createCall(J){let $=J.flow??this.options.callFlow??"unified",Q,Z;if($==="ephemeral")Q={authorization:`Bearer ${(await this.clientSecret({session:J.session,ttlSeconds:IZ,signal:J.signal})).value}`,"content-type":"application/sdp"},Z=J.sdp;else{let V=new FormData;V.set("sdp",J.sdp),V.set("session",JSON.stringify(wJ(J.session??{},this.model))),Q=await this.target.headers(),Z=V}if(J.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=this.url("/calls"),K=await this.request(J.webrtcFilter?`${W}${W.includes("?")?"&":"?"}webrtcfilter=on`:W,{method:"POST",headers:Q,body:Z},J.signal),X=await K.text(),G=wZ(K);if(!G)throw new f({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:X,callId:G}}async clientSecret(J={}){let $=J.ttlSeconds??jZ;if(!Number.isInteger($)||$<O9||$>C9)throw RangeError(`ttlSeconds must be a whole number from ${O9} to ${C9}, got ${$}.`);let Q={...await this.target.headers(),"content-type":"application/json"};if(J.safetyIdentifier)Q["OpenAI-Safety-Identifier"]=J.safetyIdentifier;let W=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:Q,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:wJ(J.session??{},this.model)})},J.signal)).json();if(typeof W?.value!=="string")throw new f({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:W.value,expiresAt:Number(W.expires_at??0),session:W.session,callsUrl:this.url("/calls")}}async hangup(J,$={}){try{await this.request(this.url(`/calls/${encodeURIComponent(J)}/hangup`),{method:"POST",headers:await this.target.headers()},$.signal)}catch(Q){if(A9(Q,J))return;throw Q}}sideband(J,$={}){return new IJ({...$,callId:J,url:this.sidebandUrl(J),headers:this.target.headers,webSocket:$.webSocket??this.options.webSocket,hangup:()=>this.hangup(J)})}async request(J,$,Q){try{return await c(J,$,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:Q,fetchImpl:this.options.fetchImpl})}catch(Z){if(Q?.aborted)throw Z;throw new f(T(Z),{cause:Z,...Z instanceof w?{status:Z.status}:{}})}}}function A9(J,$){if(!(J instanceof f)||J.status!==404)return!1;let Q=J.cause instanceof w?J.cause.body:void 0,Z=Q?.error??Q,W=String(Z?.code??"").toLowerCase(),K=String(Z?.message??"").toLowerCase();if(W.includes("call"))return!0;if(K.includes($.toLowerCase()))return!0;return/\bcall\b/.test(K)&&/not (be )?found|does not exist|no longer|ended/.test(K)}function wZ(J){let $=J.headers.get("location");if(!$)return;let Q=$.split("?")[0].replace(/\/+$/,""),Z=Q.slice(Q.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}function q$(J,$){let{capabilities:Q}=$,Z={model:$.model,input:bZ(J.messages,Q,J.tools),stream:!0};if(J.systemPrompt)Z.instructions=J.systemPrompt;let W=lZ(J.tools,Q);if(W.length>0){if(Z.tools=W,!Q.parallelToolCalls)Z.parallel_tool_calls=!1}if(J.output)Z.text={format:{type:"json_schema",name:J.output.name,schema:J.output.schema,strict:J.output.strict}};if(J.reasoning&&Q.reasoning)Z.reasoning=J.reasoning==="none"?{effort:"none"}:{effort:J.reasoning,summary:"auto"};if(typeof J.temperature==="number")Z.temperature=J.temperature;if(typeof J.maxOutputTokens==="number")Z.max_output_tokens=J.maxOutputTokens;return Z}function bZ(J,$,Q){let Z=[],W=new Map;if($.toolSearch){for(let K of Q??[])if(bJ(K))W.set(K.name,K)}for(let K of J){let X=K.role,G=[],V=()=>{if(G.length===0)return;Z.push({type:"message",role:X,content:G}),G=[]};for(let Y of K.content??[])switch(Y.type){case"text":{if(!Y.text)break;G.push(a(X,Y.text));break}case"output":{if(Y.partial)break;G.push(a(X,JSON.stringify(Y.value)));break}case"file":{if(X==="assistant")break;let H=yZ(Y);if(!$.fileInput){if(H)G.push(a(X,x$(Y,!1)));break}if(Y.fileId?.startsWith(m))throw Error(`FilePart.fileId holds a gemi attachment id (${Y.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!Y.fileId&&!H)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(Y.providerRejected){if(H)G.push(a(X,x$(Y,!1)));G.push(a(X,_$(Y.name)));break}if(H)G.push(a(X,x$(Y,!!Y.fileId)));if(Y.fileId)G.push(hZ(Y));break}case"reasoning":{V();let H=cZ(Y);if(H)Z.push(H);break}case"tool-call":{if(Y.partial)break;if(V(),$.toolSearch&&Array.isArray(Y.toolSearches))for(let D of Y.toolSearches)Z.push(...pZ(D,Q??[]));let H={type:"function_call",call_id:Y.toolCallId,name:String(Y.name),arguments:JSON.stringify(Y.input??{})};if(Y.namespace&&W.has(Y.namespace))H.namespace=Y.namespace;Z.push(H);break}case"tool-result":{V(),Z.push({type:"function_call_output",call_id:Y.toolCallId,output:mZ(Y)});break}}V()}return vZ(Z)}var fZ="No result was recorded for this tool call. Assume it did not complete.";function vZ(J){let $=new Set,Q=new Set,Z=[];for(let K of J){if(K.type==="function_call"){let X=String(K.call_id);if($.has(X))continue;$.add(X)}else if(K.type==="function_call_output"){let X=String(K.call_id);if(!$.has(X)||Q.has(X))continue;Q.add(X)}Z.push(K)}if(Q.size===$.size)return Z;let W=[];for(let K of Z){if(W.push(K),K.type!=="function_call")continue;let X=String(K.call_id);if(Q.has(X))continue;Q.add(X),W.push({type:"function_call_output",call_id:X,output:fZ})}return W}function a(J,$){return{type:J==="assistant"?"output_text":"input_text",text:$}}function yZ(J){let $=J.attachmentId;return typeof $==="string"&&$.startsWith(m)?$:void 0}function x$(J,$){let Q=[`id=${JSON.stringify(J.attachmentId)}`];if(J.name)Q.push(`name=${JSON.stringify(J.name)}`);if(J.mimeType)Q.push(`mimeType=${JSON.stringify(J.mimeType)}`);let Z=`attachment ${Q.join(" ")}`;return $?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function hZ(J){let $=J.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":gZ(J.name))?"input_image":"input_file",file_id:J.fileId}}function gZ(J){let $=/\.([a-z0-9]+)$/.exec(J?.trim().toLowerCase()??"");return $?.[1]!==void 0&&uZ.has($[1])}var uZ=new Set(["jpeg","jpg","png","gif","webp"]);function cZ(J){if(!J.id)return null;let $={type:"reasoning",id:J.id};return $.summary=J.text?[{type:"summary_text",text:J.text}]:[],$}function mZ(J){if(J.status==="ok"){let $=J.modelOutput!==void 0?J.modelOutput:J.output;return typeof $==="string"?$:JSON.stringify($??null)}if(J.status==="running"){let $=J.job?.summary===void 0?"":` Started with: ${JSON.stringify(J.job.summary)}.`;return`Started background job ${J.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${$}`}if(J.status==="denied"){let $=J.reason?` Reason given: ${J.reason}`:"";if(J.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(J.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${J.error?.code??"unknown"}): ${J.error?.message??"no message"}`}function pZ(J,$){let Q=new Set(R9(J?.loaded)),Z=R9(J?.namespaces),W=new Set(Z),K=[];for(let G of $)if(bJ(G)){if(!W.has(G.name))continue;let V=G.tools.filter((Y)=>Q.size===0||Q.has(Y.name));if(V.length===0)continue;K.push({type:"namespace",name:G.name,description:G.description,tools:V.map((Y)=>t(Y,!0))})}else if(G.deferred&&Q.has(G.name))K.push(t(G,!0));if(K.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:J.arguments&&typeof J.arguments==="object"?J.arguments:{paths:Z.length>0?Z:[...Q]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:K}]}function R9(J){return Array.isArray(J)?J.filter(($)=>typeof $==="string"):[]}function bJ(J){return Array.isArray(J.tools)}function lZ(J,$){if(!J||J.length===0)return[];if(!$.toolSearch){let W=[];for(let K of J)if(bJ(K))for(let X of K.tools)W.push(t(X,!1));else W.push(t(K,!1));return W}let Q=[],Z=!1;for(let W of J)if(bJ(W)){let K=W.tools.map((X)=>{if(X.deferred)Z=!0;return t(X,!0)});Q.push({type:"namespace",name:W.name,description:W.description,tools:K})}else{if(W.deferred)Z=!0;Q.push(t(W,!0))}if(Z)Q.push({type:"tool_search"});return Q}function t(J,$){let Q={type:"function",name:J.name,description:J.description,parameters:J.parameters,strict:J.strict};if($&&J.deferred)Q.defer_loading=!0;return Q}class r{static models(){return[]}normalizeError(J){return T(J)}}var E9=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class I$ extends r{model;capabilities;config;constructor(J,$={}){super();this.model=J,this.capabilities=j$(J),this.config=$}static model(J,$){return new I$(J,$)}static models(){return E9}stream(J){let $=q$(J,{model:this.model,capabilities:this.capabilities});return E$(this.endpoint(),$,{signal:J.signal,structuredOutput:Boolean(J.output),files:C$(J.messages)})}upload(J){return T$(this.endpoint(),J)}endpoint(){return R$(XJ(this.config))}get realtime(){return new GJ(XJ(this.config,{timeoutMs:k$}),{model:this.model})}}class w$ extends r{model;capabilities;config;constructor(J,$={}){super();this.model=J,this.capabilities=j$(J),this.config=$}static model(J,$){return new w$(J,$)}static models(){return E9}stream(J){let $=q$(J,{model:this.deployment(),capabilities:this.capabilities});return E$(this.endpoint(),$,{signal:J.signal,structuredOutput:Boolean(J.output),files:C$(J.messages)})}upload(J){return T$(this.endpoint(),J,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return R$(YJ(this.config))}get realtime(){return new GJ(J9(this.config,{timeoutMs:k$}),{model:this.deployment(),callFlow:"ephemeral"})}}class fJ{now;entries=new Map;constructor(J=Date.now){this.now=J}allow(J,$){let Q=this.entries.get(J);if(Q?.openUntil===void 0)return!0;let Z=this.now();if(Z<Q.openUntil)return!1;if(Q.probeUntil!==void 0&&Z<Q.probeUntil)return!1;return Q.probeUntil=Z+$.cooldownMs,!0}record(J,$,Q){let Z=this.entries.get(J)??{failures:0},W=Z.openUntil!==void 0;if($==="success")return this.entries.delete(J),W?"closed":void 0;if($==="none"){delete Z.probeUntil;return}if(Z.failures+=1,this.entries.set(J,Z),W||Z.failures>=Q.failures)return Z.openUntil=this.now()+Q.cooldownMs,delete Z.probeUntil,W?void 0:"open";return}state(J){let $=this.entries.get(J);if($?.openUntil===void 0)return"closed";return this.now()<$.openUntil?"open":"half-open"}}var T9=Symbol("timed-out");class VJ extends r{model;capabilities;entries;options;circuit;constructor(J,$={}){super();if(J.length===0)throw Error("FallbackProvider needs at least one provider.");for(let Z of J)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=[...J];let Q=$.circuit;if(Q){let Z=Q.failures??3,W=Q.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 K=new Set;for(let G of J){let V=b$(G);if(K.has(V))throw Error(`FallbackProvider: two legs share the circuit key "${V}". Give one of them a \`circuitKey\`.`);K.add(V)}let X=Q.store??new fJ;this.options={...$,circuit:{...Q,store:X}},this.circuit={policy:{failures:Z,cooldownMs:W},store:X,...Q.onStateChange?{onStateChange:Q.onStateChange}:{}}}else this.options=$,this.circuit=void 0;this.model=J[0].provider.model,this.capabilities=dZ(J.map((Z)=>Z.provider.capabilities))}static chain(J,$){return new VJ(J,$)}from(J){if(!Number.isInteger(J)||J<0||J>=this.entries.length)throw RangeError(`FallbackProvider.from(${J}): the chain has ${this.entries.length} entries.`);return new VJ(this.entries.slice(J),this.options)}leg(J){let $=this.from(J).entries[0];return new VJ([$],this.options)}upload(J){return this.entries[0].provider.upload(J)}normalizeError(J){return this.entries[0].provider.normalizeError(J)}stream(J){return this.run(J)}async*run(J){let $,Q=J.signal,Z=0;for(let W=0;W<this.entries.length;W++){let K=this.entries[W],X=W===this.entries.length-1,G=K.provider.model;if(this.circuit&&!X&&!await this.allow(K))continue;Z+=1;let V=!1,Y=async(_)=>{if(V)return;V=!0,await this.record(W,K,_)},H=new AbortController,D=()=>H.abort(Q?.reason);if(Q?.aborted)H.abort(Q.reason);else Q?.addEventListener("abort",D,{once:!0});let z=[],B=!1,U=!1,N,F,P,L=!1,O,j=!1,k=(_)=>{let R=$?A(A(S(),$),_.usage):_.usage;return $=void 0,{..._,usage:R}};try{O=K.provider.stream({...J,...K.reasoning!==void 0?{reasoning:K.reasoning}:{},signal:H.signal})[Symbol.asyncIterator]();let _=!0;for(;;){let R=_&&K.timeoutMs!==void 0?await iZ(O.next(),K.timeoutMs):await O.next();if(R===T9){L=!0,P={error:{code:"provider_error",message:`${G} sent nothing within ${K.timeoutMs}ms.`,retryable:!0}};break}if(_=!1,R.done){j=!0;break}let C=R.value;if(C.type==="finish"&&C.model)F=C.model;if(B){if(C.type==="finish")N=A(N??S(),C.usage),U=!0,yield k(C);else{if(C.type==="error")P={error:C.error};yield C}continue}if(xJ(C)){B=!0,await Y("success"),yield*z.splice(0),yield C;continue}if(C.type==="error")P={error:C.error,...C.status!==void 0?{status:C.status}:{},...C.requestId!==void 0?{requestId:C.requestId}:{}};else if(C.type==="finish"){if(N=A(N??S(),C.usage),C.reason==="error"&&!P)P={error:{code:"provider_error",message:`${G} ended the call with an error and did not say which.`,retryable:!1}}}z.push(C)}}catch(_){let R=K.provider.normalizeError(_);if(B){if(R.code!=="aborted")yield{type:"error",error:R,...s(_)};this.report({index:W,model:G,responseModel:F,attempt:Z,usage:N,outcome:f$(R),error:R}),yield k({type:"finish",reason:R.code==="aborted"?"aborted":"error",usage:S(),...F?{model:F}:{}});return}P={error:R,...s(_)}}finally{if(Q?.removeEventListener("abort",D),!j)H.abort(),O?.return?.()?.catch(()=>{})}if(B){if(!U&&$)yield{type:"finish",reason:P?"error":"stop",usage:$},$=void 0;this.report({index:W,model:G,responseModel:F,attempt:Z,usage:N,outcome:P?f$(P.error):"ok",...P?{error:P.error}:{}});return}if(Q?.aborted){await Y("none"),this.report({index:W,model:G,responseModel:F,attempt:Z,usage:N,outcome:"aborted"}),yield k({type:"finish",reason:"aborted",usage:N??S(),...F?{model:F}:{}});return}if(!P){await Y("success"),this.report({index:W,model:G,responseModel:F,attempt:Z,usage:N,outcome:"ok"});for(let _ of z)yield _.type==="finish"?k(_):_;return}let I=!X&&P.error.code!=="aborted"&&this.shouldFallBack(P.error,{index:W,model:G,timedOut:L,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}});if(await Y(I?"failure":"none"),this.report({index:W,model:G,responseModel:F,attempt:Z,usage:N,outcome:I?"fallback":f$(P.error),error:P.error}),I){if(N)$=A($??S(),N);continue}let x=!1,d;for(let _ of z){if(_.type==="finish"){d=_;continue}if(_.type==="error")x=!0;yield _}if(!x&&P.error.code!=="aborted")yield{type:"error",error:P.error,...P.status!==void 0?{status:P.status}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}};yield k({type:"finish",reason:P.error.code==="aborted"?"aborted":d?.reason??"error",usage:N??S(),...F?{model:F}:{}});return}}async allow(J){if(!this.circuit)return!0;try{return await this.circuit.store.allow(b$(J),this.circuit.policy)}catch{return!0}}async record(J,$,Q){if(!this.circuit)return;let Z=b$($),W;try{W=await this.circuit.store.record(Z,Q,this.circuit.policy)}catch{return}if(!W)return;try{this.circuit.onStateChange?.({index:J,model:$.provider.model,key:Z,state:W})}catch{}}shouldFallBack(J,$){let Q=this.options.fallbackOn??((Z)=>Z.retryable);try{return Q(J,$)}catch{return!1}}report(J){if(J.usage===void 0)delete J.usage;if(J.responseModel===void 0)delete J.responseModel;try{this.options.onUsage?.(J)}catch{}}}function b$(J){return J.circuitKey??J.provider.model}function f$(J){return J.code==="aborted"?"aborted":"failed"}function dZ(J){return{reasoning:J.every(($)=>$.reasoning),structuredOutput:J.every(($)=>$.structuredOutput),fileInput:J.every(($)=>$.fileInput),parallelToolCalls:J.every(($)=>$.parallelToolCalls),toolSearch:J.every(($)=>$.toolSearch)}}function iZ(J,$){let Q,Z=new Promise((W)=>{Q=setTimeout(()=>W(T9),$)});return Promise.race([J,Z]).finally(()=>clearTimeout(Q))}async function nZ(J,$,Q={}){let Z=Q.samples??1;if(!Number.isInteger(Z)||Z<1)throw RangeError(`evalChain: samples must be a positive integer, got ${Z}.`);let W=[];for(let K=0;K<J.entries.length;K++){let X=J.leg(K),G={index:K,model:X.model,results:[],errors:[]};for(let V=0;V<Z;V++)try{G.results.push(await $(X,{index:K,sample:V}))}catch(Y){G.errors.push({sample:V,error:Y})}W.push(G)}return W}class yJ extends Error{line;constructor(J){super(J??"Voice session ended by the app.");this.name="VoiceHangup",this.line=J}}var zJ="ask_agent",oZ={maxDurationMs:900000,idleTimeoutMs:120000,maxQueued:3,progressIntervalMs:4000,closingLineMs:1e4,tickMs:60000,hangupGraceMs:30000,toolTimeoutMs:60000,maxToolCallsPerMinute:20,toolOutputChars:8000},sZ={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 HJ(J={}){return[{name:J.name??zJ,description:J.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 vJ=new Map;class p{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(J){return new p(J)}static get(J){return vJ.get(J)}static async endAll(J){await Promise.all([...vJ.values()].map(($)=>$.end("hangup",J)))}constructor(J){this.params=J,this.sessionId=J.sessionId??crypto.randomUUID(),this.threadId=J.threadId,this.body=J.body??{},this.limits={...oZ,...j9(J.limits)},this.lines={...sZ,...j9(J.lines)},this.delegateName=J.delegate?.name??zJ;let $=new Set(HJ(J.delegate).map((Q)=>Q.name));for(let Q of J.tools??[]){if($.has(Q.tool.name)||this.toolHandlers.has(Q.tool.name))throw Error(`VoiceBridge: two tools are named "${Q.tool.name}".`);this.toolHandlers.set(Q.tool.name,Q)}if("realtime"in J.call){let{realtime:Q,callId:Z}=J.call;this.callId=Z,this.sideband=Q.sideband(Z),this.hangupCall=()=>this.sideband.hangup()}else this.callId=J.call.callId??J.call.sideband.callId,this.sideband=J.call.sideband,this.hangupCall=()=>this.sideband.hangup();this.ended=new Promise((Q)=>this.resolveEnded=Q),vJ.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(J){this.body=J;let $=this.params.contextNote?.(J);if($)this.sideband.addNote($)}end(J="hangup",$){return this.ending??=this.finish(J,$??null)}async listen(){for await(let J of this.sideband){try{this.params.onEvent?.(J)}catch{}this.closingWaiter?.(J),await this.handle(J)}}async handle(J){switch(J.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.usage;if($){this.usage=A(this.usage,$);let Q=this.info();this.hook(()=>this.params.onUsage?.($,Q))}return}case"conversation.item.input_audio_transcription.completed":{let $=J;if(this.say("user",String($.transcript??"")),$.transcriptionUsage||$.transcriptionSeconds!==void 0){this.transcription={usage:$.transcriptionUsage?A(this.transcription.usage,$.transcriptionUsage):this.transcription.usage,seconds:this.transcription.seconds+($.transcriptionSeconds??0)};let Q=this.info(),Z={...$.transcriptionUsage?{usage:$.transcriptionUsage}:{},...$.transcriptionSeconds!==void 0?{seconds:$.transcriptionSeconds}:{}};this.hook(()=>this.params.onTranscriptionUsage?.(Z,Q))}return}case"response.output_audio_transcript.done":this.say("assistant",String(J.transcript??""));return;case"response.output_text.done":this.say("assistant",String(J.text??""));return;case"response.function_call_arguments.done":{let $=J;if(this.touch(),!this.ending)this.call($.call_id,$.name,$.arguments);return}case"session.updated":if(this.tampered(J.session))this.end("session_tampered",null);return;case"error":{let $=J.error;if(this.errors.push({code:$?.code,message:String($?.message??"")}),this.pendingCreate&&$?.event_id===this.pendingCreate)if(this.pendingCreate=void 0,$.code==="conversation_already_has_active_response")this.responseActive=!0,this.responseWanted=!0;else this.responseActive=!1;return}case"sideband.closed":{let $=J;if(!this.ending&&!$.byClient)this.end($.code===1000?"call_ended":"sideband_lost",null);return}}}say(J,$){if($.trim())this.transcript.push({role:J,text:$,at:Date.now()})}call(J,$,Q){let Z=aZ(Q);if($===this.delegateName){let K=typeof Z.request==="string"?Z.request.trim():"";if(!K)return this.answer(J,{status:"error",message:"The request was empty."});return this.enqueue({record:{request:K,status:"queued"},turn:{text:K},callId:J})}let W=this.toolHandlers.get($);if(W)return void this.runTool(J,W,Z);switch($){case"stop_work":{let K=this.running;if(K)K.stopRequested=!0,K.handle?.stop({reason:"Stopped by voice."});let X=this.dropQueue();return this.answer(J,{stopped:Boolean(K),dropped:X})}case"work_status":return this.answer(J,{running:this.running?{request:this.running.record.request,step:this.lastProgress??"starting"}:null,queued:this.queue.map((K)=>K.record.request),...this.pending.length?{needsInput:this.questions()}:{}});case"answer_question":{if(!this.pending.length)return this.answer(J,{status:"error",message:"There is no open question."});let K=typeof Z.answer==="string"?Z.answer:"",X=typeof Z.approve==="boolean"?Z.approve:void 0,G=this.pending.map((V)=>tZ(V,K,X));return this.pending=[],this.enqueue({record:{request:`(answer) ${K}`,status:"queued"},turn:{toolResults:G},callId:J})}default:return this.answer(J,{status:"error",message:`There is no tool called ${$}.`})}}enqueue(J){if(!this.running){this.requests.push(J.record),this.run(J);return}if(this.queue.length>=this.limits.maxQueued)return this.answer(J.callId,{status:"busy",message:"Too many requests are waiting. Ask the user to wait for the current one."});this.requests.push(J.record),this.queue.push(J),this.answer(J.callId,{status:"queued",position:this.queue.length,message:"It will start when the current request is done."}),J.callId=void 0}async run(J){this.running=J,J.record.status="running",this.lastProgress=void 0,this.pauseIdle();try{let $=new Set;await this.waitForThread($);let Q=await this.latestBody();while(!J.stopRequested&&await this.waitForThread($));if(J.stopRequested||this.ending){J.record.status="dropped",this.complete(J,{status:"stopped"});return}let Z;try{Z=await this.params.controller.startTurn({threadId:this.threadId,user:this.params.user,body:Q,turn:J.turn})}catch(K){J.record.status="refused",this.complete(J,{status:"refused",message:K instanceof Error?K.message:"The request could not be started."});return}J.handle=Z,J.record.runId=Z.runId,this.follow(Z);let W=await Z.result();if(J.record.status="done",J.record.finishReason=W.finishReason,W.finishReason==="awaiting-input"&&W.pending.length)this.pending=W.pending,this.complete(J,{status:"needs_input",text:W.text,questions:this.questions()});else if(W.finishReason==="error")this.complete(J,{status:"failed",message:W.error?.message??"The work failed."});else if(W.finishReason==="aborted")this.complete(J,{status:"stopped",text:W.text});else this.complete(J,{status:"done",text:W.text})}catch($){J.record.status="done",this.complete(J,{status:"failed",message:$ instanceof Error?$.message:"The work failed."})}finally{this.running=void 0,this.flushNote();let $=this.queue.shift();if($&&!this.ending)this.run($);else this.touch()}}async runTool(J,$,Q){let Z=$.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(J,{status:"busy",message:"Too many tool calls in the last minute. Tell the user to wait a moment."});return}this.toolCallTimes.push(W);let K={name:Z,status:"running"};this.toolCalls.push(K),this.toolsRunning+=1,this.pauseIdle();let X=new AbortController,G=$.timeoutMs??this.limits.toolTimeoutMs,V,Y;try{let D=await Promise.race([$.run(Q,{sessionId:this.sessionId,signal:X.signal}),new Promise((z,B)=>{V=setTimeout(()=>{B(new g(`"${Z}" took longer than ${Math.round(G/1000)} s.`)),X.abort()},G)})]);K.status="done",Y={status:"done",output:this.clip(D)}}catch(D){if(D instanceof yJ){K.status="refused",K.message=D.message,this.end("usage",D.line??null);return}let z=D instanceof g?D.message:"The tool failed.";if(!(D instanceof g))console.error(`[gemi/ai] the voice tool "${Z}" threw.`,D);K.status="failed",K.message=z,Y={status:"failed",message:z}}finally{clearTimeout(V),K.durationMs=Date.now()-W,this.toolsRunning-=1,this.touch()}let H=this.info();if(this.hook(()=>this.params.onToolCall?.({...K},H)),!this.ending)this.answer(J,Y)}clip(J){let $;try{$=JSON.stringify(J)}catch{return String(J)}if($===void 0||$.length<=this.limits.toolOutputChars)return J;return`${$.slice(0,this.limits.toolOutputChars)}\u2026 (cut: ${$.length} characters in all)`}async waitForThread(J=new Set){let $=this.params.liveRuns;if(!$)return!1;let Q=await $.find({threadId:this.threadId}),Z=Q&&!J.has(Q.runId)?$.get(Q.runId):null;if(!Q||!Z)return!1;return J.add(Q.runId),await Z.result().catch(()=>{return}),!0}async latestBody(){let J=this.params.store;if(!J)return this.body;let $=await J.get(this.sessionId).catch(()=>null);if($)this.body=$.body;return this.body}async follow(J){let $=this.params.progress??rZ();try{for await(let Q of J.run){let Z=$(Q);if(Z)this.note(Z)}}catch{}}complete(J,$){if(this.ending)return;if(J.callId)this.sideband.functionOutput(J.callId,$),J.callId=void 0;else this.sideband.addNote(`Update on the earlier request "${J.record.request}": ${JSON.stringify($)}`);this.respond()}answer(J,$){this.sideband.functionOutput(J,$),this.respond()}respond(){if(this.ending)return;if(this.responseActive){this.responseWanted=!0;return}this.responseActive=!0,this.createResponse()}createResponse(){let J=`gemi_voice_${crypto.randomUUID()}`;this.pendingCreate=J,this.sideband.send({type:"response.create",event_id:J})}questions(){return this.pending.map((J)=>({kind:J.kind,tool:String(J.name),input:J.input}))}dropQueue(){let J=this.queue.splice(0);for(let $ of J)$.record.status="dropped";return J.length}note(J){if(J===this.lastProgress)return;this.lastProgress=J;let $=this.lastNoteAt+this.limits.progressIntervalMs-Date.now();if($<=0)return this.flushNote();this.noteTimer??=setTimeout(()=>this.flushNote(),$)}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 J=this.info();this.hook(()=>this.params.onTick?.(J))}hook(J){this.hooks=this.hooks.then(async()=>{try{await J()}catch($){if($ instanceof yJ)this.end("usage",$.line??null);else console.error("[gemi/ai] a voice hook threw; ending the call.",$),this.end("error",this.lines.error)}})}tampered(J){let $=this.params.session;if(!$||!J)return!1;if($.instructions!==void 0&&J.instructions!==void 0&&J.instructions!==$.instructions)return!0;if(Array.isArray(J.tools)){let Q=new Set([...HJ(this.params.delegate),...$.tools??[]].map((W)=>W.name)),Z=new Set(J.tools.map((W)=>String(W?.name)));if(Q.size!==Z.size||[...Q].some((W)=>!Z.has(W)))return!0}return!1}async finish(J,$){for(let X of this.timers)clearTimeout(X);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.noteTimer)clearTimeout(this.noteTimer);if(this.tickTimer)clearInterval(this.tickTimer);if(this.dropQueue(),$&&(J!=="call_ended"&&J!=="sideband_lost"))await this.closingLine($);if(J!=="call_ended")await this.hangUp();else this.sideband.close();await this.hooks;let Z=Date.now(),W=Z-this.startedAt,K={sessionId:this.sessionId,...this.callId?{callId:this.callId}:{},threadId:this.threadId,reason:J,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};vJ.delete(this.sessionId),await this.params.store?.update(this.sessionId,{endedAt:Z,endReason:J}).catch(()=>{return});try{await this.params.onEnd?.(K)}catch(X){console.error("[gemi/ai] a voice session's onEnd threw.",X)}return this.resolveEnded(K),K}async hangUp(){try{await this.hangupCall()}catch(J){console.error("[gemi/ai] a voice call could not be hung up; waiting for the vendor.",J),this.errors.push({code:"hangup_failed",message:J instanceof Error?J.message:String(J)});let $;await Promise.race([this.sideband.closed,new Promise((Q)=>$=setTimeout(Q,this.limits.hangupGraceMs))]),clearTimeout($),this.sideband.close()}}async closingLine(J){await new Promise(($)=>{let Q=`gemi_voice_closing_${crypto.randomUUID()}`,Z=`gemi_voice_cancel_${crypto.randomUUID()}`,W=this.responseActive?"cancelling":"asked",K,X=setTimeout(G,this.limits.closingLineMs);function G(){clearTimeout(X),$()}let V=()=>{W="asked",this.sideband.send({type:"response.create",event_id:Q,response:{instructions:`Say exactly this to the user, and nothing else: "${J}"`,tool_choice:"none"}})};if(this.closingWaiter=(Y)=>{let H=Y;if(H.type==="sideband.closed")return G();if(W==="cancelling"){if(H.type==="response.done"||H.type==="error"&&H.error?.event_id===Z)V();return}if(H.type==="error"&&H.error?.event_id===Q)return G();if(H.type==="response.created"&&!K){K=H.response?.id;return}let D=(z)=>!K||!z||z===K;if(H.type==="response.done"&&D(H.response?.id))W="playing";else if(H.type==="output_audio_buffer.stopped"&&W==="playing"&&D(H.response_id))G()},W==="cancelling")this.sideband.send({type:"response.cancel",event_id:Z});else V()}),this.closingWaiter=void 0}}function j9(J){if(!J)return{};return Object.fromEntries(Object.entries(J).filter(([,$])=>$!==void 0))}function aZ(J){try{let $=JSON.parse(J);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function tZ(J,$,Q){let Z={toolCallId:J.toolCallId,signature:J.signature,...J.path?{path:J.path}:{}};if(J.kind==="question")return{...Z,output:$};if(J.kind==="approval")return{...Z,approve:Q===!0,...$?{reason:$}:{}};return{...Z,approve:!1,reason:"Not available in a voice call."}}function rZ(){let J=new Set;return($)=>{if($.type==="tool-call"){if($.part.partial||$.resent||J.has($.part.toolCallId))return;return J.add($.part.toolCallId),`running ${String($.part.name)}`}if($.type==="tool-progress"){let Q=$.data;if(typeof Q==="string")return Q;if(Q&&typeof Q==="object")for(let Z of["message","label","title"]){let W=Q[Z];if(typeof W==="string"&&W)return W}}return}}var k9="http://gemi.internal/__gemi__/voice/mcp";async function v$(J,$){if(!$.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}=J,Z=J.scopes??Q.scopes().map((X)=>X.name),W=(X)=>({kind:"remote",req:X,principal:{user:$.user,via:"voice",id:`voice:${$.sessionId}`,scopes:Z}});return(await Q.available(W(x9()),J.filter)).filter((X)=>!X.requiresApproval).map((X)=>({tool:{name:X.name,description:X.description,parameters:X.inputSchema},...J.timeoutMs!==void 0?{timeoutMs:J.timeoutMs}:{},run:(G,V)=>{let Y=x9();return h.run(Y,async()=>{return await J.authorize?.({name:X.name,input:G,sessionId:V.sessionId}),Q.execute(W(Y),X.name,G,void 0,{signal:V.signal})},{user:$.user})}}))}function x9(){return new q(new Request(k9,{method:"POST"}),{},"api",new URL(k9).pathname)}class y${records=new Map;retainEndedMs;constructor(J={}){this.retainEndedMs=J.retainEndedMs??600000}async create(J){this.sweep(),this.records.set(J.id,structuredClone(J))}async get(J){let $=this.records.get(J);return $?structuredClone($):null}async update(J,$){let Q=this.records.get(J);if(!Q)return;this.records.set(J,{...Q,...structuredClone($),id:J})}sweep(){let J=Date.now()-this.retainEndedMs;for(let[$,Q]of this.records)if(Q.endedAt!==void 0&&Q.endedAt<J)this.records.delete($)}}var h$=new y$;var q9=new WeakMap,I9=100;class h9{threadsTable;messagesTable;sql;dialect;connection;constructor(J,$={}){this.threadsTable=w9($.threadsTable??"gemi_agent_threads","threads"),this.messagesTable=w9($.messagesTable??"gemi_agent_messages","messages"),this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){let J=$0(this.dialect,this.threadsTable,this.messagesTable);for(let $ of J)await this.sql.unsafe($)}async createThread(J){let $=this.q(),Q=crypto.randomUUID(),Z=J.userId===void 0||J.userId===null?null:String(J.userId),W=this.clock($);return await $`
|
|
147
147
|
INSERT INTO ${this.threads($)} (id, user_id, created_at, updated_at)
|
|
148
148
|
VALUES (${Q}, ${Z}, ${W}, ${W})
|
|
149
149
|
`,{threadId:Q}}async loadThread(J){let $=this.q();if((await $`SELECT id FROM ${this.threads($)} WHERE id = ${J}`).length===0)return null;return(await $`
|
|
150
150
|
SELECT message FROM ${this.messages($)}
|
|
151
151
|
WHERE thread_id = ${J}
|
|
152
152
|
ORDER BY position
|
|
153
|
-
`).map((W)=>JSON.parse(String(W.message)))}async appendMessages(J,$){if($.length===0){if(await this.getThread(J)===null)throw
|
|
153
|
+
`).map((W)=>JSON.parse(String(W.message)))}async appendMessages(J,$){if($.length===0){if(await this.getThread(J)===null)throw b9(J);return}await this.atomically(async(Q)=>{await Q`UPDATE ${this.threads(Q)} SET updated_at = ${this.clock(Q)} WHERE id = ${J}`;let Z=await Q`
|
|
154
154
|
SELECT title FROM ${this.threads(Q)} WHERE id = ${J}
|
|
155
|
-
`;if(Z.length===0)throw
|
|
155
|
+
`;if(Z.length===0)throw b9(J);let W=[...new Set($.map((Y)=>Y.id))],K=await Q`
|
|
156
156
|
SELECT id FROM ${this.messages(Q)}
|
|
157
|
-
WHERE thread_id = ${J} AND id IN (${
|
|
157
|
+
WHERE thread_id = ${J} AND id IN (${f9(Q,W)})
|
|
158
158
|
`,X=new Set(K.map((Y)=>String(Y.id))),[G]=await Q`
|
|
159
159
|
SELECT MAX(position) AS position FROM ${this.messages(Q)} WHERE thread_id = ${J}
|
|
160
160
|
`,V=G?.position===null||G?.position===void 0?0:Number(G.position)+1;for(let Y of $){let H=JSON.stringify(Y);if(X.has(Y.id))await Q`
|
|
@@ -163,35 +163,35 @@ import{$b as e$,$c as d0,Ac as n9,Bc as o9,Cc as N8,Ec as U8,Fc as S8,Gc as C8,H
|
|
|
163
163
|
`;else await Q`
|
|
164
164
|
INSERT INTO ${this.messages(Q)} (thread_id, id, position, message, created_at)
|
|
165
165
|
VALUES (${J}, ${Y.id}, ${V}, ${H}, ${this.clock(Q)})
|
|
166
|
-
`,X.add(Y.id),V+=1}if(Z[0].title===null||Z[0].title===void 0){let Y=
|
|
166
|
+
`,X.add(Y.id),V+=1}if(Z[0].title===null||Z[0].title===void 0){let Y=eZ($);if(Y!==null)await Q`
|
|
167
167
|
UPDATE ${this.threads(Q)} SET title = ${Y}
|
|
168
168
|
WHERE id = ${J} AND title IS NULL
|
|
169
169
|
`}})}async removeMessages(J,$){if($.length===0)return;let Q=this.q();await Q`
|
|
170
170
|
DELETE FROM ${this.messages(Q)}
|
|
171
|
-
WHERE thread_id = ${J} AND id IN (${
|
|
171
|
+
WHERE thread_id = ${J} AND id IN (${f9(Q,[...new Set($)])})
|
|
172
172
|
`}async loadSummaries(J){let $=this.q(),[Q]=await $`
|
|
173
173
|
SELECT summaries FROM ${this.threads($)} WHERE id = ${J}
|
|
174
|
-
`;return Q?
|
|
174
|
+
`;return Q?v9(Q.summaries):[]}async saveSummary(J,$){await this.atomically(async(Q)=>{await Q`UPDATE ${this.threads(Q)} SET updated_at = updated_at WHERE id = ${J}`;let[Z]=await Q`
|
|
175
175
|
SELECT summaries FROM ${this.threads(Q)} WHERE id = ${J}
|
|
176
|
-
`;if(!Z)return;let W=DJ(
|
|
176
|
+
`;if(!Z)return;let W=DJ(v9(Z.summaries),$);await Q`
|
|
177
177
|
UPDATE ${this.threads(Q)} SET summaries = ${JSON.stringify(W)}
|
|
178
178
|
WHERE id = ${J}
|
|
179
179
|
`})}async lockSummary(J,$,Q){let Z=this.q(),W=`${$}:${crypto.randomUUID()}`,K=this.clock(Z),X=await Z`
|
|
180
180
|
UPDATE ${this.threads(Z)}
|
|
181
181
|
SET summary_lock = ${W}, summary_lock_until = ${K} + ${this.ms(Z,Q)}
|
|
182
182
|
WHERE id = ${J} AND (summary_lock_until IS NULL OR summary_lock_until <= ${K})
|
|
183
|
-
`;if(
|
|
183
|
+
`;if(J0(X)===0)return null;return async()=>{let G=this.q();await G`
|
|
184
184
|
UPDATE ${this.threads(G)} SET summary_lock = NULL, summary_lock_until = NULL
|
|
185
185
|
WHERE id = ${J} AND summary_lock = ${W}
|
|
186
186
|
`}}async getThread(J){let $=this.q(),[Q]=await $`
|
|
187
187
|
SELECT id, user_id, title, created_at, updated_at FROM ${this.threads($)}
|
|
188
188
|
WHERE id = ${J}
|
|
189
|
-
`;return Q?
|
|
189
|
+
`;return Q?y9(Q):null}async listThreads(J={}){let $=this.q(),Q=Math.max(0,Math.floor(J.limit??50)),Z=Math.max(0,Math.floor(J.offset??0)),W=J.userId===void 0?$`1 = 1`:J.userId===null?$`user_id IS NULL`:$`user_id = ${String(J.userId)}`;return(await $`
|
|
190
190
|
SELECT id, user_id, title, created_at, updated_at FROM ${this.threads($)}
|
|
191
191
|
WHERE ${W}
|
|
192
192
|
ORDER BY updated_at DESC, id DESC
|
|
193
193
|
LIMIT ${Q} OFFSET ${Z}
|
|
194
|
-
`).map(
|
|
194
|
+
`).map(y9)}async deleteThread(J){await this.atomically(async($)=>{await $`DELETE FROM ${this.messages($)} WHERE thread_id = ${J}`,await $`DELETE FROM ${this.threads($)} WHERE id = ${J}`})}atomically(J){if(this.joinable())return SJ(this.sql,(W)=>J(W),{connection:this.connection});let $=()=>this.sql.begin((W)=>J(W));if(this.dialect!=="sqlite")return $();let Z=(q9.get(this.sql)??Promise.resolve()).then($,$);return q9.set(this.sql,Z.then(()=>{},()=>{})),Z}joinable(){if(this.connection===void 0)return;let J=n();if(J===void 0||o()!==this.connection)return;return J}q(){return this.joinable()??this.sql}quote(J){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${J}\``:`"${J}"`}threads(J){return J.unsafe(this.quote(this.threadsTable))}messages(J){return J.unsafe(this.quote(this.messagesTable))}clock(J){switch(this.dialect){case"postgres":return J`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return J`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return J`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(J,$){let Q=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?J`CAST(${Q} AS SIGNED)`:J`CAST(${Q} AS BIGINT)`}}function w9(J,$){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The agent ${$} table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);return J}function b9(J){return Error(`Thread ${J} does not exist here, or has been deleted.`)}function f9(J,$){return $.map((Q)=>J`${Q}`).reduce((Q,Z)=>J`${Q}, ${Z}`)}function eZ(J){for(let $ of J){if($.role!=="user")continue;let Q=$.content.map((Z)=>Z.type==="text"?Z.text:"").join(" ").replace(/\s+/g," ").trim();if(Q)return Q.length>I9?`${Q.slice(0,I9-1)}\u2026`:Q}return null}function v9(J){if(J===null||J===void 0||J==="")return[];let $=JSON.parse(String(J));return Array.isArray($)?$:[]}function y9(J){return{id:String(J.id),userId:J.user_id===null||J.user_id===void 0?null:String(J.user_id),title:J.title===null||J.title===void 0?null:String(J.title),createdAt:Number(J.created_at),updatedAt:Number(J.updated_at)}}function J0(J){let $=J;return Math.max(Number($.count??0),Number($.affectedRows??0))}function $0(J,$,Q){if(J==="mysql"||J==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
195
195
|
\`id\` VARCHAR(191) NOT NULL,
|
|
196
196
|
\`user_id\` VARCHAR(191) NULL,
|
|
197
197
|
\`title\` TEXT NULL,
|
|
@@ -231,14 +231,14 @@ import{$b as e$,$c as d0,Ac as n9,Bc as o9,Cc as N8,Ec as U8,Fc as S8,Gc as C8,H
|
|
|
231
231
|
"created_at" BIGINT NOT NULL,
|
|
232
232
|
|
|
233
233
|
CONSTRAINT "${Q}_pkey" PRIMARY KEY ("thread_id", "id")
|
|
234
|
-
)`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}class e extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,$,Q){super(`Frame ${$} of run ${J} has been evicted; the oldest frame still buffered is ${Q}. Reload the thread instead of resuming.`);this.runId=J;this.requested=$;this.oldest=Q}}class
|
|
234
|
+
)`,`CREATE UNIQUE INDEX IF NOT EXISTS "${Q}_thread_id_position_key" ON "${Q}"("thread_id", "position")`]}class e extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(J,$,Q){super(`Frame ${$} of run ${J} has been evicted; the oldest frame still buffered is ${Q}. Reload the thread instead of resuming.`);this.runId=J;this.requested=$;this.oldest=Q}}class BJ extends Error{runId;code="live_run_not_found";constructor(J){super(`No live run ${J} in this process.`);this.runId=J}}class hJ{ttlMs;maxFrames;maxAgeMs;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(J={}){this.ttlMs=J.ttlMs??60000,this.maxFrames=J.maxFrames??4096,this.maxAgeMs=J.maxAgeMs===void 0?3600000:J.maxAgeMs}register(J,$={}){let Q={run:J,threadId:$.threadId,owner:$.owner??null,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evicted:!1,evictAt:null,expireAt:null,wake:new Set,version:0};if(this.runs.set(J.runId,Q),$.threadId)this.byThread.set($.threadId,J.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,J.runId);return this.scheduleExpiry(Q,$.maxRunDurationMs),this.pump(Q,$)}findByClientRunId(J){let $=this.byClientRun.get(J);return $&&this.runs.has($)?$:null}async find(J){let $=this.byThread.get(J.threadId);if(!$)return null;let Q=this.runs.get($);if(!Q)return null;return{runId:$,seq:Q.lastSeq}}get(J){return this.runs.get(J)?.run??null}ownerOf(J){return this.runs.get(J)?.owner??null}mayAccess(J,$){let Q=this.ownerOf(J);return Q===null||Q===$}isRunning(J){let $=this.runs.get(J);return!!$&&!$.ended&&!$.evicted}replay(J,$){let Q=this.runs.get(J);if(!Q)throw new BJ(J);if($!==void 0&&$<Q.lostBefore)throw new e(J,$,Q.lostBefore);let Z=Q.frames[0]?.seq;return this.drain(Q,J,$??Z??Q.lastSeq+1)}clear(){for(let J of this.runs.values()){if(J.evictAt)clearTimeout(J.evictAt);if(J.expireAt)clearTimeout(J.expireAt);J.ended=!0,this.notify(J)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(J,$){let Q=Promise.resolve();try{for await(let Z of J.run.frames()){if(J.evicted){let K=$.onEvent;if(K)Q=Q.then(()=>K(Z.event)).catch((X)=>g$($,X));continue}if(J.frames.push(Z),J.lastSeq=Z.seq,J.frames.length>this.maxFrames){let K=J.frames.shift();if(K)J.lostBefore=K.seq+1}this.notify(J);let W=$.onEvent;if(W)Q=Q.then(()=>W(Z.event)).catch((K)=>g$($,K))}}catch(Z){g$($,Z)}finally{if(J.ended=!0,J.expireAt)clearTimeout(J.expireAt),J.expireAt=null;this.notify(J),this.scheduleEviction(J),await Q}}async*drain(J,$,Q){let Z=Q;while(!0){let W=J.version;for(;;){if(Z<J.lostBefore)throw new e($,Z,J.lostBefore);let K=J.frames,X=K[0]?.seq;if(X===void 0)break;let G=Math.max(0,Z-X);if(G>=K.length)break;let V=K[G];yield V,Z=V.seq+1}if(J.ended&&Z>J.lastSeq||J.evicted)return;await this.wait(J,W)}}wait(J,$){if(J.version!==$)return Promise.resolve();return new Promise((Q)=>J.wake.add(Q))}notify(J){J.version++;let $=Array.from(J.wake);J.wake.clear();for(let Q of $)Q()}scheduleEviction(J){if(J.evictAt)return;let $=setTimeout(()=>{let Q=J.run.runId;if(!J.ended)J.evicted=!0,J.frames=[];if(this.runs.get(Q)===J)this.runs.delete(Q);if(J.threadId&&this.byThread.get(J.threadId)===Q)this.byThread.delete(J.threadId);if(J.clientRunId&&this.byClientRun.get(J.clientRunId)===Q)this.byClientRun.delete(J.clientRunId);this.notify(J)},this.ttlMs);$.unref?.(),J.evictAt=$}scheduleExpiry(J,$){if(this.maxAgeMs===null||$===null)return;let Q=$===void 0?this.maxAgeMs:Math.max(this.maxAgeMs,$+this.ttlMs);if(!Number.isFinite(Q)||Q>2147483647)return;let Z=setTimeout(()=>{if(J.expireAt=null,J.ended)return;try{J.run.stop({reason:`The run was still going ${Math.round(Q/1000)}s after it started, past the live-run registry's age limit.`})}catch{}this.scheduleEviction(J)},Q);Z.unref?.(),J.expireAt=Z}}var u$=new hJ;function g$(J,$){try{J.onInternalError?.($)}catch{}}class gJ{maxEntries;records=new Map;constructor(J=1e5){this.maxEntries=J}async record(J,$){if(this.records.has(J))return;this.records.set(J,{...$});while(this.records.size>this.maxEntries){let Q=this.records.keys().next().value;if(Q===void 0)break;this.records.delete(Q)}}async get(J){let $=this.records.get(J);return $?{...$}:null}}var c$=new gJ;class l${now;receipts=new Map;sweepAt=1024;constructor(J=Date.now){this.now=J}async claim(J,$){let Q=this.now();if(this.receipts.size>=this.sweepAt)this.sweep(Q);let Z=this.receipts.get(J);if(Z&&Z.expiresAt>Q)return Z.result?{status:"replay",result:structuredClone(Z.result)}:{status:"blocked"};return this.receipts.set(J,{expiresAt:$}),{status:"claimed"}}async complete(J,$,Q){this.receipts.set(J,{result:structuredClone($),expiresAt:Q})}async release(J){let $=this.receipts.get(J);if($&&!$.result)this.receipts.delete(J)}get size(){return this.receipts.size}sweep(J){for(let[$,Q]of this.receipts)if(Q.expiresAt<=J)this.receipts.delete($);this.sweepAt=Math.max(1024,this.receipts.size*2)}}var g9="pending",m$="done:",Q0=`
|
|
235
235
|
if redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end
|
|
236
236
|
local held = redis.call('GET', KEYS[1])
|
|
237
237
|
if not held then return ARGV[1] end
|
|
238
|
-
return held`,
|
|
238
|
+
return held`,Z0=`
|
|
239
239
|
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
240
|
-
return 0`;class p${injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,$){let Q=await this.client.send("EVAL",[nZ,"1",this.key(J),f9,v9($)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(u$))return{status:"replay",result:JSON.parse(Z.slice(u$.length))};return{status:"blocked"}}async complete(J,$,Q){await this.client.send("SET",[this.key(J),u$+JSON.stringify($),"PX",v9(Q)])}async release(J){await this.client.send("EVAL",[oZ,"1",this.key(J),f9])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=y9(),$=J.bound(c$)?J.make(c$).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function v9(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var sZ=86400000,aZ=60000;class hJ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??sZ,this.clientOwnedIds=J.clientOwnedIds??!1}async createThread(J){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(J){this.sweep();let $=this.threads.get(J);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(J,$){this.sweep();let Q=this.threads.get(J);if(!Q){if(!this.clientOwnedIds)throw Error(`Thread ${J} does not exist here, or has expired.`);Q={messages:[],touchedAt:Date.now()},this.threads.set(J,Q)}for(let Z of $){let W=Q.messages.findIndex((K)=>K.id===Z.id);if(W===-1)Q.messages.push(Z);else Q.messages[W]=Z}Q.touchedAt=Date.now()}async removeMessages(J,$){this.sweep();let Q=this.threads.get(J);if(!Q)return;let Z=new Set($);Q.messages=Q.messages.filter((W)=>!Z.has(W.id)),Q.touchedAt=Date.now()}async loadSummaries(J){return this.threads.get(J)?.summaries?.slice()??[]}async saveSummary(J,$){let Q=this.threads.get(J);if(!Q)return;Q.summaries=DJ(Q.summaries??[],$)}delete(J){this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<aZ)return;this.lastSweep=J;for(let[$,Q]of this.threads)if(J-Q.touchedAt>this.ttlMs)this.threads.delete($)}}var l$=new hJ;function c9(J={}){return{messages:J.messages?[...J.messages]:[],pending:J.pending?[...J.pending]:[],error:null,threadId:J.threadId,seq:J.seq??-1,cursorRunId:J.cursorRunId,runMessageIds:[],loadedTools:[]}}function m9(J,$,Q=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==J.cursorRunId)&&$.seq<=J.seq)return J;return{...p9(J,$.event,Q),seq:$.seq}}function p9(J,$,Q){switch($.type){case"run-start":return{...J,messages:tZ(J.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return l(J,$.messageId,Q,(Z)=>({...Z,role:$.role}));case"text-delta":if(g9(J,$.messageId))return J;return l(J,$.messageId,Q,(Z)=>({...Z,content:Q0(Z.content,$.delta)}));case"reasoning-delta":if(g9(J,$.messageId))return J;return l(J,$.messageId,Q,(Z)=>({...Z,content:Z0(Z.content,$.delta,$.id)}));case"output-delta":return l(J,$.messageId,Q,(Z)=>({...Z,content:u9(Z.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return l(J,$.messageId,Q,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===$.part.toolCallId),K=W===-1?void 0:Z.content[W],X=$.part.progress??K?.progress,G=$.part.nested??K?.nested,V=$.part.attachments??K?.attachments,Y={...$.part,...X?{progress:X}:{},...G?{nested:G}:{},...V?{attachments:V}:{}},H=Z.content.slice();if(W===-1)H.push(Y);else H[W]=Y;return{...Z,content:H}});case"tool-search":{let Z=$.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return h9(J,$.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],$.data]}));case"nested-event":{let Z=$;return h9(J,$.toolCallId,(W)=>{let K=W.nested??[],X=K.findIndex((H)=>H.runId===Z.runId),G=K[X]??{runId:Z.runId,agent:Z.agent,messages:[]},V=J0(G,Z,Q),Y=X===-1?[...K,V]:K.map((H,D)=>D===X?V:H);return{...W,nested:Y}})}case"tool-result":{let Z=l(J,$.messageId,Q,(W)=>({...W,content:u9(W.content,$.part,(K)=>K.type==="tool-result"&&K.toolCallId===$.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((X)=>X.id===$.message.id),W=J.messages.slice();if(Z===-1)W.push($.message);else W[Z]=$.message;let K=J.runMessageIds.includes($.message.id)?J.runMessageIds:[...J.runMessageIds,$.message.id];return{...J,messages:W,runMessageIds:K}}case"message-id":{let Z=J.messages.findIndex((G)=>G.id===$.localId);if(Z===-1){if(!$.message||J.messages.some((G)=>G.id===$.messageId))return J;return{...J,messages:[...J.messages,$.message]}}let W=J.messages[Z],K={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},X=J.messages.some((G)=>G.id===$.messageId)?J.messages.filter((G,V)=>V!==Z).map((G)=>G.id===$.messageId?{...G,...K}:G):J.messages.map((G,V)=>V===Z?{...G,...K,id:$.messageId}:G);return{...J,messages:X}}case"awaiting-input":return{...J,runId:$.runId,pending:[...$.pending]};case"message-end":return l(J,$.messageId,Q,(Z)=>({...Z,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.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{...J,usage:$.usage};case"error":return{...J,error:$.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:$.finishReason,messages:l9(J,$.finishReason)};default:return J}}function tZ(J,$){if(!J.some((Q)=>Q.runId===$&&Q.finishReason===void 0))return J;return J.map((Q)=>{if(Q.runId!==$||Q.finishReason!==void 0)return Q;let{runId:Z,...W}=Q;return{...W,content:[]}})}function l9(J,$){return J.messages.map((Q)=>Q.role==="assistant"&&J.runMessageIds.includes(Q.id)?rZ(Q,$):Q)}function rZ(J,$){let Q=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((K)=>K.finishReason===void 0)?{...W,nested:W.nested.map((K)=>K.finishReason===void 0?eZ(K,$):K)}:W);if(J.finishReason===void 0)return{...J,finishReason:$,content:Q};return Q.some((W,K)=>W!==J.content[K])?{...J,content:Q}:J}function eZ(J,$){let Q={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:$,messages:l9(Q,$)}}function h9(J,$,Q){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],K=W.content.findIndex((Y)=>Y.type==="tool-call"&&Y.toolCallId===$);if(K===-1)continue;if(W.finishReason!==void 0&&!$0(J,W,$))return J;let X=W.content.slice();X[K]=Q(X[K]);let G=J.messages.slice();G[Z]={...W,content:X};let V=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:V,messages:G}}return J}function J0(J,$,Q){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((K)=>K.id),loadedTools:[],finishReason:J.finishReason},W=p9(Z,$.event,Q);return{...J,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function $0(J,$,Q){if($.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Q))}function g9(J,$){let Q=J.messages.find((Z)=>Z.id===$);return Q!==void 0&&Q.finishReason!==void 0}function l(J,$,Q,Z){let W=J.messages.findIndex((G)=>G.id===$),K=J.runMessageIds.includes($)?J.runMessageIds:[...J.runMessageIds,$];if(W===-1){let G={id:$,role:"assistant",content:[],createdAt:Q};return{...J,runMessageIds:K,messages:[...J.messages,Z(G)]}}let X=J.messages.slice();return X[W]=Z(X[W]),{...J,runMessageIds:K,messages:X}}function Q0(J,$){let Q=J[J.length-1];if(Q&&Q.type==="text")return[...J.slice(0,-1),{type:"text",text:Q.text+$}];return[...J,{type:"text",text:$}]}function Z0(J,$,Q){let Z=J[J.length-1];if(Z&&Z.type==="reasoning"&&Z.id===Q)return[...J.slice(0,-1),{...Z,text:(Z.text??"")+$}];return[...J,Q?{type:"reasoning",id:Q,text:$}:{type:"reasoning",text:$}]}function u9(J,$,Q){let Z=J.findIndex(Q);if(Z===-1)return[...J,$];let W=J.slice();return W[Z]=$,W}class i${store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,$,Q,Z){this.store=J;this.threadId=$;this.report=Z;this.state=c9({messages:Q})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[d$(J)])}frame(J){if(this.closed)return;let $=J.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=m9(this.state,J),$.type){case"message":this.write(()=>[d$($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let $ of J)this.done.add($.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let $=this.state.messages.find((Z)=>Z.id===J);if(!$)return;let Q=this.runId;this.write(()=>{let Z=d$($);if(Z.finishReason===void 0&&Q)Z.runId=Q;return[Z]})}write(J){let $;try{$=J()}catch(Q){this.report(Q);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Q)=>this.report(Q))}}function d$(J){return structuredClone(J)}async function d9(J,$){let Q=[],Z=null,W=J.slice();for(let K=0;K<W.length;K++){let X=W[K];if(X.role!=="assistant"||X.finishReason!==void 0)continue;if(X.runId&&await $(X.runId))continue;Z??=new Set(J.flatMap((Y)=>Y.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let G=X.content.map((Y)=>Y.type==="tool-call"?i9(Y):Y);for(let Y of X.content){if(Y.type!=="tool-call"||Z.has(Y.toolCallId))continue;let H={type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"denied",cause:"interrupted"};G.push(H)}let V={...X,content:G,finishReason:"interrupted"};W[K]=V,Q.push(V)}return{messages:W,settled:Q}}function i9(J){let{partial:$,...Q}=J;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(W0)}}function W0(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Q)=>Q.type==="tool-call"?i9(Q):Q)}:$)}}var K0=50,X0=["running","ok","error"];async function s9(J,$){let{store:Q,threadId:Z}=$,W=Math.max(K0,$.scan??0),K=await Q.listForThread(Z,{limit:W}),X,G=async(F)=>{if(F.state!=="running")return F;if(X??=await n9(Q),F.deadlineAt>X)return F;return await o9(Q,F),await Q.get(F.id)??F};for(let F=0;F<K.length;F++)K[F]=await G(K[F]);let V=new Map(K.map((F)=>[F.id,F])),Y=J.slice(),H=[],D=new Set;for(let F=0;F<Y.length;F++){let U=Y[F],N=null;for(let B=0;B<U.content.length;B++){let P=U.content[B];if(P.type==="tool-call")D.add(P.toolCallId);if(P.type!=="tool-result"||P.status!=="running")continue;let L=P.job?.id,O=L?V.get(L):void 0;if(L&&O===void 0){let j=await Q.get(L);if(O=j?await G(j):void 0,O)V.set(L,O)}if(O?.state==="running")continue;N??=U.content.slice(),N[B]=Y0(P,O,$.outputSchemaFor,$.modelOutputFor)}if(N){let B={...U,content:N};Y[F]=B,H.push(B)}}let z=[];for(let F of K){if(F.orphaned||D.has(F.toolCallId))continue;if(await $.isRunLive(F.runId))continue;z.push(F)}return{messages:Y,settled:H,orphans:z,jobs:K}}async function a9(J,$,Q){for(let Z of $)try{await J.transition(Z.id,X0,{orphaned:!0})}catch(W){Q(W)}}function Y0(J,$,Q,Z){let W={type:"tool-result",toolCallId:J.toolCallId,name:J.name},K=(V,Y)=>{let H=Z?.(String(J.name),V);return{...W,status:"ok",job:Y,output:V,...H!==void 0?{modelOutput:H}:{}}};if(!$)return{...W,status:"error",job:J.job,error:{code:"tool_error",message:`The background job for "${String(J.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:J.toolCallId,retryable:!0}};let X={id:$.id,...$.summary!==void 0?{summary:$.summary}:{},...$.usage?{usage:$.usage}:{}};if($.state==="error")return{...W,status:"error",job:X,error:$.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let G=Q?.(String(J.name));if(G){let V=G.safeParse($.output);if(V.ok===!1)return{...W,status:"error",job:X,error:{code:"invalid_tool_result",message:`The background job for "${String(J.name)}" finished with an output that does not match the tool's output schema: ${V.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return K(V.value,X)}return K($.output,X)}class oJ extends Error{status;code;kind;constructor(J,$){super(J);this.name="AgentTurnError",this.status=$.status,this.code=$.code,this.kind=$.kind}static async from(J){let $={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")$=Z.error}catch{}let Q=(Z)=>typeof $[Z]==="string"?$[Z]:void 0;return new oJ(Q("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:Q("code"),kind:Q("kind")})}}function G0(J){for(let $=J.length-1;$>=0;$--){let Q=J[$];if(Q.role!=="assistant")continue;return Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var V0=YQ,gJ=new Map,t9=new WeakMap,BJ=new WeakMap,r9="http://gemi.internal/__gemi/agent-turn",uJ=new Map,H0=4194304,z0=1000,D0=5,cJ=65536,mJ=()=>{};class MQ{byKey=new Map;take(J,$,Q){let Z=this.byKey.get(J);if(!Z?.has($)&&(Z?.size??0)>=Q)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set($,(Z.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let K=this.byKey.get(J),X=(K?.get($)??1)-1;if(!K)return;if(X>0)K.set($,X);else if(K.delete($),K.size===0)this.byKey.delete(J)}}}var e9=new WeakMap;function F0(J){let $=e9.get(J);if(!$)$=new MQ,e9.set(J,$);return $}function B0(J){return J}class Q8 extends V0{static kind="agent-controller";hooks;store=l$;liveRuns=h$;voice;voiceStore=v$;attachments=nJ;attachmentStorage=HQ;fileOwners=g$;nonces=e$;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,$){return this.hooks?.instructions?.(J,$)}reasoning(J,$){return this.hooks?.reasoning?.(J,$)}skills(J,$){return this.hooks?.skills?.(J,$)}context(J,$){let Q=this.hooks?.context;if(Q)return Q(J,$);return{}}memoryScopes(J,$){let Q=this.hooks?.memoryScopes;if(Q)return Q(J,$);return{}}memoryMaxTokens=void 0;requireThread=!1;maxBodyBytes=H0;maxHistoryMessages=z0;contextWindow=void 0;prepareStep(J,$){return this.hooks?.prepareStep?.(J,$)}maxConcurrentRuns=D0;runLimitKey(J,$){let Q=this.hooks?.runLimitKey;if(Q)return Q(J,$);return $.owner}authorizeRequest(J,$){let Q=this.hooks?.authorizeRequest;if(Q)return Q(J,$);return this.resource?.authorize(J,$)}resource;runOwner(J){let $=this.hooks?.runOwner;if($)return $(J);let Q=J.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(J){let{threadId:$}=J;if(typeof $!=="string"||$==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let Q={...J.turn,...J.text!==void 0?{text:J.text}:{}},Z={...J.body,threadId:$,turn:Q},W=new q(new Request(r9,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)}),{},"api",new URL(r9).pathname),K=new this;BJ.set(W,null);let X=await h.run(W,()=>K.stream(W),{user:J.user??null}),G=BJ.get(W);if(!G)throw await oJ.from(X);BJ.delete(W),X.body?.cancel().catch(mJ);let{run:V,hooks:Y}=G,H=[],D=(async()=>{for await(let F of V)if(F.type==="awaiting-input")H=F.pending})().catch(mJ),z;return{runId:V.runId,threadId:$,run:V,stop:(F)=>V.stop(F),result:()=>z??=(async()=>{let F=await V.result();await Promise.all([Y,D]);let U=F.messages;return{...F,threadId:$,text:G0(U),pending:F.finishReason==="awaiting-input"?H:[]}})()}}async stream(J=new q){let $=await PJ(J,this.maxBodyBytes);if($.error)return JJ($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=M0(Q);if(W.error)return JJ({body:{},error:W.error});let K=W.turn,X=Z!==void 0&&Q.regenerate===!0,G=typeof Q.clientRunId==="string"?Q.clientRunId:void 0,V=pJ(Q);if(this.requireThread&&!Z)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(X&&!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(Q.messages)&&Q.messages.length>this.maxHistoryMessages)return t$(413,"history_too_long",`The conversation has ${Q.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(J),H=G?{cancelled:!1,owner:Y}:null;if(H)uJ.set(G,H);let D=null,z=[],F=async()=>{try{return await U()}finally{if(Z&&z.length>0&&D===null)await this.store.appendMessages(Z,z).catch((N)=>this.reportHookFailure(N))}},U=async()=>{let N,B=null;if(Z){let T=await this.store.loadThread(Z);if(!T)return M(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});let i=await this.settleThread(Z,T,{write:!0});if(N=i.messages,B=this.jobsBlock(i.jobs),X){let $J=T0(N);if(!$J)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});z=N.slice($J.index),await this.store.removeMessages(Z,z.map((EQ)=>EQ.id)),N=N.slice(0,$J.index),K=K?.localId?{...$J.turn,localId:K.localId}:$J.turn}}else N=Array.isArray(Q.messages)?Q.messages:[],b0(this.nonces);let P=[await this.instructions(J,{body:V})||void 0,B??void 0].filter(Boolean).join(`
|
|
240
|
+
return 0`;class d${injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:receipt"}async claim(J,$){let Q=await this.client.send("EVAL",[Q0,"1",this.key(J),g9,u9($)]);if(Q==="claimed")return{status:"claimed"};let Z=String(Q??"");if(Z.startsWith(m$))return{status:"replay",result:JSON.parse(Z.slice(m$.length))};return{status:"blocked"}}async complete(J,$,Q){await this.client.send("SET",[this.key(J),m$+JSON.stringify($),"PX",u9(Q)])}async release(J){await this.client.send("EVAL",[Z0,"1",this.key(J),g9])}key(J){return`${this.prefix}:${J}`}get client(){if(this.injectedClient)return this.injectedClient;let J=c9(),$=J.bound(p$)?J.make(p$).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function u9(J){return String(Math.max(1,Math.ceil(J-Date.now())))}var W0=86400000,K0=60000;class uJ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(J={}){this.ttlMs=J.ttlMs??W0,this.clientOwnedIds=J.clientOwnedIds??!1}async createThread(J){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(J){this.sweep();let $=this.threads.get(J);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(J,$){this.sweep();let Q=this.threads.get(J);if(!Q){if(!this.clientOwnedIds)throw Error(`Thread ${J} does not exist here, or has expired.`);Q={messages:[],touchedAt:Date.now()},this.threads.set(J,Q)}for(let Z of $){let W=Q.messages.findIndex((K)=>K.id===Z.id);if(W===-1)Q.messages.push(Z);else Q.messages[W]=Z}Q.touchedAt=Date.now()}async removeMessages(J,$){this.sweep();let Q=this.threads.get(J);if(!Q)return;let Z=new Set($);Q.messages=Q.messages.filter((W)=>!Z.has(W.id)),Q.touchedAt=Date.now()}async loadSummaries(J){return this.threads.get(J)?.summaries?.slice()??[]}async saveSummary(J,$){let Q=this.threads.get(J);if(!Q)return;Q.summaries=DJ(Q.summaries??[],$)}delete(J){this.threads.delete(J)}get size(){return this.threads.size}sweep(J=Date.now()){if(J-this.lastSweep<K0)return;this.lastSweep=J;for(let[$,Q]of this.threads)if(J-Q.touchedAt>this.ttlMs)this.threads.delete($)}}var i$=new uJ;function d9(J={}){return{messages:J.messages?[...J.messages]:[],pending:J.pending?[...J.pending]:[],error:null,threadId:J.threadId,seq:J.seq??-1,cursorRunId:J.cursorRunId,runMessageIds:[],loadedTools:[]}}function i9(J,$,Q=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==J.cursorRunId)&&$.seq<=J.seq)return J;return{...n9(J,$.event,Q),seq:$.seq}}function n9(J,$,Q){switch($.type){case"run-start":return{...J,messages:X0(J.messages,$.runId),runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??J.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return l(J,$.messageId,Q,(Z)=>({...Z,role:$.role}));case"text-delta":if(p9(J,$.messageId))return J;return l(J,$.messageId,Q,(Z)=>({...Z,content:z0(Z.content,$.delta)}));case"reasoning-delta":if(p9(J,$.messageId))return J;return l(J,$.messageId,Q,(Z)=>({...Z,content:D0(Z.content,$.delta,$.id)}));case"output-delta":return l(J,$.messageId,Q,(Z)=>({...Z,content:l9(Z.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return l(J,$.messageId,Q,(Z)=>{let W=Z.content.findIndex((D)=>D.type==="tool-call"&&D.toolCallId===$.part.toolCallId),K=W===-1?void 0:Z.content[W],X=$.part.progress??K?.progress,G=$.part.nested??K?.nested,V=$.part.attachments??K?.attachments,Y={...$.part,...X?{progress:X}:{},...G?{nested:G}:{},...V?{attachments:V}:{}},H=Z.content.slice();if(W===-1)H.push(Y);else H[W]=Y;return{...Z,content:H}});case"tool-search":{let Z=$.loaded.filter((W)=>!J.loadedTools.includes(W));if(Z.length===0)return J;return{...J,loadedTools:[...J.loadedTools,...Z]}}case"tool-progress":return m9(J,$.toolCallId,(Z)=>({...Z,progress:[...Z.progress??[],$.data]}));case"nested-event":{let Z=$;return m9(J,$.toolCallId,(W)=>{let K=W.nested??[],X=K.findIndex((H)=>H.runId===Z.runId),G=K[X]??{runId:Z.runId,agent:Z.agent,messages:[]},V=V0(G,Z,Q),Y=X===-1?[...K,V]:K.map((H,D)=>D===X?V:H);return{...W,nested:Y}})}case"tool-result":{let Z=l(J,$.messageId,Q,(W)=>({...W,content:l9(W.content,$.part,(K)=>K.type==="tool-result"&&K.toolCallId===$.part.toolCallId)}));return{...Z,pending:Z.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let Z=J.messages.findIndex((X)=>X.id===$.message.id),W=J.messages.slice();if(Z===-1)W.push($.message);else W[Z]=$.message;let K=J.runMessageIds.includes($.message.id)?J.runMessageIds:[...J.runMessageIds,$.message.id];return{...J,messages:W,runMessageIds:K}}case"message-id":{let Z=J.messages.findIndex((G)=>G.id===$.localId);if(Z===-1){if(!$.message||J.messages.some((G)=>G.id===$.messageId))return J;return{...J,messages:[...J.messages,$.message]}}let W=J.messages[Z],K={localId:W.localId??W.id,...W.metadata?{metadata:W.metadata}:{}},X=J.messages.some((G)=>G.id===$.messageId)?J.messages.filter((G,V)=>V!==Z).map((G)=>G.id===$.messageId?{...G,...K}:G):J.messages.map((G,V)=>V===Z?{...G,...K,id:$.messageId}:G);return{...J,messages:X}}case"awaiting-input":return{...J,runId:$.runId,pending:[...$.pending]};case"message-end":return l(J,$.messageId,Q,(Z)=>({...Z,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.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{...J,usage:$.usage};case"error":return{...J,error:$.error,pending:[]};case"run-end":return{...J,runId:void 0,finishReason:$.finishReason,messages:o9(J,$.finishReason)};default:return J}}function X0(J,$){if(!J.some((Q)=>Q.runId===$&&Q.finishReason===void 0))return J;return J.map((Q)=>{if(Q.runId!==$||Q.finishReason!==void 0)return Q;let{runId:Z,...W}=Q;return{...W,content:[]}})}function o9(J,$){return J.messages.map((Q)=>Q.role==="assistant"&&J.runMessageIds.includes(Q.id)?Y0(Q,$):Q)}function Y0(J,$){let Q=J.content.map((W)=>W.type==="tool-call"&&W.nested?.some((K)=>K.finishReason===void 0)?{...W,nested:W.nested.map((K)=>K.finishReason===void 0?G0(K,$):K)}:W);if(J.finishReason===void 0)return{...J,finishReason:$,content:Q};return Q.some((W,K)=>W!==J.content[K])?{...J,content:Q}:J}function G0(J,$){let Q={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((Z)=>Z.id),loadedTools:[]};return{...J,finishReason:$,messages:o9(Q,$)}}function m9(J,$,Q){for(let Z=J.messages.length-1;Z>=0;Z--){let W=J.messages[Z],K=W.content.findIndex((Y)=>Y.type==="tool-call"&&Y.toolCallId===$);if(K===-1)continue;if(W.finishReason!==void 0&&!H0(J,W,$))return J;let X=W.content.slice();X[K]=Q(X[K]);let G=J.messages.slice();G[Z]={...W,content:X};let V=J.runMessageIds.includes(W.id)?J.runMessageIds:[...J.runMessageIds,W.id];return{...J,runMessageIds:V,messages:G}}return J}function V0(J,$,Q){let Z={messages:J.messages,pending:[],error:null,seq:-1,runMessageIds:J.messages.map((K)=>K.id),loadedTools:[],finishReason:J.finishReason},W=n9(Z,$.event,Q);return{...J,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function H0(J,$,Q){if($.finishReason!=="awaiting-input")return!1;return!J.messages.some((Z)=>Z.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Q))}function p9(J,$){let Q=J.messages.find((Z)=>Z.id===$);return Q!==void 0&&Q.finishReason!==void 0}function l(J,$,Q,Z){let W=J.messages.findIndex((G)=>G.id===$),K=J.runMessageIds.includes($)?J.runMessageIds:[...J.runMessageIds,$];if(W===-1){let G={id:$,role:"assistant",content:[],createdAt:Q};return{...J,runMessageIds:K,messages:[...J.messages,Z(G)]}}let X=J.messages.slice();return X[W]=Z(X[W]),{...J,runMessageIds:K,messages:X}}function z0(J,$){let Q=J[J.length-1];if(Q&&Q.type==="text")return[...J.slice(0,-1),{type:"text",text:Q.text+$}];return[...J,{type:"text",text:$}]}function D0(J,$,Q){let Z=J[J.length-1];if(Z&&Z.type==="reasoning"&&Z.id===Q)return[...J.slice(0,-1),{...Z,text:(Z.text??"")+$}];return[...J,Q?{type:"reasoning",id:Q,text:$}:{type:"reasoning",text:$}]}function l9(J,$,Q){let Z=J.findIndex(Q);if(Z===-1)return[...J,$];let W=J.slice();return W[Z]=$,W}class o${store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(J,$,Q,Z){this.store=J;this.threadId=$;this.report=Z;this.state=d9({messages:Q})}finish(J){if(this.closed)return;this.done.add(J.id),this.write(()=>[n$(J)])}frame(J){if(this.closed)return;let $=J.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=i9(this.state,J),$.type){case"message":this.write(()=>[n$($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(J=[]){this.closed=!0;for(let $ of J)this.done.add($.id)}settled(){return this.chain}checkpoint(J){if(this.done.has(J))return;let $=this.state.messages.find((Z)=>Z.id===J);if(!$)return;let Q=this.runId;this.write(()=>{let Z=n$($);if(Z.finishReason===void 0&&Q)Z.runId=Q;return[Z]})}write(J){let $;try{$=J()}catch(Q){this.report(Q);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Q)=>this.report(Q))}}function n$(J){return structuredClone(J)}async function s9(J,$){let Q=[],Z=null,W=J.slice();for(let K=0;K<W.length;K++){let X=W[K];if(X.role!=="assistant"||X.finishReason!==void 0)continue;if(X.runId&&await $(X.runId))continue;Z??=new Set(J.flatMap((Y)=>Y.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let G=X.content.map((Y)=>Y.type==="tool-call"?a9(Y):Y);for(let Y of X.content){if(Y.type!=="tool-call"||Z.has(Y.toolCallId))continue;let H={type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"denied",cause:"interrupted"};G.push(H)}let V={...X,content:G,finishReason:"interrupted"};W[K]=V,Q.push(V)}return{messages:W,settled:Q}}function a9(J){let{partial:$,...Q}=J;if(!Q.nested?.some((Z)=>Z.finishReason===void 0))return Q;return{...Q,nested:Q.nested.map(B0)}}function B0(J){if(J.finishReason!==void 0)return J;return{...J,finishReason:"interrupted",messages:J.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Q)=>Q.type==="tool-call"?a9(Q):Q)}:$)}}var F0=50,P0=["running","ok","error"];async function e9(J,$){let{store:Q,threadId:Z}=$,W=Math.max(F0,$.scan??0),K=await Q.listForThread(Z,{limit:W}),X,G=async(B)=>{if(B.state!=="running")return B;if(X??=await t9(Q),B.deadlineAt>X)return B;return await r9(Q,B),await Q.get(B.id)??B};for(let B=0;B<K.length;B++)K[B]=await G(K[B]);let V=new Map(K.map((B)=>[B.id,B])),Y=J.slice(),H=[],D=new Set;for(let B=0;B<Y.length;B++){let U=Y[B],N=null;for(let F=0;F<U.content.length;F++){let P=U.content[F];if(P.type==="tool-call")D.add(P.toolCallId);if(P.type!=="tool-result"||P.status!=="running")continue;let L=P.job?.id,O=L?V.get(L):void 0;if(L&&O===void 0){let j=await Q.get(L);if(O=j?await G(j):void 0,O)V.set(L,O)}if(O?.state==="running")continue;N??=U.content.slice(),N[F]=N0(P,O,$.outputSchemaFor,$.modelOutputFor)}if(N){let F={...U,content:N};Y[B]=F,H.push(F)}}let z=[];for(let B of K){if(B.orphaned||D.has(B.toolCallId))continue;if(await $.isRunLive(B.runId))continue;z.push(B)}return{messages:Y,settled:H,orphans:z,jobs:K}}async function JQ(J,$,Q){for(let Z of $)try{await J.transition(Z.id,P0,{orphaned:!0})}catch(W){Q(W)}}function N0(J,$,Q,Z){let W={type:"tool-result",toolCallId:J.toolCallId,name:J.name},K=(V,Y)=>{let H=Z?.(String(J.name),V);return{...W,status:"ok",job:Y,output:V,...H!==void 0?{modelOutput:H}:{}}};if(!$)return{...W,status:"error",job:J.job,error:{code:"tool_error",message:`The background job for "${String(J.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:J.toolCallId,retryable:!0}};let X={id:$.id,...$.summary!==void 0?{summary:$.summary}:{},...$.usage?{usage:$.usage}:{}};if($.state==="error")return{...W,status:"error",job:X,error:$.error??{code:"tool_error",message:`The background job for "${String(J.name)}" failed.`,toolCallId:J.toolCallId,retryable:!0}};let G=Q?.(String(J.name));if(G){let V=G.safeParse($.output);if(V.ok===!1)return{...W,status:"error",job:X,error:{code:"invalid_tool_result",message:`The background job for "${String(J.name)}" finished with an output that does not match the tool's output schema: ${V.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return K(V.value,X)}return K($.output,X)}class aJ extends Error{status;code;kind;constructor(J,$){super(J);this.name="AgentTurnError",this.status=$.status,this.code=$.code,this.kind=$.kind}static async from(J){let $={};try{let Z=await J.json();if(Z?.error&&typeof Z.error==="object")$=Z.error}catch{}let Q=(Z)=>typeof $[Z]==="string"?$[Z]:void 0;return new aJ(Q("message")??`The agent turn was refused with status ${J.status}.`,{status:J.status,code:Q("code"),kind:Q("kind")})}}function U0(J){for(let $=J.length-1;$>=0;$--){let Q=J[$];if(Q.role!=="assistant")continue;return Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")}return""}var L0=zQ,cJ=new Map,$Q=new WeakMap,FJ=new WeakMap,QQ="http://gemi.internal/__gemi/agent-turn",mJ=new Map,O0=4194304,C0=1000,_0=5,pJ=65536,lJ=()=>{};class TQ{byKey=new Map;take(J,$,Q){let Z=this.byKey.get(J);if(!Z?.has($)&&(Z?.size??0)>=Q)return null;if(!Z)Z=new Map,this.byKey.set(J,Z);Z.set($,(Z.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let K=this.byKey.get(J),X=(K?.get($)??1)-1;if(!K)return;if(X>0)K.set($,X);else if(K.delete($),K.size===0)this.byKey.delete(J)}}}var ZQ=new WeakMap;function M0(J){let $=ZQ.get(J);if(!$)$=new TQ,ZQ.set(J,$);return $}function S0(J){return J}class W8 extends L0{static kind="agent-controller";hooks;store=i$;liveRuns=u$;voice;voiceStore=h$;attachments=sJ;attachmentStorage=FQ;fileOwners=c$;nonces=$8;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(J,$){return this.hooks?.instructions?.(J,$)}reasoning(J,$){return this.hooks?.reasoning?.(J,$)}skills(J,$){return this.hooks?.skills?.(J,$)}context(J,$){let Q=this.hooks?.context;if(Q)return Q(J,$);return{}}memoryScopes(J,$){let Q=this.hooks?.memoryScopes;if(Q)return Q(J,$);return{}}memoryMaxTokens=void 0;requireThread=!1;maxBodyBytes=O0;maxHistoryMessages=C0;contextWindow=void 0;prepareStep(J,$){return this.hooks?.prepareStep?.(J,$)}maxConcurrentRuns=_0;runLimitKey(J,$){let Q=this.hooks?.runLimitKey;if(Q)return Q(J,$);return $.owner}authorizeRequest(J,$){let Q=this.hooks?.authorizeRequest;if(Q)return Q(J,$);return this.resource?.authorize(J,$)}resource;runOwner(J){let $=this.hooks?.runOwner;if($)return $(J);let Q=J.ctx?.()?.user,Z=Q?.id??Q?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}static async startTurn(J){let{threadId:$}=J;if(typeof $!=="string"||$==="")throw TypeError("AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.");let Q={...J.turn,...J.text!==void 0?{text:J.text}:{}},Z={...J.body,threadId:$,turn:Q},W=new q(new Request(QQ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)}),{},"api",new URL(QQ).pathname),K=new this;FJ.set(W,null);let X=await h.run(W,()=>K.stream(W),{user:J.user??null}),G=FJ.get(W);if(!G)throw await aJ.from(X);FJ.delete(W),X.body?.cancel().catch(lJ);let{run:V,hooks:Y}=G,H=[],D=(async()=>{for await(let B of V)if(B.type==="awaiting-input")H=B.pending})().catch(lJ),z;return{runId:V.runId,threadId:$,run:V,stop:(B)=>V.stop(B),result:()=>z??=(async()=>{let B=await V.result();await Promise.all([Y,D]);let U=B.messages;return{...B,threadId:$,text:U0(U),pending:B.finishReason==="awaiting-input"?H:[]}})()}}async stream(J=new q){let $=await PJ(J,this.maxBodyBytes);if($.error)return JJ($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:void 0,W=q0(Q);if(W.error)return JJ({body:{},error:W.error});let K=W.turn,X=Z!==void 0&&Q.regenerate===!0,G=typeof Q.clientRunId==="string"?Q.clientRunId:void 0,V=dJ(Q);if(this.requireThread&&!Z)return M(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(X&&!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(Q.messages)&&Q.messages.length>this.maxHistoryMessages)return e$(413,"history_too_long",`The conversation has ${Q.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let Y=await this.runOwner(J),H=G?{cancelled:!1,owner:Y}:null;if(H)mJ.set(G,H);let D=null,z=[],B=async()=>{try{return await U()}finally{if(Z&&z.length>0&&D===null)await this.store.appendMessages(Z,z).catch((N)=>this.reportHookFailure(N))}},U=async()=>{let N,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 i=await this.settleThread(Z,E,{write:!0});if(N=i.messages,F=this.jobsBlock(i.jobs),X){let $J=f0(N);if(!$J)return M(409,{code:"nothing_to_regenerate",message:`Thread ${Z} has no user turn to answer again.`});z=N.slice($J.index),await this.store.removeMessages(Z,z.map((IQ)=>IQ.id)),N=N.slice(0,$J.index),K=K?.localId?{...$J.turn,localId:K.localId}:$J.turn}}else N=Array.isArray(Q.messages)?Q.messages:[],p0(this.nonces);let P=[await this.instructions(J,{body:V})||void 0,F??void 0].filter(Boolean).join(`
|
|
241
241
|
|
|
242
|
-
`)||void 0,L=await this.context(J,{body:V}),O=await this.reasoning(J,{body:V})||void 0,j=await this.skills(J,{body:V})||void 0,k=await this.attachmentsFor(J,Z,{body:V}),I=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(H?.cancelled)return WQ();let x=Z?new i$(this.store,Z,N,(T)=>this.reportHookFailure(T)):null,d=`run_${crypto.randomUUID()}`,_={req:J,runId:d,threadId:Z},R={id:null,notified:Promise.resolve()},C=this.agent.stream({runId:d,messages:N,turn:K,threadId:Z,...x?{onMessage:(T)=>x.finish(T)}:{},onTurn:(T)=>{if(R.id!==null)return;R.id=T.id;let i=x?x.settled():Promise.resolve();R.notified=i.then(()=>this.safely(()=>this.onMessage(T,_)))},instructions:P,...O?{reasoning:O}:{},...j&&j.length>0?{skills:j}:{},context:L,attachments:k,body:V,redactError:(T,i)=>this.redactError(T,i,_),nonces:this.nonces,receipts:this.receipts,subject:Y,...I?{memory:{scopes:I,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&CQ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==Q8.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(T)=>this.prepareStep(T,_)}:{}}),RQ=this.liveRuns.register(C,{threadId:Z,owner:Y,clientRunId:G,onEvent:(T)=>this.dispatchEvent(T,_),onInternalError:(T)=>this.reportHookFailure(T),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=C,x)this.follow(C,x);let{stored:TQ,hooks:Z8}=this.persistRun(C,_,RQ,x,R);if(t9.set(C,TQ),BJ.has(J))BJ.set(J,{run:C,hooks:Z8});return J.ctx?.()?.waitUntil(Z8),C.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let N=await this.foreignFile([...K?.files??[],...Z?[]:j0(Q.messages)],Y);if(N)return N;if(H?.cancelled)return WQ();let B=await this.runLimitKey(J,{owner:Y,threadId:Z}),P=B===null?mJ:F0(this.liveRuns).take(B,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return t$(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return Z?await this.withThread(Z,Y,F):await F()}finally{let L=D;if(L)L.result().then(P,P);else P()}}finally{if(H&&uJ.get(G)===H)uJ.delete(G)}}async withThread(J,$,Q){let Z=gJ.get(J)??Promise.resolve(),W,K=new Promise((G)=>{W=G}),X=Z.then(()=>K);gJ.set(J,X),await Z;try{let G=await this.liveRuns.find({threadId:J});if(G&&this.liveRuns.isRunning(G.runId)&&!this.liveRuns.mayAccess(G.runId,$))return NJ();let V=G?this.liveRuns.get(G.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await t9.get(V);return await Q()}finally{if(W(),gJ.get(J)===X)gJ.delete(J)}}async attach(J=new q){let $=await PJ(J,cJ);if($.error)return JJ($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:R0(J,"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(J,{route:"attach",threadId:Z});let W=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(J)))return NJ();if(!W)return M(404,{code:"no_live_run",message:`No run in progress for thread ${Z} in this process.`});let K=typeof Q.runId==="string"?Q.runId:void 0,X=K&&K!==W.runId?void 0:A0(J,Q);try{return zQ(this.liveRuns.replay(W.runId,X))}catch(G){if(G instanceof e)return M(410,{code:G.code,message:G.message,oldestSeq:G.oldest});if(G instanceof FJ)return M(404,{code:G.code,message:G.message});throw G}}async stop(J=new q){let $=await PJ(J,cJ);if($.error)return JJ($);let Q=$.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner(J),W=typeof Q.runId==="string"?Q.runId:void 0;if(!W&&typeof Q.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Q.clientRunId)??void 0,!W){let X=uJ.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return NJ();return X.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Q.threadId==="string")W=(await this.liveRuns.find({threadId:Q.threadId}))?.runId;let K=W?this.liveRuns.get(W):null;if(!K)return{stopped:!1};if(!this.liveRuns.mayAccess(K.runId,Z))return NJ();return K.stop({reason:typeof Q.reason==="string"?Q.reason:void 0}),{stopped:!0}}attachmentScope(J,$,Q){let Z=this.hooks?.attachmentScope;if(Z)return Z(J,$,Q);let W=J.ctx()?.user,K=W?.id??W?.publicId;if(K!==void 0&&K!==null&&String(K)!=="")return{key:`user:${String(K)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(J){let $=this.hooks?.attachmentLimits;if($)return $(J);return null}checkUpload(J,$,Q){return this.hooks?.checkUpload?.(J,$,Q)}attachmentDestination(J,$,Q){let Z=this.hooks?.attachmentDestination;if(Z)return Z(J,$,Q);return"both"}async attachmentsFor(J,$,Q={body:{}}){let Z=await this.attachmentScope(J,$,Q);if(!Z)return null;return new iJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new q){let $=this.voice;if(!$)return n$();let Q=await PJ(J,cJ);if(Q.error)return JJ(Q);let{sdp:Z,threadId:W,pushToTalk:K}=Q.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 X=pJ(Q.body,k0),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:G,body:X});let V=J.ctx?.()?.user??null,Y=await $.start({req:J,body:X,threadId:G,user:V,pushToTalk:K===!0}),H=Date.now(),D,z=async(L)=>{if(L!==void 0)console.error("[gemi/ai] a voice session could not start.",L);if(D)await $.realtime.hangup(D).catch((O)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",O)});try{await Y.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:Y.threadId??G??"",reason:"start_failed",startedAt:H,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)}},F=Y.threadId??G;if(!F)return await z(void 0),M(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(F!==G)await this.authorizeRequest(J,{route:"stream",threadId:F,body:X})}catch(L){throw await z(void 0),L}let U=crypto.randomUUID(),N=Y.tools??[];try{if(Y.mcp)N=[...N,...await b$(Y.mcp,{user:V,sessionId:U})]}catch(L){return await z(L),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let B={...Y.session,tools:[...HJ($.delegate),...Y.session?.tools??[],...N.map((L)=>L.tool)],...K===!0?{turnDetection:null}:{}},P;try{P=await $.realtime.createCall({sdp:Z,session:B,safetyIdentifier:Y.safetyIdentifier})}catch(L){await z(L);let O=L instanceof f&&L.code==="rate_limited";return M(O?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=P.callId;try{await this.voiceStore.create({id:U,callId:P.callId,threadId:F,owner:await this.runOwner(J),body:X,startedAt:H});let{threadId:L,session:O,safetyIdentifier:j,mcp:k,tools:I,...x}=Y;return{sessionId:p.start({...x,tools:N,controller:this.constructor,threadId:F,user:V,body:X,call:{realtime:$.realtime,callId:P.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:B}).sessionId,sdp:P.sdpAnswer,threadId:F,delegate:$.delegate?.name??zJ,endsAt:H+(Y.limits?.maxDurationMs??900000)}}catch(L){return await z(L),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new q){if(!this.voice)return n$();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await PJ(J,cJ);if(Q.error)return JJ(Q);let Z=pJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),p.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new q){let $=this.voice;if(!$)return n$();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Q.body}),Q.endedAt!==void 0)return{ended:!1};let Z=p.get(Q.id);if(Z)await Z.end("hangup");else await $.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let $=J.params?.sessionId,Q=typeof $==="string"&&$?await this.voiceStore.get($):null;if(!Q)return M(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return NJ();return Q}async upload(J=new q){let $=await J.rawRequest.formData(),Q=$.get("file");if(!(Q instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=Q instanceof File&&Q.name?Q.name:"upload",W=Q.type||"application/octet-stream",K=N0($.get("body")),X=$.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:K});let G=L0(await this.attachmentLimits(J),Q,Z,W);if(G)throw new a$(G.code,G.message);let V=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,Y=await this.runOwner(J),H=(k)=>this.fileOwners.record(k,{owner:Y,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString()}),D={body:K,threadId:V},z=await this.checkUpload({name:Z,size:Q.size,mimeType:W},J,D);if(z)throw new a$(z.code||"upload_refused",z.message);let F=await this.attachmentDestination(Q,J,D),U=x0(F,$.get("destination")),N=await this.attachmentScope(J,V,{body:K}),B=U!=="provider"&&!N;if(B){if(U==="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()`.');q0()}if(U==="provider"||!N){let k=await JQ(this.agent.provider,Q);await H(k);let I={fileId:k,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(B)I.downgraded="no_scope";return I}let P=UQ(),L=await this.attachmentStorage.put({name:LQ(P,Z),body:Q,contentType:W}),O=U==="both"?await JQ(this.agent.provider,Q):void 0;if(O)await H(O);let j={id:P,scopeKey:N.key,fileId:O,objectName:L,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:U};return await this.attachments.put(N,j),{fileId:O,attachmentId:P,name:Z,mimeType:W,size:Q.size,destination:U}}async foreignFile(J,$){let Q=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of Q){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return E0()}return null}onMessage(J,$){return this.hooks?.onMessage?.(J,$)}onToolCall(J,$){return this.hooks?.onToolCall?.(J,$)}onToolResult(J,$){return this.hooks?.onToolResult?.(J,$)}onAwaitingInput(J,$){return this.hooks?.onAwaitingInput?.(J,$)}redactError(J,$,Q){let Z=this.hooks?.redactError;if(Z)return Z(J,$,Q);return J8(J,$)}onError(J,$){return this.hooks?.onError?.(J,$)}onStreamComplete(J,$){return this.hooks?.onStreamComplete?.(J,$)}reportHookFailure(J){let $=this.hooks?.reportHookFailure;if($)try{return $(J)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,$){switch(J.type){case"tool-call":if(!J.part.partial&&!J.resent)await this.onToolCall({toolCallId:J.part.toolCallId,name:String(J.part.name),input:J.part.input},$);return;case"tool-result":await this.onToolResult(J.part,$);return;case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(BQ(J.error),$);return;default:return}}async readThread(J){let $=await this.store.loadThread(J);return $?(await this.settleThread(J,$,{write:!1})).messages:null}isRunLive(J,$){return this.liveRuns.get(J)!==null}async settleThread(J,$,{write:Q}){let Z=(V)=>this.isRunLive(V,J),W=await d9($,Z),K=W.messages,X=[],G=new Map(W.settled.map((V)=>[V.id,V]));if(f0(K)||Q)try{let V=await s9(K,{threadId:J,store:v.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolNamed(Y)?.outputSchema,modelOutputFor:(Y,H)=>_Q(this.toolNamed(Y),H,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});K=V.messages,X=V.jobs;for(let Y of V.settled)G.set(Y.id,Y);if(Q&&V.orphans.length>0){await a9(v.store,V.orphans,(H)=>this.reportHookFailure(H));let Y=new Set(V.orphans.map((H)=>H.id));X=X.map((H)=>Y.has(H.id)?{...H,orphaned:!0}:H)}}catch(V){this.reportHookFailure(V)}if(Q&&G.size>0)try{await this.store.appendMessages(J,[...G.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:X}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??LJ}jobsBlock(J){return H8(J,this.jobsBlockMax())}toolNamed(J){let $=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let K=$(W.tools);if(K)return K}else if(W.name===J)return W}return};return $(this.agent.tools??[])}follow(J,$){(async()=>{try{for await(let Q of J.frames())$.frame(Q)}catch(Q){this.reportHookFailure(Q)}})()}persistRun(J,$,Q,Z=null,W={id:null,notified:Promise.resolve()}){let K=Promise.resolve(),X=(async()=>{let V;try{V=await J.result()}catch(H){Z?.close(),await Z?.settled(),K=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},$)));return}let Y=V.messages;if(Z?.close(Y),await Z?.settled(),$.threadId&&Y.length>0)try{await this.store.appendMessages($.threadId,Y)}catch(H){this.reportHookFailure(H)}K=this.notifyRun(V,Y,$,W)})(),G=X.then(()=>w0(Promise.all([K,Q]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:G}}async notifyRun(J,$,Q,Z){await Z.notified;for(let W of $){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete(J,Q))}async safely(J){try{await J()}catch($){this.reportHookFailure($)}}}var o$=["turn","clientRunId","threadId","messages","regenerate"],P0=["text","files","toolResults"];function pJ(J,$=AQ(J)?o$:[...o$,...P0]){let Q={};for(let[Z,W]of Object.entries(J)){if($.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function N0(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new s$("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new s$("The upload's `body` field must be a JSON object.");return pJ($,o$)}class s$ extends lJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function JQ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof w&&U0.has(Q.status))throw new SQ(E(Q).message);throw Q}}var U0=new Set([400,413,415,422]);class a$ extends lJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function L0(J,$,Q,Z){if(!J)return null;let{maxBytes:W,accept:K}=J;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${$Q($.size)}; the limit is ${$Q(W)}.`};if(K&&K.length>0&&!K.some((X)=>O0(X,Q,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify(Q)} is not a type this chat accepts. Accepted: ${K.join(", ")}.`};return null}function O0(J,$,Q){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return $.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function $Q(J){if(J<1024)return`${J} B`;let $=["KB","MB","GB"],Q=J/1024,Z=0;while(Q>=1024&&Z<$.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${$[Z]}`}class SQ extends lJ{constructor(J){super(J);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(J)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:J}}},view:{}}}}async function PJ(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!C0(Q.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(Q.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>$)return QQ($);let W;try{let X=await _0(Q,$);if(X===null)return QQ($);W=X}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let K;try{K=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(K===null||typeof K!=="object"||Array.isArray(K))return{body:{},error:"The request body must be a JSON object."};return{body:K}}function C0(J){return VQ(J)==="application/json"}async function _0(J,$){if(!Number.isFinite($)||!J.body)return await J.text();let Q=J.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:V}=await Q.read();if(G)break;if(W+=V.byteLength,W>$)return await Q.cancel().catch(mJ),null;Z.push(V)}let K=new Uint8Array(W),X=0;for(let G of Z)K.set(G,X),X+=G.byteLength;return new TextDecoder().decode(K)}function QQ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function t$(J,$,Q){return M(J,{...dJ(GQ(J),Q,J),code:$})}function JJ(J){if(J.status===413)return t$(413,J.code??"body_too_large",J.error??"");return M(J.status??400,{code:J.code??"invalid_request",message:J.error})}function AQ(J){return Boolean(J.turn)&&typeof J.turn==="object"}function M0(J){let $=AQ(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=S0($.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray($.toolResults))Q.toolResults=$.toolResults;if(Object.keys(Q).length===0)return{};if($===J.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:Z}=$;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>ZQ)return{error:`turn.localId is longer than ${ZQ} characters.`};Q.localId=Z}return{turn:Q}}var ZQ=200;function S0(J){let $=[];for(let[Q,Z]of J.entries()){let W=`turn.files[${Q}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let K={};for(let H of["fileId","attachmentId","name","mimeType"]){let D=Z[H];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${H} must be a string.`;K[H]=D}let{fileId:X,attachmentId:G,name:V,mimeType:Y}=K;if(X?.startsWith(m))return`${W}.fileId holds a gemi attachment id (${X}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(G!==void 0&&!G.startsWith(m))return`${W}.attachmentId is not a gemi attachment id: it must start with "${m}".`;if(!X&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...X?{fileId:X}:{},...G?{attachmentId:G}:{},...V!==void 0?{name:V}:{},...Y!==void 0?{mimeType:Y}:{}})}return $}function A0(J,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let Z=Math.floor($.cursor);if(Z>=0)return Z+1;return}let Q=J?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function R0(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function T0(J){let $=$8(J);for(let Q=J.length-1;Q>=0;Q--){let Z=J[Q];if(Z.role!=="user"||$.has(Z.id))continue;let W="",K=[];for(let X of Z.content){if(X.type==="text")W+=X.text;if(X.type==="file")K.push({...X.fileId?{fileId:X.fileId}:{},...X.attachmentId?{attachmentId:X.attachmentId}:{},...X.name?{name:X.name}:{},...X.mimeType?{mimeType:X.mimeType}:{}})}if(!W&&K.length===0)continue;return{index:Q,turn:{...W?{text:W}:{},...K.length>0?{files:K}:{}}}}return null}function WQ(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function NJ(){return M(403,dJ("permission","This run belongs to someone else.",403))}function E0(){return M(403,dJ("permission","A file in this turn was uploaded by someone else.",403))}function j0(J){if(!Array.isArray(J))return[];let $=[];for(let Q of J){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}var k0=["sdp","threadId","pushToTalk"];function n$(){return M(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function M(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function x0(J,$){if(typeof $!=="string"||$.length===0)return J;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===J||J==="both"&&$==="storage")return $;if(J==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${J}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var KQ=!1;function q0(){if(KQ)return;KQ=!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 I0=2147483647;function w0(J,$){let Q=J.then(()=>{},()=>{});if(!($<=I0))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var XQ=!1;function b0(J){if(XQ||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof r$))return;XQ=!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 f0(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}export{d0 as windowMessages,HJ as voiceTools,u0 as turnStarts,kJ as toRealtimeUsage,lQ as toAgentTools,h0 as supportsStrict,c0 as splitTurns,r0 as settleSummaries,y0 as s,J8 as redactError,m0 as messageSize,KJ as measureUsage,b$ as mcpVoiceTools,h$ as liveRuns,DJ as keepSummary,C9 as isCallNotFound,$8 as injectedMessageIds,V$ as generate,hZ as evalChain,B0 as defineAgentHooks,v$ as defaultVoiceStore,t0 as defaultSummaryStore,e$ as defaultNonceStore,g$ as defaultFileOwners,nJ as defaultAttachmentStore,l$ as defaultAgentStore,fJ as VoiceHangup,p as VoiceBridge,g0 as Usage,z$ as ToolNamespace,g as ToolError,J6 as Skill,iJ as ScopedAttachments,$6 as SKILLS_NAMESPACE,p$ as RedisReceiptStore,DQ as RedisNonceStore,xJ as RealtimeSideband,f as RealtimeRequestError,GJ as RealtimeClient,Y8 as Prompt,FQ as PrismaNonceStore,e0 as PendingEscalation,x$ as OpenAIProvider,N$ as OpenAIImageProvider,f$ as MemoryVoiceSessionStore,a0 as MemorySummaryStore,m$ as MemoryReceiptStore,r$ as MemoryNonceStore,vJ as MemoryLiveRuns,yJ as MemoryFileOwners,wJ as MemoryCircuitStore,OQ as MemoryAttachmentStore,hJ as MemoryAgentStore,F8 as MemoryAgentJobStore,x8 as MEMORY_NAMESPACE,FJ as LiveRunNotFoundError,P8 as JobsRequireThreadError,B8 as JobHandle,v0 as JSONSchemaError,NQ as InvalidAttachmentScopeError,A8 as InMemoryAgentMemoryStore,TJ as ImageRequestError,EJ as ImageProvider,D$ as ImageModel,e as FrameCursorEvictedError,VJ as FallbackProvider,j8 as FakeAgentMemoryStore,SJ as Eval,b9 as DatabaseAgentStore,Z$ as DatabaseAgentMemoryStore,$$ as DatabaseAgentJobStore,L9 as DEFAULT_TRANSCRIPTION_MODEL,S8 as DEFAULT_MEMORY_MAX_TOKENS,k8 as DEFAULT_MEMORY_LIMITS,i0 as DEFAULT_MAX_SUMMARY_TOKENS,Q6 as DEFAULT_MAX_RUN_DURATION_MS,N8 as DEFAULT_JOB_DEADLINE_MS,LJ as DEFAULT_JOBS_CONTEXT_MAX,zJ as DEFAULT_DELEGATE_NAME,p0 as DEFAULT_CONTEXT_WINDOW_STEP,l0 as DEFAULT_CONTEXT_WINDOW_NOTE,n0 as DEFAULT_COMPACT_TRIGGER_TOKENS,o0 as DEFAULT_COMPACT_INSTRUCTIONS,s0 as COMPACT_SUMMARY_HEADER,q$ as AzureOpenAIProvider,U$ as AzureOpenAIImageProvider,PQ as AttachmentNotFoundError,oJ as AgentTurnError,AJ as AgentTool,Z6 as AgentRunError,r as AgentProvider,R8 as AgentMemoryRefusedError,T8 as AgentMemoryConflictError,E8 as AgentMemories,v as AgentJobs,rJ as AgentJobDeadlineSweep,U8 as AgentJob,Q8 as AgentController,W6 as Agent};
|
|
242
|
+
`)||void 0,L=await this.context(J,{body:V}),O=await this.reasoning(J,{body:V})||void 0,j=await this.skills(J,{body:V})||void 0,k=await this.attachmentsFor(J,Z,{body:V}),I=this.agent.memory?await this.memoryScopes(J,{body:V}):void 0;if(H?.cancelled)return GQ();let x=Z?new o$(this.store,Z,N,(E)=>this.reportHookFailure(E)):null,d=`run_${crypto.randomUUID()}`,_={req:J,runId:d,threadId:Z},R={id:null,notified:Promise.resolve()},C=this.agent.stream({runId:d,messages:N,turn:K,threadId:Z,...x?{onMessage:(E)=>x.finish(E)}:{},onTurn:(E)=>{if(R.id!==null)return;R.id=E.id;let i=x?x.settled():Promise.resolve();R.notified=i.then(()=>this.safely(()=>this.onMessage(E,_)))},instructions:P,...O?{reasoning:O}:{},...j&&j.length>0?{skills:j}:{},context:L,attachments:k,body:V,redactError:(E,i)=>this.redactError(E,i,_),nonces:this.nonces,receipts:this.receipts,subject:Y,...I?{memory:{scopes:I,...this.memoryMaxTokens!==void 0?{maxTokens:this.memoryMaxTokens}:{}}}:{},...Z?{jobs:{owner:Y}}:{},...this.contextWindow!==void 0?{contextWindow:this.contextWindow}:{},...Z&&AQ(this.store)?{summaryStore:this.store}:{},...this.prepareStep!==W8.prototype.prepareStep||this.hooks?.prepareStep?{prepareStep:(E)=>this.prepareStep(E,_)}:{}}),xQ=this.liveRuns.register(C,{threadId:Z,owner:Y,clientRunId:G,onEvent:(E)=>this.dispatchEvent(E,_),onInternalError:(E)=>this.reportHookFailure(E),maxRunDurationMs:this.agent.maxRunDurationMs});if(D=C,x)this.follow(C,x);let{stored:qQ,hooks:K8}=this.persistRun(C,_,xQ,x,R);if($Q.set(C,qQ),FJ.has(J))FJ.set(J,{run:C,hooks:K8});return J.ctx?.()?.waitUntil(K8),C.toResponse()};try{await this.authorizeRequest(J,{route:"stream",threadId:Z,body:V});let N=await this.foreignFile([...K?.files??[],...Z?[]:y0(Q.messages)],Y);if(N)return N;if(H?.cancelled)return GQ();let F=await this.runLimitKey(J,{owner:Y,threadId:Z}),P=F===null?lJ:M0(this.liveRuns).take(F,Z?`thread:${Z}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!P)return e$(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return Z?await this.withThread(Z,Y,B):await B()}finally{let L=D;if(L)L.result().then(P,P);else P()}}finally{if(H&&mJ.get(G)===H)mJ.delete(G)}}async withThread(J,$,Q){let Z=cJ.get(J)??Promise.resolve(),W,K=new Promise((G)=>{W=G}),X=Z.then(()=>K);cJ.set(J,X),await Z;try{let G=await this.liveRuns.find({threadId:J});if(G&&this.liveRuns.isRunning(G.runId)&&!this.liveRuns.mayAccess(G.runId,$))return NJ();let V=G?this.liveRuns.get(G.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await $Q.get(V);return await Q()}finally{if(W(),cJ.get(J)===X)cJ.delete(J)}}async attach(J=new q){let $=await PJ(J,pJ);if($.error)return JJ($);let Q=$.body,Z=typeof Q.threadId==="string"?Q.threadId:b0(J,"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(J,{route:"attach",threadId:Z});let W=await this.liveRuns.find({threadId:Z});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(J)))return NJ();if(!W)return M(404,{code:"no_live_run",message:`No run in progress for thread ${Z} in this process.`});let K=typeof Q.runId==="string"?Q.runId:void 0,X=K&&K!==W.runId?void 0:w0(J,Q);try{return PQ(this.liveRuns.replay(W.runId,X))}catch(G){if(G instanceof e)return M(410,{code:G.code,message:G.message,oldestSeq:G.oldest});if(G instanceof BJ)return M(404,{code:G.code,message:G.message});throw G}}async stop(J=new q){let $=await PJ(J,pJ);if($.error)return JJ($);let Q=$.body;await this.authorizeRequest(J,{route:"stop",threadId:typeof Q.threadId==="string"?Q.threadId:void 0});let Z=await this.runOwner(J),W=typeof Q.runId==="string"?Q.runId:void 0;if(!W&&typeof Q.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Q.clientRunId)??void 0,!W){let X=mJ.get(Q.clientRunId);if(X){if(X.owner!==null&&X.owner!==Z)return NJ();return X.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Q.threadId==="string")W=(await this.liveRuns.find({threadId:Q.threadId}))?.runId;let K=W?this.liveRuns.get(W):null;if(!K)return{stopped:!1};if(!this.liveRuns.mayAccess(K.runId,Z))return NJ();return K.stop({reason:typeof Q.reason==="string"?Q.reason:void 0}),{stopped:!0}}attachmentScope(J,$,Q){let Z=this.hooks?.attachmentScope;if(Z)return Z(J,$,Q);let W=J.ctx()?.user,K=W?.id??W?.publicId;if(K!==void 0&&K!==null&&String(K)!=="")return{key:`user:${String(K)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(J){let $=this.hooks?.attachmentLimits;if($)return $(J);return null}checkUpload(J,$,Q){return this.hooks?.checkUpload?.(J,$,Q)}attachmentDestination(J,$,Q){let Z=this.hooks?.attachmentDestination;if(Z)return Z(J,$,Q);return"both"}async attachmentsFor(J,$,Q={body:{}}){let Z=await this.attachmentScope(J,$,Q);if(!Z)return null;return new oJ(this.attachments,this.attachmentStorage,Z)}async voiceStart(J=new q){let $=this.voice;if(!$)return s$();let Q=await PJ(J,pJ);if(Q.error)return JJ(Q);let{sdp:Z,threadId:W,pushToTalk:K}=Q.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 X=dJ(Q.body,h0),G=typeof W==="string"&&W!==""?W:void 0;await this.authorizeRequest(J,{route:"stream",threadId:G,body:X});let V=J.ctx?.()?.user??null,Y=await $.start({req:J,body:X,threadId:G,user:V,pushToTalk:K===!0}),H=Date.now(),D,z=async(L)=>{if(L!==void 0)console.error("[gemi/ai] a voice session could not start.",L);if(D)await $.realtime.hangup(D).catch((O)=>{console.error("[gemi/ai] a voice call that failed to start could not be hung up.",O)});try{await Y.onEnd?.({sessionId:"",...D?{callId:D}:{},threadId:Y.threadId??G??"",reason:"start_failed",startedAt:H,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)}},B=Y.threadId??G;if(!B)return await z(void 0),M(400,{code:"invalid_request",message:"A voice session needs a thread: send `threadId`, or answer one from `voice.start`."});try{if(B!==G)await this.authorizeRequest(J,{route:"stream",threadId:B,body:X})}catch(L){throw await z(void 0),L}let U=crypto.randomUUID(),N=Y.tools??[];try{if(Y.mcp)N=[...N,...await v$(Y.mcp,{user:V,sessionId:U})]}catch(L){return await z(L),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}let F={...Y.session,tools:[...HJ($.delegate),...Y.session?.tools??[],...N.map((L)=>L.tool)],...K===!0?{turnDetection:null}:{}},P;try{P=await $.realtime.createCall({sdp:Z,session:F,safetyIdentifier:Y.safetyIdentifier})}catch(L){await z(L);let O=L instanceof f&&L.code==="rate_limited";return M(O?429:502,{code:"voice_unavailable",message:"Voice isn't available right now."})}D=P.callId;try{await this.voiceStore.create({id:U,callId:P.callId,threadId:B,owner:await this.runOwner(J),body:X,startedAt:H});let{threadId:L,session:O,safetyIdentifier:j,mcp:k,tools:I,...x}=Y;return{sessionId:p.start({...x,tools:N,controller:this.constructor,threadId:B,user:V,body:X,call:{realtime:$.realtime,callId:P.callId},sessionId:U,store:this.voiceStore,liveRuns:this.liveRuns,delegate:$.delegate,session:F}).sessionId,sdp:P.sdpAnswer,threadId:B,delegate:$.delegate?.name??zJ,endsAt:H+(Y.limits?.maxDurationMs??900000)}}catch(L){return await z(L),M(500,{code:"voice_unavailable",message:"Voice isn't available right now."})}}async voiceUpdate(J=new q){if(!this.voice)return s$();let $=await this.voiceSession(J);if($ instanceof Response)return $;let Q=await PJ(J,pJ);if(Q.error)return JJ(Q);let Z=dJ(Q.body,[]);if(await this.authorizeRequest(J,{route:"stream",threadId:$.threadId,body:Z}),$.endedAt!==void 0)return M(409,{code:"voice_ended",message:"This voice session has ended."});return await this.voiceStore.update($.id,{body:Z}),p.get($.id)?.setBody(Z),{updated:!0}}async voiceEnd(J=new q){let $=this.voice;if(!$)return s$();let Q=await this.voiceSession(J);if(Q instanceof Response)return Q;if(await this.authorizeRequest(J,{route:"stream",threadId:Q.threadId,body:Q.body}),Q.endedAt!==void 0)return{ended:!1};let Z=p.get(Q.id);if(Z)await Z.end("hangup");else await $.realtime.hangup(Q.callId),await this.voiceStore.update(Q.id,{endedAt:Date.now(),endReason:"hangup"});return{ended:!0}}async voiceSession(J){let $=J.params?.sessionId,Q=typeof $==="string"&&$?await this.voiceStore.get($):null;if(!Q)return M(404,{code:"voice_not_found",message:"No such voice session."});if(Q.owner!==null&&Q.owner!==await this.runOwner(J))return NJ();return Q}async upload(J=new q){let $=await J.rawRequest.formData(),Q=$.get("file");if(!(Q instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let Z=Q instanceof File&&Q.name?Q.name:"upload",W=Q.type||"application/octet-stream",K=R0($.get("body")),X=$.get("threadId");await this.authorizeRequest(J,{route:"upload",threadId:typeof X==="string"&&X.length>0?X:void 0,body:K});let G=T0(await this.attachmentLimits(J),Q,Z,W);if(G)throw new r$(G.code,G.message);let V=typeof X==="string"&&X.length>0&&await this.store.loadThread(X)!==null?X:void 0,Y=await this.runOwner(J),H=(k)=>this.fileOwners.record(k,{owner:Y,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString()}),D={body:K,threadId:V},z=await this.checkUpload({name:Z,size:Q.size,mimeType:W},J,D);if(z)throw new r$(z.code||"upload_refused",z.message);let B=await this.attachmentDestination(Q,J,D),U=g0(B,$.get("destination")),N=await this.attachmentScope(J,V,{body:K}),F=U!=="provider"&&!N;if(F){if(U==="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()`.');u0()}if(U==="provider"||!N){let k=await WQ(this.agent.provider,Q);await H(k);let I={fileId:k,name:Z,mimeType:W,size:Q.size,destination:"provider"};if(F)I.downgraded="no_scope";return I}let P=_Q(),L=await this.attachmentStorage.put({name:MQ(P,Z),body:Q,contentType:W}),O=U==="both"?await WQ(this.agent.provider,Q):void 0;if(O)await H(O);let j={id:P,scopeKey:N.key,fileId:O,objectName:L,name:Z,mimeType:W,size:Q.size,createdAt:new Date().toISOString(),destination:U};return await this.attachments.put(N,j),{fileId:O,attachmentId:P,name:Z,mimeType:W,size:Q.size,destination:U}}async foreignFile(J,$){let Q=new Set(J.map((Z)=>Z.fileId).filter((Z)=>typeof Z==="string"));for(let Z of Q){let W=await this.fileOwners.get(Z);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return v0()}return null}onMessage(J,$){return this.hooks?.onMessage?.(J,$)}onToolCall(J,$){return this.hooks?.onToolCall?.(J,$)}onToolResult(J,$,Q){return this.hooks?.onToolResult?.(J,$,Q)}onAwaitingInput(J,$){return this.hooks?.onAwaitingInput?.(J,$)}redactError(J,$,Q){let Z=this.hooks?.redactError;if(Z)return Z(J,$,Q);return Q8(J,$)}onError(J,$){return this.hooks?.onError?.(J,$)}onStreamComplete(J,$){return this.hooks?.onStreamComplete?.(J,$)}reportHookFailure(J){let $=this.hooks?.reportHookFailure;if($)try{return $(J)}catch(Q){console.error("[gemi/ai] reportHookFailure hook failed",Q)}console.error("[gemi/ai] agent controller hook failed",J)}async dispatchEvent(J,$){switch(J.type){case"tool-call":if(!J.part.partial&&!J.resent)await this.onToolCall({toolCallId:J.part.toolCallId,name:String(J.part.name),input:J.part.input},$);return;case"tool-result":{let Q=J.part;await this.onToolResult(Q,$,{toolCallId:Q.toolCallId,name:String(Q.name),input:EQ(Q)});return}case"awaiting-input":await this.onAwaitingInput(J.pending,$);return;case"error":await this.onError(LQ(J.error),$);return;default:return}}async readThread(J){let $=await this.store.loadThread(J);return $?(await this.settleThread(J,$,{write:!1})).messages:null}isRunLive(J,$){return this.liveRuns.get(J)!==null}async settleThread(J,$,{write:Q}){let Z=(V)=>this.isRunLive(V,J),W=await s9($,Z),K=W.messages,X=[],G=new Map(W.settled.map((V)=>[V.id,V]));if(l0(K)||Q)try{let V=await e9(K,{threadId:J,store:v.store,isRunLive:Z,outputSchemaFor:(Y)=>this.toolNamed(Y)?.outputSchema,modelOutputFor:(Y,H)=>RQ(this.toolNamed(Y),H,(D)=>this.reportHookFailure(D)),scan:this.jobsBlockMax()});K=V.messages,X=V.jobs;for(let Y of V.settled)G.set(Y.id,Y);if(Q&&V.orphans.length>0){await JQ(v.store,V.orphans,(H)=>this.reportHookFailure(H));let Y=new Set(V.orphans.map((H)=>H.id));X=X.map((H)=>Y.has(H.id)?{...H,orphaned:!0}:H)}}catch(V){this.reportHookFailure(V)}if(Q&&G.size>0)try{await this.store.appendMessages(J,[...G.values()])}catch(V){this.reportHookFailure(V)}return{messages:K,jobs:X}}jobsBlockMax(){let J=this.agent.jobs?.contextBlock;if(J===!1)return 0;return J?.max??CJ}jobsBlock(J){return F8(J,this.jobsBlockMax())}toolNamed(J){let $=(Q)=>{for(let Z of Q){let W=Z;if(Array.isArray(W.tools)){let K=$(W.tools);if(K)return K}else if(W.name===J)return W}return};return $(this.agent.tools??[])}follow(J,$){(async()=>{try{for await(let Q of J.frames())$.frame(Q)}catch(Q){this.reportHookFailure(Q)}})()}persistRun(J,$,Q,Z=null,W={id:null,notified:Promise.resolve()}){let K=Promise.resolve(),X=(async()=>{let V;try{V=await J.result()}catch(H){Z?.close(),await Z?.settled(),K=W.notified.then(()=>this.safely(()=>this.onError({code:"unknown",message:H instanceof Error?H.message:String(H),retryable:!1},$)));return}let Y=V.messages;if(Z?.close(Y),await Z?.settled(),$.threadId&&Y.length>0)try{await this.store.appendMessages($.threadId,Y)}catch(H){this.reportHookFailure(H)}K=this.notifyRun(V,Y,$,W)})(),G=X.then(()=>m0(Promise.all([K,Q]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:G}}async notifyRun(J,$,Q,Z){await Z.notified;for(let W of $){if(W.id===Z.id)continue;await this.safely(()=>this.onMessage(W,Q))}await this.safely(()=>this.onStreamComplete(J,Q))}async safely(J){try{await J()}catch($){this.reportHookFailure($)}}}var a$=["turn","clientRunId","threadId","messages","regenerate"],A0=["text","files","toolResults"];function dJ(J,$=kQ(J)?a$:[...a$,...A0]){let Q={};for(let[Z,W]of Object.entries(J)){if($.includes(Z))continue;Object.defineProperty(Q,Z,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Q}function R0(J){if(J===null)return{};let $;if(typeof J==="string")try{$=JSON.parse(J)}catch{throw new t$("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new t$("The upload's `body` field must be a JSON object.");return dJ($,a$)}class t$ extends iJ{constructor(J){super(J);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:J}}},view:{}}}}async function WQ(J,$){try{return await J.upload($)}catch(Q){if(Q instanceof w&&E0.has(Q.status))throw new jQ(T(Q).message);throw Q}}var E0=new Set([400,413,415,422]);class r$ extends iJ{constructor(J,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:J,message:$}}},view:{}}}}function T0(J,$,Q,Z){if(!J)return null;let{maxBytes:W,accept:K}=J;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Q)} is ${KQ($.size)}; the limit is ${KQ(W)}.`};if(K&&K.length>0&&!K.some((X)=>j0(X,Q,Z)))return{code:"unsupported_file_type",message:`${JSON.stringify(Q)} is not a type this chat accepts. Accepted: ${K.join(", ")}.`};return null}function j0(J,$,Q){let Z=J.trim().toLowerCase();if(!Z)return!1;if(Z.startsWith("."))return $.toLowerCase().endsWith(Z);let W=Q.toLowerCase().split(";")[0].trim();if(Z.endsWith("/*"))return W.startsWith(Z.slice(0,-1));return W===Z}function KQ(J){if(J<1024)return`${J} B`;let $=["KB","MB","GB"],Q=J/1024,Z=0;while(Q>=1024&&Z<$.length-1)Q/=1024,Z++;return`${Math.round(Q*10)/10} ${$[Z]}`}class jQ extends iJ{constructor(J){super(J);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(J)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:J}}},view:{}}}}async function PJ(J,$){let Q=J?.rawRequest;if(!Q||Q.method==="GET"||Q.method==="HEAD"||!Q.body)return{body:{}};if(!k0(Q.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(Q.headers.get("Content-Length"));if(Number.isFinite(Z)&&Z>$)return XQ($);let W;try{let X=await x0(Q,$);if(X===null)return XQ($);W=X}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let K;try{K=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(K===null||typeof K!=="object"||Array.isArray(K))return{body:{},error:"The request body must be a JSON object."};return{body:K}}function k0(J){return BQ(J)==="application/json"}async function x0(J,$){if(!Number.isFinite($)||!J.body)return await J.text();let Q=J.body.getReader(),Z=[],W=0;for(;;){let{done:G,value:V}=await Q.read();if(G)break;if(W+=V.byteLength,W>$)return await Q.cancel().catch(lJ),null;Z.push(V)}let K=new Uint8Array(W),X=0;for(let G of Z)K.set(G,X),X+=G.byteLength;return new TextDecoder().decode(K)}function XQ(J){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${J} bytes).`}}function e$(J,$,Q){return M(J,{...nJ(DQ(J),Q,J),code:$})}function JJ(J){if(J.status===413)return e$(413,J.code??"body_too_large",J.error??"");return M(J.status??400,{code:J.code??"invalid_request",message:J.error})}function kQ(J){return Boolean(J.turn)&&typeof J.turn==="object"}function q0(J){let $=kQ(J)?J.turn:J,Q={};if(typeof $.text==="string")Q.text=$.text;if(Array.isArray($.files)){let Z=I0($.files);if(typeof Z==="string")return{error:Z};Q.files=Z}if(Array.isArray($.toolResults))Q.toolResults=$.toolResults;if(Object.keys(Q).length===0)return{};if($===J.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:Z}=$;if(typeof Z!=="string")return{error:"turn.localId must be a string."};if(Z.length>YQ)return{error:`turn.localId is longer than ${YQ} characters.`};Q.localId=Z}return{turn:Q}}var YQ=200;function I0(J){let $=[];for(let[Q,Z]of J.entries()){let W=`turn.files[${Q}]`;if(!Z||typeof Z!=="object"||Array.isArray(Z))return`${W} must be an object.`;let K={};for(let H of["fileId","attachmentId","name","mimeType"]){let D=Z[H];if(D===void 0||D===null||D==="")continue;if(typeof D!=="string")return`${W}.${H} must be a string.`;K[H]=D}let{fileId:X,attachmentId:G,name:V,mimeType:Y}=K;if(X?.startsWith(m))return`${W}.fileId holds a gemi attachment id (${X}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(G!==void 0&&!G.startsWith(m))return`${W}.attachmentId is not a gemi attachment id: it must start with "${m}".`;if(!X&&!G)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...X?{fileId:X}:{},...G?{attachmentId:G}:{},...V!==void 0?{name:V}:{},...Y!==void 0?{mimeType:Y}:{}})}return $}function w0(J,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let Z=Math.floor($.cursor);if(Z>=0)return Z+1;return}let Q=J?.rawRequest?.headers?.get("Last-Event-ID");if(Q){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function b0(J,$){let Q=J?.search?.get($);return typeof Q==="string"?Q:void 0}function f0(J){let $=Z8(J);for(let Q=J.length-1;Q>=0;Q--){let Z=J[Q];if(Z.role!=="user"||$.has(Z.id))continue;let W="",K=[];for(let X of Z.content){if(X.type==="text")W+=X.text;if(X.type==="file")K.push({...X.fileId?{fileId:X.fileId}:{},...X.attachmentId?{attachmentId:X.attachmentId}:{},...X.name?{name:X.name}:{},...X.mimeType?{mimeType:X.mimeType}:{}})}if(!W&&K.length===0)continue;return{index:Q,turn:{...W?{text:W}:{},...K.length>0?{files:K}:{}}}}return null}function GQ(){return M(409,{code:"stopped",message:"The turn was stopped before it started."})}function NJ(){return M(403,nJ("permission","This run belongs to someone else.",403))}function v0(){return M(403,nJ("permission","A file in this turn was uploaded by someone else.",403))}function y0(J){if(!Array.isArray(J))return[];let $=[];for(let Q of J){let Z=Q?.content;if(!Array.isArray(Z))continue;for(let W of Z)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}var h0=["sdp","threadId","pushToTalk"];function s$(){return M(404,{code:"voice_not_enabled",message:"This agent has no voice: set `voice` on its controller."})}function M(J,$){return new Response(JSON.stringify({error:$}),{status:J,headers:{"Content-Type":"application/json"}})}function g0(J,$){if(typeof $!=="string"||$.length===0)return J;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===J||J==="both"&&$==="storage")return $;if(J==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${J}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var VQ=!1;function u0(){if(VQ)return;VQ=!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 c0=2147483647;function m0(J,$){let Q=J.then(()=>{},()=>{});if(!($<=c0))return Q;let Z,W=new Promise((K)=>{Z=setTimeout(K,$)});return Promise.race([Q,W]).finally(()=>clearTimeout(Z))}var HQ=!1;function p0(J){if(HQ||Bun.env.NODE_ENV!=="production")return;if(!(J instanceof J8))return;HQ=!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 l0(J){return J.some(($)=>$.content.some((Q)=>Q.type==="tool-result"&&Q.status==="running"))}export{J6 as windowMessages,HJ as voiceTools,s0 as turnStarts,qJ as toRealtimeUsage,eQ as toAgentTools,n0 as supportsStrict,a0 as splitTurns,Y6 as settleSummaries,i0 as s,Q8 as redactError,t0 as messageSize,KJ as measureUsage,v$ as mcpVoiceTools,u$ as liveRuns,DJ as keepSummary,A9 as isCallNotFound,Z8 as injectedMessageIds,z$ as generate,nZ as evalChain,S0 as defineAgentHooks,h$ as defaultVoiceStore,X6 as defaultSummaryStore,$8 as defaultNonceStore,c$ as defaultFileOwners,sJ as defaultAttachmentStore,i$ as defaultAgentStore,yJ as VoiceHangup,p as VoiceBridge,o0 as Usage,B$ as ToolNamespace,g as ToolError,V6 as Skill,oJ as ScopedAttachments,H6 as SKILLS_NAMESPACE,d$ as RedisReceiptStore,NQ as RedisNonceStore,IJ as RealtimeSideband,f as RealtimeRequestError,GJ as RealtimeClient,z8 as Prompt,UQ as PrismaNonceStore,G6 as PendingEscalation,I$ as OpenAIProvider,L$ as OpenAIImageProvider,y$ as MemoryVoiceSessionStore,K6 as MemorySummaryStore,l$ as MemoryReceiptStore,J8 as MemoryNonceStore,hJ as MemoryLiveRuns,gJ as MemoryFileOwners,fJ as MemoryCircuitStore,SQ as MemoryAttachmentStore,uJ as MemoryAgentStore,U8 as MemoryAgentJobStore,b8 as MEMORY_NAMESPACE,BJ as LiveRunNotFoundError,O8 as JobsRequireThreadError,L8 as JobHandle,d0 as JSONSchemaError,CQ as InvalidAttachmentScopeError,j8 as InMemoryAgentMemoryStore,jJ as ImageRequestError,kJ as ImageProvider,F$ as ImageModel,e as FrameCursorEvictedError,VJ as FallbackProvider,I8 as FakeAgentMemoryStore,RJ as Eval,h9 as DatabaseAgentStore,K$ as DatabaseAgentMemoryStore,Z$ as DatabaseAgentJobStore,M9 as DEFAULT_TRANSCRIPTION_MODEL,T8 as DEFAULT_MEMORY_MAX_TOKENS,w8 as DEFAULT_MEMORY_LIMITS,$6 as DEFAULT_MAX_SUMMARY_TOKENS,z6 as DEFAULT_MAX_RUN_DURATION_MS,C8 as DEFAULT_JOB_DEADLINE_MS,CJ as DEFAULT_JOBS_CONTEXT_MAX,zJ as DEFAULT_DELEGATE_NAME,r0 as DEFAULT_CONTEXT_WINDOW_STEP,e0 as DEFAULT_CONTEXT_WINDOW_NOTE,Q6 as DEFAULT_COMPACT_TRIGGER_TOKENS,Z6 as DEFAULT_COMPACT_INSTRUCTIONS,W6 as COMPACT_SUMMARY_HEADER,w$ as AzureOpenAIProvider,O$ as AzureOpenAIImageProvider,OQ as AttachmentNotFoundError,aJ as AgentTurnError,EJ as AgentTool,D6 as AgentRunError,r as AgentProvider,k8 as AgentMemoryRefusedError,x8 as AgentMemoryConflictError,q8 as AgentMemories,v as AgentJobs,J$ as AgentJobDeadlineSweep,_8 as AgentJob,W8 as AgentController,B6 as Agent};
|
|
243
243
|
|
|
244
|
-
//# debugId=
|
|
244
|
+
//# debugId=BC2F53030F49461164756E2164756E21
|